id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
16,400
prograils/lit
lib/lit/import.rb
Lit.Import.upsert
def upsert(locale, key, value) # rubocop:disable Metrics/MethodLength I18n.with_locale(locale) do # when an array has to be inserted with a default value, it needs to # be done like: # I18n.t('foo', default: [['bar', 'baz']]) # because without the double array, array items are treated as fallback keys # - then, the last array element is the final fallback; so in this case we # don't specify fallback keys and only specify the final fallback, which # is the array val = value.is_a?(Array) ? [value] : value I18n.t(key, default: val) unless @raw # this indicates that this translation already exists existing_translation = Lit::Localization.joins(:locale, :localization_key) .find_by('localization_key = ? and locale = ?', key, locale) if existing_translation existing_translation.update(translated_value: value, is_changed: true) lkey = existing_translation.localization_key lkey.update(is_deleted: false) if lkey.is_deleted end end end end
ruby
def upsert(locale, key, value) # rubocop:disable Metrics/MethodLength I18n.with_locale(locale) do # when an array has to be inserted with a default value, it needs to # be done like: # I18n.t('foo', default: [['bar', 'baz']]) # because without the double array, array items are treated as fallback keys # - then, the last array element is the final fallback; so in this case we # don't specify fallback keys and only specify the final fallback, which # is the array val = value.is_a?(Array) ? [value] : value I18n.t(key, default: val) unless @raw # this indicates that this translation already exists existing_translation = Lit::Localization.joins(:locale, :localization_key) .find_by('localization_key = ? and locale = ?', key, locale) if existing_translation existing_translation.update(translated_value: value, is_changed: true) lkey = existing_translation.localization_key lkey.update(is_deleted: false) if lkey.is_deleted end end end end
[ "def", "upsert", "(", "locale", ",", "key", ",", "value", ")", "# rubocop:disable Metrics/MethodLength", "I18n", ".", "with_locale", "(", "locale", ")", "do", "# when an array has to be inserted with a default value, it needs to", "# be done like:", "# I18n.t('foo', default: [['bar', 'baz']])", "# because without the double array, array items are treated as fallback keys", "# - then, the last array element is the final fallback; so in this case we", "# don't specify fallback keys and only specify the final fallback, which", "# is the array", "val", "=", "value", ".", "is_a?", "(", "Array", ")", "?", "[", "value", "]", ":", "value", "I18n", ".", "t", "(", "key", ",", "default", ":", "val", ")", "unless", "@raw", "# this indicates that this translation already exists", "existing_translation", "=", "Lit", "::", "Localization", ".", "joins", "(", ":locale", ",", ":localization_key", ")", ".", "find_by", "(", "'localization_key = ? and locale = ?'", ",", "key", ",", "locale", ")", "if", "existing_translation", "existing_translation", ".", "update", "(", "translated_value", ":", "value", ",", "is_changed", ":", "true", ")", "lkey", "=", "existing_translation", ".", "localization_key", "lkey", ".", "update", "(", "is_deleted", ":", "false", ")", "if", "lkey", ".", "is_deleted", "end", "end", "end", "end" ]
This is mean to insert a value for a key in a given locale using some kind of strategy which depends on the service's options. For instance, when @raw option is true (it's the default), if a key already exists, it overrides the default_value of the existing localization key; otherwise, with @raw set to false, it keeps the default as it is and, no matter if a translated value is there, translated_value is overridden with the imported one and is_changed is set to true.
[ "This", "is", "mean", "to", "insert", "a", "value", "for", "a", "key", "in", "a", "given", "locale", "using", "some", "kind", "of", "strategy", "which", "depends", "on", "the", "service", "s", "options", "." ]
a230cb450694848834c1afb9f26d5c24bc54e68e
https://github.com/prograils/lit/blob/a230cb450694848834c1afb9f26d5c24bc54e68e/lib/lit/import.rb#L128-L152
16,401
norman/babosa
lib/babosa/identifier.rb
Babosa.Identifier.transliterate!
def transliterate!(*kinds) kinds.compact! kinds = [:latin] if kinds.empty? kinds.each do |kind| transliterator = Transliterator.get(kind).instance @wrapped_string = transliterator.transliterate(@wrapped_string) end @wrapped_string end
ruby
def transliterate!(*kinds) kinds.compact! kinds = [:latin] if kinds.empty? kinds.each do |kind| transliterator = Transliterator.get(kind).instance @wrapped_string = transliterator.transliterate(@wrapped_string) end @wrapped_string end
[ "def", "transliterate!", "(", "*", "kinds", ")", "kinds", ".", "compact!", "kinds", "=", "[", ":latin", "]", "if", "kinds", ".", "empty?", "kinds", ".", "each", "do", "|", "kind", "|", "transliterator", "=", "Transliterator", ".", "get", "(", "kind", ")", ".", "instance", "@wrapped_string", "=", "transliterator", ".", "transliterate", "(", "@wrapped_string", ")", "end", "@wrapped_string", "end" ]
Approximate an ASCII string. This works only for Western strings using characters that are Roman-alphabet characters + diacritics. Non-letter characters are left unmodified. string = Identifier.new "Łódź string.transliterate # => "Lodz, Poland" string = Identifier.new "日本" string.transliterate # => "日本" You can pass any key(s) from +Characters.approximations+ as arguments. This allows for contextual approximations. Various languages are supported, you can see which ones by looking at the source of {Babosa::Transliterator::Base}. string = Identifier.new "Jürgen Müller" string.transliterate # => "Jurgen Muller" string.transliterate :german # => "Juergen Mueller" string = Identifier.new "¡Feliz año!" string.transliterate # => "¡Feliz ano!" string.transliterate :spanish # => "¡Feliz anio!" The approximations are an array, which you can modify if you choose: # Make Spanish use "nh" rather than "nn" Babosa::Transliterator::Spanish::APPROXIMATIONS["ñ"] = "nh" Notice that this method does not simply convert to ASCII; if you want to remove non-ASCII characters such as "¡" and "¿", use {#to_ascii!}: string.transliterate!(:spanish) # => "¡Feliz anio!" string.transliterate! # => "¡Feliz anio!" @param *args <Symbol> @return String
[ "Approximate", "an", "ASCII", "string", ".", "This", "works", "only", "for", "Western", "strings", "using", "characters", "that", "are", "Roman", "-", "alphabet", "characters", "+", "diacritics", ".", "Non", "-", "letter", "characters", "are", "left", "unmodified", "." ]
29f6057dac9016171e7e82c51d85e2fb5e6e5fbe
https://github.com/norman/babosa/blob/29f6057dac9016171e7e82c51d85e2fb5e6e5fbe/lib/babosa/identifier.rb#L118-L126
16,402
norman/babosa
lib/babosa/identifier.rb
Babosa.Identifier.to_ruby_method!
def to_ruby_method!(allow_bangs = true) leader, trailer = @wrapped_string.strip.scan(/\A(.+)(.)\z/).flatten leader = leader.to_s trailer = trailer.to_s if allow_bangs trailer.downcase! trailer.gsub!(/[^a-z0-9!=\\?]/, '') else trailer.downcase! trailer.gsub!(/[^a-z0-9]/, '') end id = leader.to_identifier id.transliterate! id.to_ascii! id.clean! id.word_chars! id.clean! @wrapped_string = id.to_s + trailer if @wrapped_string == "" raise Error, "Input generates impossible Ruby method name" end with_separators!("_") end
ruby
def to_ruby_method!(allow_bangs = true) leader, trailer = @wrapped_string.strip.scan(/\A(.+)(.)\z/).flatten leader = leader.to_s trailer = trailer.to_s if allow_bangs trailer.downcase! trailer.gsub!(/[^a-z0-9!=\\?]/, '') else trailer.downcase! trailer.gsub!(/[^a-z0-9]/, '') end id = leader.to_identifier id.transliterate! id.to_ascii! id.clean! id.word_chars! id.clean! @wrapped_string = id.to_s + trailer if @wrapped_string == "" raise Error, "Input generates impossible Ruby method name" end with_separators!("_") end
[ "def", "to_ruby_method!", "(", "allow_bangs", "=", "true", ")", "leader", ",", "trailer", "=", "@wrapped_string", ".", "strip", ".", "scan", "(", "/", "\\A", "\\z", "/", ")", ".", "flatten", "leader", "=", "leader", ".", "to_s", "trailer", "=", "trailer", ".", "to_s", "if", "allow_bangs", "trailer", ".", "downcase!", "trailer", ".", "gsub!", "(", "/", "\\\\", "/", ",", "''", ")", "else", "trailer", ".", "downcase!", "trailer", ".", "gsub!", "(", "/", "/", ",", "''", ")", "end", "id", "=", "leader", ".", "to_identifier", "id", ".", "transliterate!", "id", ".", "to_ascii!", "id", ".", "clean!", "id", ".", "word_chars!", "id", ".", "clean!", "@wrapped_string", "=", "id", ".", "to_s", "+", "trailer", "if", "@wrapped_string", "==", "\"\"", "raise", "Error", ",", "\"Input generates impossible Ruby method name\"", "end", "with_separators!", "(", "\"_\"", ")", "end" ]
Normalize a string so that it can safely be used as a Ruby method name.
[ "Normalize", "a", "string", "so", "that", "it", "can", "safely", "be", "used", "as", "a", "Ruby", "method", "name", "." ]
29f6057dac9016171e7e82c51d85e2fb5e6e5fbe
https://github.com/norman/babosa/blob/29f6057dac9016171e7e82c51d85e2fb5e6e5fbe/lib/babosa/identifier.rb#L167-L189
16,403
norman/babosa
lib/babosa/identifier.rb
Babosa.Identifier.truncate_bytes!
def truncate_bytes!(max) return @wrapped_string if @wrapped_string.bytesize <= max curr = 0 new = [] unpack("U*").each do |char| break if curr > max char = [char].pack("U") curr += char.bytesize if curr <= max new << char end end @wrapped_string = new.join end
ruby
def truncate_bytes!(max) return @wrapped_string if @wrapped_string.bytesize <= max curr = 0 new = [] unpack("U*").each do |char| break if curr > max char = [char].pack("U") curr += char.bytesize if curr <= max new << char end end @wrapped_string = new.join end
[ "def", "truncate_bytes!", "(", "max", ")", "return", "@wrapped_string", "if", "@wrapped_string", ".", "bytesize", "<=", "max", "curr", "=", "0", "new", "=", "[", "]", "unpack", "(", "\"U*\"", ")", ".", "each", "do", "|", "char", "|", "break", "if", "curr", ">", "max", "char", "=", "[", "char", "]", ".", "pack", "(", "\"U\"", ")", "curr", "+=", "char", ".", "bytesize", "if", "curr", "<=", "max", "new", "<<", "char", "end", "end", "@wrapped_string", "=", "new", ".", "join", "end" ]
Truncate the string to +max+ bytes. This can be useful for ensuring that a UTF-8 string will always fit into a database column with a certain max byte length. The resulting string may be less than +max+ if the string must be truncated at a multibyte character boundary. @example "üéøá".to_identifier.truncate_bytes(3) #=> "ü" @return String
[ "Truncate", "the", "string", "to", "+", "max", "+", "bytes", ".", "This", "can", "be", "useful", "for", "ensuring", "that", "a", "UTF", "-", "8", "string", "will", "always", "fit", "into", "a", "database", "column", "with", "a", "certain", "max", "byte", "length", ".", "The", "resulting", "string", "may", "be", "less", "than", "+", "max", "+", "if", "the", "string", "must", "be", "truncated", "at", "a", "multibyte", "character", "boundary", "." ]
29f6057dac9016171e7e82c51d85e2fb5e6e5fbe
https://github.com/norman/babosa/blob/29f6057dac9016171e7e82c51d85e2fb5e6e5fbe/lib/babosa/identifier.rb#L212-L225
16,404
norman/babosa
lib/babosa/identifier.rb
Babosa.Identifier.send_to_new_instance
def send_to_new_instance(*args) id = Identifier.allocate id.instance_variable_set :@wrapped_string, to_s id.send(*args) id end
ruby
def send_to_new_instance(*args) id = Identifier.allocate id.instance_variable_set :@wrapped_string, to_s id.send(*args) id end
[ "def", "send_to_new_instance", "(", "*", "args", ")", "id", "=", "Identifier", ".", "allocate", "id", ".", "instance_variable_set", ":@wrapped_string", ",", "to_s", "id", ".", "send", "(", "args", ")", "id", "end" ]
Used as the basis of the bangless methods.
[ "Used", "as", "the", "basis", "of", "the", "bangless", "methods", "." ]
29f6057dac9016171e7e82c51d85e2fb5e6e5fbe
https://github.com/norman/babosa/blob/29f6057dac9016171e7e82c51d85e2fb5e6e5fbe/lib/babosa/identifier.rb#L286-L291
16,405
mattsears/nyan-cat-formatter
lib/nyan_cat_formatter/common.rb
NyanCat.Common.nyan_cat
def nyan_cat if self.failed_or_pending? && self.finished? ascii_cat('x')[@color_index%2].join("\n") #'~|_(x.x)' elsif self.failed_or_pending? ascii_cat('o')[@color_index%2].join("\n") #'~|_(o.o)' elsif self.finished? ascii_cat('-')[@color_index%2].join("\n") # '~|_(-.-)' else ascii_cat('^')[@color_index%2].join("\n") # '~|_(^.^)' end end
ruby
def nyan_cat if self.failed_or_pending? && self.finished? ascii_cat('x')[@color_index%2].join("\n") #'~|_(x.x)' elsif self.failed_or_pending? ascii_cat('o')[@color_index%2].join("\n") #'~|_(o.o)' elsif self.finished? ascii_cat('-')[@color_index%2].join("\n") # '~|_(-.-)' else ascii_cat('^')[@color_index%2].join("\n") # '~|_(^.^)' end end
[ "def", "nyan_cat", "if", "self", ".", "failed_or_pending?", "&&", "self", ".", "finished?", "ascii_cat", "(", "'x'", ")", "[", "@color_index", "%", "2", "]", ".", "join", "(", "\"\\n\"", ")", "#'~|_(x.x)'", "elsif", "self", ".", "failed_or_pending?", "ascii_cat", "(", "'o'", ")", "[", "@color_index", "%", "2", "]", ".", "join", "(", "\"\\n\"", ")", "#'~|_(o.o)'", "elsif", "self", ".", "finished?", "ascii_cat", "(", "'-'", ")", "[", "@color_index", "%", "2", "]", ".", "join", "(", "\"\\n\"", ")", "# '~|_(-.-)'", "else", "ascii_cat", "(", "'^'", ")", "[", "@color_index", "%", "2", "]", ".", "join", "(", "\"\\n\"", ")", "# '~|_(^.^)'", "end", "end" ]
Determine which Ascii Nyan Cat to display. If tests are complete, Nyan Cat goes to sleep. If there are failing or pending examples, Nyan Cat is concerned. @return [String] Nyan Cat
[ "Determine", "which", "Ascii", "Nyan", "Cat", "to", "display", ".", "If", "tests", "are", "complete", "Nyan", "Cat", "goes", "to", "sleep", ".", "If", "there", "are", "failing", "or", "pending", "examples", "Nyan", "Cat", "is", "concerned", "." ]
54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1
https://github.com/mattsears/nyan-cat-formatter/blob/54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1/lib/nyan_cat_formatter/common.rb#L48-L58
16,406
mattsears/nyan-cat-formatter
lib/nyan_cat_formatter/common.rb
NyanCat.Common.terminal_width
def terminal_width if defined? JRUBY_VERSION default_width = 80 else default_width = `stty size`.split.map { |x| x.to_i }.reverse.first - 1 end @terminal_width ||= default_width end
ruby
def terminal_width if defined? JRUBY_VERSION default_width = 80 else default_width = `stty size`.split.map { |x| x.to_i }.reverse.first - 1 end @terminal_width ||= default_width end
[ "def", "terminal_width", "if", "defined?", "JRUBY_VERSION", "default_width", "=", "80", "else", "default_width", "=", "`", "`", ".", "split", ".", "map", "{", "|", "x", "|", "x", ".", "to_i", "}", ".", "reverse", ".", "first", "-", "1", "end", "@terminal_width", "||=", "default_width", "end" ]
A Unix trick using stty to get the console columns @return [Fixnum]
[ "A", "Unix", "trick", "using", "stty", "to", "get", "the", "console", "columns" ]
54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1
https://github.com/mattsears/nyan-cat-formatter/blob/54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1/lib/nyan_cat_formatter/common.rb#L103-L110
16,407
mattsears/nyan-cat-formatter
lib/nyan_cat_formatter/common.rb
NyanCat.Common.scoreboard
def scoreboard @pending_examples ||= [] @failed_examples ||= [] padding = @example_count.to_s.length [ @current.to_s.rjust(padding), success_color((@current - @pending_examples.size - @failed_examples.size).to_s.rjust(padding)), pending_color(@pending_examples.size.to_s.rjust(padding)), failure_color(@failed_examples.size.to_s.rjust(padding)) ] end
ruby
def scoreboard @pending_examples ||= [] @failed_examples ||= [] padding = @example_count.to_s.length [ @current.to_s.rjust(padding), success_color((@current - @pending_examples.size - @failed_examples.size).to_s.rjust(padding)), pending_color(@pending_examples.size.to_s.rjust(padding)), failure_color(@failed_examples.size.to_s.rjust(padding)) ] end
[ "def", "scoreboard", "@pending_examples", "||=", "[", "]", "@failed_examples", "||=", "[", "]", "padding", "=", "@example_count", ".", "to_s", ".", "length", "[", "@current", ".", "to_s", ".", "rjust", "(", "padding", ")", ",", "success_color", "(", "(", "@current", "-", "@pending_examples", ".", "size", "-", "@failed_examples", ".", "size", ")", ".", "to_s", ".", "rjust", "(", "padding", ")", ")", ",", "pending_color", "(", "@pending_examples", ".", "size", ".", "to_s", ".", "rjust", "(", "padding", ")", ")", ",", "failure_color", "(", "@failed_examples", ".", "size", ".", "to_s", ".", "rjust", "(", "padding", ")", ")", "]", "end" ]
Creates a data store of pass, failed, and pending example results We have to pad the results here because sprintf can't properly pad color @return [Array]
[ "Creates", "a", "data", "store", "of", "pass", "failed", "and", "pending", "example", "results", "We", "have", "to", "pad", "the", "results", "here", "because", "sprintf", "can", "t", "properly", "pad", "color" ]
54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1
https://github.com/mattsears/nyan-cat-formatter/blob/54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1/lib/nyan_cat_formatter/common.rb#L116-L124
16,408
mattsears/nyan-cat-formatter
lib/nyan_cat_formatter/common.rb
NyanCat.Common.nyan_trail
def nyan_trail marks = @example_results.each_with_index.map{ |mark, i| highlight(mark) * example_width(i) } marks.shift(current_width - terminal_width) if current_width >= terminal_width nyan_cat.split("\n").each_with_index.map do |line, index| format("%s#{line}", marks.join) end.join("\n") end
ruby
def nyan_trail marks = @example_results.each_with_index.map{ |mark, i| highlight(mark) * example_width(i) } marks.shift(current_width - terminal_width) if current_width >= terminal_width nyan_cat.split("\n").each_with_index.map do |line, index| format("%s#{line}", marks.join) end.join("\n") end
[ "def", "nyan_trail", "marks", "=", "@example_results", ".", "each_with_index", ".", "map", "{", "|", "mark", ",", "i", "|", "highlight", "(", "mark", ")", "*", "example_width", "(", "i", ")", "}", "marks", ".", "shift", "(", "current_width", "-", "terminal_width", ")", "if", "current_width", ">=", "terminal_width", "nyan_cat", ".", "split", "(", "\"\\n\"", ")", ".", "each_with_index", ".", "map", "do", "|", "line", ",", "index", "|", "format", "(", "\"%s#{line}\"", ",", "marks", ".", "join", ")", "end", ".", "join", "(", "\"\\n\"", ")", "end" ]
Creates a rainbow trail @return [String] the sprintf format of the Nyan cat
[ "Creates", "a", "rainbow", "trail" ]
54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1
https://github.com/mattsears/nyan-cat-formatter/blob/54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1/lib/nyan_cat_formatter/common.rb#L129-L135
16,409
mattsears/nyan-cat-formatter
lib/nyan_cat_formatter/common.rb
NyanCat.Common.colors
def colors @colors ||= (0...(6 * 7)).map do |n| pi_3 = Math::PI / 3 n *= 1.0 / 6 r = (3 * Math.sin(n ) + 3).to_i g = (3 * Math.sin(n + 2 * pi_3) + 3).to_i b = (3 * Math.sin(n + 4 * pi_3) + 3).to_i 36 * r + 6 * g + b + 16 end end
ruby
def colors @colors ||= (0...(6 * 7)).map do |n| pi_3 = Math::PI / 3 n *= 1.0 / 6 r = (3 * Math.sin(n ) + 3).to_i g = (3 * Math.sin(n + 2 * pi_3) + 3).to_i b = (3 * Math.sin(n + 4 * pi_3) + 3).to_i 36 * r + 6 * g + b + 16 end end
[ "def", "colors", "@colors", "||=", "(", "0", "...", "(", "6", "*", "7", ")", ")", ".", "map", "do", "|", "n", "|", "pi_3", "=", "Math", "::", "PI", "/", "3", "n", "*=", "1.0", "/", "6", "r", "=", "(", "3", "*", "Math", ".", "sin", "(", "n", ")", "+", "3", ")", ".", "to_i", "g", "=", "(", "3", "*", "Math", ".", "sin", "(", "n", "+", "2", "*", "pi_3", ")", "+", "3", ")", ".", "to_i", "b", "=", "(", "3", "*", "Math", ".", "sin", "(", "n", "+", "4", "*", "pi_3", ")", "+", "3", ")", ".", "to_i", "36", "*", "r", "+", "6", "*", "g", "+", "b", "+", "16", "end", "end" ]
Calculates the colors of the rainbow @return [Array]
[ "Calculates", "the", "colors", "of", "the", "rainbow" ]
54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1
https://github.com/mattsears/nyan-cat-formatter/blob/54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1/lib/nyan_cat_formatter/common.rb#L172-L181
16,410
mattsears/nyan-cat-formatter
lib/nyan_cat_formatter/common.rb
NyanCat.Common.highlight
def highlight(mark = PASS) case mark when PASS; rainbowify PASS_ARY[@color_index%2] when FAIL; "\e[31m#{mark}\e[0m" when ERROR; "\e[33m#{mark}\e[0m" when PENDING; "\e[33m#{mark}\e[0m" else mark end end
ruby
def highlight(mark = PASS) case mark when PASS; rainbowify PASS_ARY[@color_index%2] when FAIL; "\e[31m#{mark}\e[0m" when ERROR; "\e[33m#{mark}\e[0m" when PENDING; "\e[33m#{mark}\e[0m" else mark end end
[ "def", "highlight", "(", "mark", "=", "PASS", ")", "case", "mark", "when", "PASS", ";", "rainbowify", "PASS_ARY", "[", "@color_index", "%", "2", "]", "when", "FAIL", ";", "\"\\e[31m#{mark}\\e[0m\"", "when", "ERROR", ";", "\"\\e[33m#{mark}\\e[0m\"", "when", "PENDING", ";", "\"\\e[33m#{mark}\\e[0m\"", "else", "mark", "end", "end" ]
Determines how to color the example. If pass, it is rainbowified, otherwise we assign red if failed or yellow if an error occurred. @return [String]
[ "Determines", "how", "to", "color", "the", "example", ".", "If", "pass", "it", "is", "rainbowified", "otherwise", "we", "assign", "red", "if", "failed", "or", "yellow", "if", "an", "error", "occurred", "." ]
54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1
https://github.com/mattsears/nyan-cat-formatter/blob/54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1/lib/nyan_cat_formatter/common.rb#L187-L195
16,411
strzibny/invoice_printer
lib/invoice_printer/pdf_document.rb
InvoicePrinter.PDFDocument.set_fonts
def set_fonts(font) font_name = Pathname.new(font).basename @pdf.font_families.update( "#{font_name}" => { normal: font, italic: font, bold: font, bold_italic: font } ) @pdf.font(font_name) end
ruby
def set_fonts(font) font_name = Pathname.new(font).basename @pdf.font_families.update( "#{font_name}" => { normal: font, italic: font, bold: font, bold_italic: font } ) @pdf.font(font_name) end
[ "def", "set_fonts", "(", "font", ")", "font_name", "=", "Pathname", ".", "new", "(", "font", ")", ".", "basename", "@pdf", ".", "font_families", ".", "update", "(", "\"#{font_name}\"", "=>", "{", "normal", ":", "font", ",", "italic", ":", "font", ",", "bold", ":", "font", ",", "bold_italic", ":", "font", "}", ")", "@pdf", ".", "font", "(", "font_name", ")", "end" ]
Add font family in Prawn for a given +font+ file
[ "Add", "font", "family", "in", "Prawn", "for", "a", "given", "+", "font", "+", "file" ]
e12c5babb8f7c078bff04c2ae721f0c73fae94b5
https://github.com/strzibny/invoice_printer/blob/e12c5babb8f7c078bff04c2ae721f0c73fae94b5/lib/invoice_printer/pdf_document.rb#L120-L131
16,412
strzibny/invoice_printer
lib/invoice_printer/pdf_document.rb
InvoicePrinter.PDFDocument.build_pdf
def build_pdf @push_down = 0 @push_items_table = 0 @pdf.fill_color '000000' build_header build_provider_box build_purchaser_box build_payment_method_box build_info_box build_items build_total build_stamp build_logo build_note build_footer end
ruby
def build_pdf @push_down = 0 @push_items_table = 0 @pdf.fill_color '000000' build_header build_provider_box build_purchaser_box build_payment_method_box build_info_box build_items build_total build_stamp build_logo build_note build_footer end
[ "def", "build_pdf", "@push_down", "=", "0", "@push_items_table", "=", "0", "@pdf", ".", "fill_color", "'000000'", "build_header", "build_provider_box", "build_purchaser_box", "build_payment_method_box", "build_info_box", "build_items", "build_total", "build_stamp", "build_logo", "build_note", "build_footer", "end" ]
Build the PDF version of the document (@pdf)
[ "Build", "the", "PDF", "version", "of", "the", "document", "(" ]
e12c5babb8f7c078bff04c2ae721f0c73fae94b5
https://github.com/strzibny/invoice_printer/blob/e12c5babb8f7c078bff04c2ae721f0c73fae94b5/lib/invoice_printer/pdf_document.rb#L134-L149
16,413
strzibny/invoice_printer
lib/invoice_printer/pdf_document.rb
InvoicePrinter.PDFDocument.determine_items_structure
def determine_items_structure items_params = {} @document.items.each do |item| items_params[:names] = true unless item.name.empty? items_params[:variables] = true unless item.variable.empty? items_params[:quantities] = true unless item.quantity.empty? items_params[:units] = true unless item.unit.empty? items_params[:prices] = true unless item.price.empty? items_params[:taxes] = true unless item.tax.empty? items_params[:taxes2] = true unless item.tax2.empty? items_params[:taxes3] = true unless item.tax3.empty? items_params[:amounts] = true unless item.amount.empty? end items_params end
ruby
def determine_items_structure items_params = {} @document.items.each do |item| items_params[:names] = true unless item.name.empty? items_params[:variables] = true unless item.variable.empty? items_params[:quantities] = true unless item.quantity.empty? items_params[:units] = true unless item.unit.empty? items_params[:prices] = true unless item.price.empty? items_params[:taxes] = true unless item.tax.empty? items_params[:taxes2] = true unless item.tax2.empty? items_params[:taxes3] = true unless item.tax3.empty? items_params[:amounts] = true unless item.amount.empty? end items_params end
[ "def", "determine_items_structure", "items_params", "=", "{", "}", "@document", ".", "items", ".", "each", "do", "|", "item", "|", "items_params", "[", ":names", "]", "=", "true", "unless", "item", ".", "name", ".", "empty?", "items_params", "[", ":variables", "]", "=", "true", "unless", "item", ".", "variable", ".", "empty?", "items_params", "[", ":quantities", "]", "=", "true", "unless", "item", ".", "quantity", ".", "empty?", "items_params", "[", ":units", "]", "=", "true", "unless", "item", ".", "unit", ".", "empty?", "items_params", "[", ":prices", "]", "=", "true", "unless", "item", ".", "price", ".", "empty?", "items_params", "[", ":taxes", "]", "=", "true", "unless", "item", ".", "tax", ".", "empty?", "items_params", "[", ":taxes2", "]", "=", "true", "unless", "item", ".", "tax2", ".", "empty?", "items_params", "[", ":taxes3", "]", "=", "true", "unless", "item", ".", "tax3", ".", "empty?", "items_params", "[", ":amounts", "]", "=", "true", "unless", "item", ".", "amount", ".", "empty?", "end", "items_params", "end" ]
Determine sections of the items table to show based on provided data
[ "Determine", "sections", "of", "the", "items", "table", "to", "show", "based", "on", "provided", "data" ]
e12c5babb8f7c078bff04c2ae721f0c73fae94b5
https://github.com/strzibny/invoice_printer/blob/e12c5babb8f7c078bff04c2ae721f0c73fae94b5/lib/invoice_printer/pdf_document.rb#L647-L661
16,414
strzibny/invoice_printer
lib/invoice_printer/pdf_document.rb
InvoicePrinter.PDFDocument.build_items_data
def build_items_data(items_params) @document.items.map do |item| line = [] line << item.name if items_params[:names] line << item.variable if items_params[:variables] line << item.quantity if items_params[:quantities] line << item.unit if items_params[:units] line << item.price if items_params[:prices] line << item.tax if items_params[:taxes] line << item.tax2 if items_params[:taxes2] line << item.tax3 if items_params[:taxes3] line << item.amount if items_params[:amounts] line end end
ruby
def build_items_data(items_params) @document.items.map do |item| line = [] line << item.name if items_params[:names] line << item.variable if items_params[:variables] line << item.quantity if items_params[:quantities] line << item.unit if items_params[:units] line << item.price if items_params[:prices] line << item.tax if items_params[:taxes] line << item.tax2 if items_params[:taxes2] line << item.tax3 if items_params[:taxes3] line << item.amount if items_params[:amounts] line end end
[ "def", "build_items_data", "(", "items_params", ")", "@document", ".", "items", ".", "map", "do", "|", "item", "|", "line", "=", "[", "]", "line", "<<", "item", ".", "name", "if", "items_params", "[", ":names", "]", "line", "<<", "item", ".", "variable", "if", "items_params", "[", ":variables", "]", "line", "<<", "item", ".", "quantity", "if", "items_params", "[", ":quantities", "]", "line", "<<", "item", ".", "unit", "if", "items_params", "[", ":units", "]", "line", "<<", "item", ".", "price", "if", "items_params", "[", ":prices", "]", "line", "<<", "item", ".", "tax", "if", "items_params", "[", ":taxes", "]", "line", "<<", "item", ".", "tax2", "if", "items_params", "[", ":taxes2", "]", "line", "<<", "item", ".", "tax3", "if", "items_params", "[", ":taxes3", "]", "line", "<<", "item", ".", "amount", "if", "items_params", "[", ":amounts", "]", "line", "end", "end" ]
Include only items params with provided data
[ "Include", "only", "items", "params", "with", "provided", "data" ]
e12c5babb8f7c078bff04c2ae721f0c73fae94b5
https://github.com/strzibny/invoice_printer/blob/e12c5babb8f7c078bff04c2ae721f0c73fae94b5/lib/invoice_printer/pdf_document.rb#L664-L678
16,415
strzibny/invoice_printer
lib/invoice_printer/pdf_document.rb
InvoicePrinter.PDFDocument.build_items_header
def build_items_header(items_params) headers = [] headers << { text: label_with_sublabel(:item) } if items_params[:names] headers << { text: label_with_sublabel(:variable) } if items_params[:variables] headers << { text: label_with_sublabel(:quantity) } if items_params[:quantities] headers << { text: label_with_sublabel(:unit) } if items_params[:units] headers << { text: label_with_sublabel(:price_per_item) } if items_params[:prices] headers << { text: label_with_sublabel(:tax) } if items_params[:taxes] headers << { text: label_with_sublabel(:tax2) } if items_params[:taxes2] headers << { text: label_with_sublabel(:tax3) } if items_params[:taxes3] headers << { text: label_with_sublabel(:amount) } if items_params[:amounts] headers end
ruby
def build_items_header(items_params) headers = [] headers << { text: label_with_sublabel(:item) } if items_params[:names] headers << { text: label_with_sublabel(:variable) } if items_params[:variables] headers << { text: label_with_sublabel(:quantity) } if items_params[:quantities] headers << { text: label_with_sublabel(:unit) } if items_params[:units] headers << { text: label_with_sublabel(:price_per_item) } if items_params[:prices] headers << { text: label_with_sublabel(:tax) } if items_params[:taxes] headers << { text: label_with_sublabel(:tax2) } if items_params[:taxes2] headers << { text: label_with_sublabel(:tax3) } if items_params[:taxes3] headers << { text: label_with_sublabel(:amount) } if items_params[:amounts] headers end
[ "def", "build_items_header", "(", "items_params", ")", "headers", "=", "[", "]", "headers", "<<", "{", "text", ":", "label_with_sublabel", "(", ":item", ")", "}", "if", "items_params", "[", ":names", "]", "headers", "<<", "{", "text", ":", "label_with_sublabel", "(", ":variable", ")", "}", "if", "items_params", "[", ":variables", "]", "headers", "<<", "{", "text", ":", "label_with_sublabel", "(", ":quantity", ")", "}", "if", "items_params", "[", ":quantities", "]", "headers", "<<", "{", "text", ":", "label_with_sublabel", "(", ":unit", ")", "}", "if", "items_params", "[", ":units", "]", "headers", "<<", "{", "text", ":", "label_with_sublabel", "(", ":price_per_item", ")", "}", "if", "items_params", "[", ":prices", "]", "headers", "<<", "{", "text", ":", "label_with_sublabel", "(", ":tax", ")", "}", "if", "items_params", "[", ":taxes", "]", "headers", "<<", "{", "text", ":", "label_with_sublabel", "(", ":tax2", ")", "}", "if", "items_params", "[", ":taxes2", "]", "headers", "<<", "{", "text", ":", "label_with_sublabel", "(", ":tax3", ")", "}", "if", "items_params", "[", ":taxes3", "]", "headers", "<<", "{", "text", ":", "label_with_sublabel", "(", ":amount", ")", "}", "if", "items_params", "[", ":amounts", "]", "headers", "end" ]
Include only relevant headers
[ "Include", "only", "relevant", "headers" ]
e12c5babb8f7c078bff04c2ae721f0c73fae94b5
https://github.com/strzibny/invoice_printer/blob/e12c5babb8f7c078bff04c2ae721f0c73fae94b5/lib/invoice_printer/pdf_document.rb#L681-L693
16,416
mdsol/mauth-client-ruby
lib/mauth/proxy.rb
MAuth.Proxy.call
def call(request_env) request = ::Rack::Request.new(request_env) request_method = request_env['REQUEST_METHOD'].downcase.to_sym request_env['rack.input'].rewind request_body = request_env['rack.input'].read request_env['rack.input'].rewind request_headers = {} request_env.each do |k, v| if k.start_with?('HTTP_') && k != 'HTTP_HOST' name = k.sub(/\AHTTP_/, '') request_headers[name] = v end end request_headers.merge!(@persistent_headers) if @browser_proxy target_uri = request_env["REQUEST_URI"] connection = @target_uris.any? { |u| target_uri.start_with? u } ? @signer_connection : @unsigned_connection response = connection.run_request(request_method, target_uri, request_body, request_headers) else response = @connection.run_request(request_method, request.fullpath, request_body, request_headers) end response_headers = response.headers.reject do |name, _value| %w(Content-Length Transfer-Encoding).map(&:downcase).include?(name.downcase) end [response.status, response_headers, [response.body || '']] end
ruby
def call(request_env) request = ::Rack::Request.new(request_env) request_method = request_env['REQUEST_METHOD'].downcase.to_sym request_env['rack.input'].rewind request_body = request_env['rack.input'].read request_env['rack.input'].rewind request_headers = {} request_env.each do |k, v| if k.start_with?('HTTP_') && k != 'HTTP_HOST' name = k.sub(/\AHTTP_/, '') request_headers[name] = v end end request_headers.merge!(@persistent_headers) if @browser_proxy target_uri = request_env["REQUEST_URI"] connection = @target_uris.any? { |u| target_uri.start_with? u } ? @signer_connection : @unsigned_connection response = connection.run_request(request_method, target_uri, request_body, request_headers) else response = @connection.run_request(request_method, request.fullpath, request_body, request_headers) end response_headers = response.headers.reject do |name, _value| %w(Content-Length Transfer-Encoding).map(&:downcase).include?(name.downcase) end [response.status, response_headers, [response.body || '']] end
[ "def", "call", "(", "request_env", ")", "request", "=", "::", "Rack", "::", "Request", ".", "new", "(", "request_env", ")", "request_method", "=", "request_env", "[", "'REQUEST_METHOD'", "]", ".", "downcase", ".", "to_sym", "request_env", "[", "'rack.input'", "]", ".", "rewind", "request_body", "=", "request_env", "[", "'rack.input'", "]", ".", "read", "request_env", "[", "'rack.input'", "]", ".", "rewind", "request_headers", "=", "{", "}", "request_env", ".", "each", "do", "|", "k", ",", "v", "|", "if", "k", ".", "start_with?", "(", "'HTTP_'", ")", "&&", "k", "!=", "'HTTP_HOST'", "name", "=", "k", ".", "sub", "(", "/", "\\A", "/", ",", "''", ")", "request_headers", "[", "name", "]", "=", "v", "end", "end", "request_headers", ".", "merge!", "(", "@persistent_headers", ")", "if", "@browser_proxy", "target_uri", "=", "request_env", "[", "\"REQUEST_URI\"", "]", "connection", "=", "@target_uris", ".", "any?", "{", "|", "u", "|", "target_uri", ".", "start_with?", "u", "}", "?", "@signer_connection", ":", "@unsigned_connection", "response", "=", "connection", ".", "run_request", "(", "request_method", ",", "target_uri", ",", "request_body", ",", "request_headers", ")", "else", "response", "=", "@connection", ".", "run_request", "(", "request_method", ",", "request", ".", "fullpath", ",", "request_body", ",", "request_headers", ")", "end", "response_headers", "=", "response", ".", "headers", ".", "reject", "do", "|", "name", ",", "_value", "|", "%w(", "Content-Length", "Transfer-Encoding", ")", ".", "map", "(", ":downcase", ")", ".", "include?", "(", "name", ".", "downcase", ")", "end", "[", "response", ".", "status", ",", "response_headers", ",", "[", "response", ".", "body", "||", "''", "]", "]", "end" ]
target_uri is the base relative to which requests are made. options: - :authenticate_responses - boolean, default true. whether responses will be authenticated. if this is true and an inauthentic response is encountered, then MAuth::InauthenticError will be raised. - :mauth_config - configuration passed to MAuth::Client.new (see its doc). default is MAuth::Client.default_config
[ "target_uri", "is", "the", "base", "relative", "to", "which", "requests", "are", "made", "." ]
cbe24f762d1c4469df01c56f80ce3b9022983b12
https://github.com/mdsol/mauth-client-ruby/blob/cbe24f762d1c4469df01c56f80ce3b9022983b12/lib/mauth/proxy.rb#L50-L75
16,417
mdsol/mauth-client-ruby
lib/mauth/client.rb
MAuth.Client.symbolize_keys
def symbolize_keys(hash) hash.keys.each do |key| hash[(key.to_sym rescue key) || key] = hash.delete(key) end hash end
ruby
def symbolize_keys(hash) hash.keys.each do |key| hash[(key.to_sym rescue key) || key] = hash.delete(key) end hash end
[ "def", "symbolize_keys", "(", "hash", ")", "hash", ".", "keys", ".", "each", "do", "|", "key", "|", "hash", "[", "(", "key", ".", "to_sym", "rescue", "key", ")", "||", "key", "]", "=", "hash", ".", "delete", "(", "key", ")", "end", "hash", "end" ]
Changes all keys in the top level of the hash to symbols. Does not affect nested hashes inside this one.
[ "Changes", "all", "keys", "in", "the", "top", "level", "of", "the", "hash", "to", "symbols", ".", "Does", "not", "affect", "nested", "hashes", "inside", "this", "one", "." ]
cbe24f762d1c4469df01c56f80ce3b9022983b12
https://github.com/mdsol/mauth-client-ruby/blob/cbe24f762d1c4469df01c56f80ce3b9022983b12/lib/mauth/client.rb#L247-L252
16,418
deliveroo/determinator
lib/determinator/control.rb
Determinator.Control.for_actor
def for_actor(id: nil, guid: nil, default_properties: {}) ActorControl.new(self, id: id, guid: guid, default_properties: default_properties) end
ruby
def for_actor(id: nil, guid: nil, default_properties: {}) ActorControl.new(self, id: id, guid: guid, default_properties: default_properties) end
[ "def", "for_actor", "(", "id", ":", "nil", ",", "guid", ":", "nil", ",", "default_properties", ":", "{", "}", ")", "ActorControl", ".", "new", "(", "self", ",", "id", ":", "id", ",", "guid", ":", "guid", ",", "default_properties", ":", "default_properties", ")", "end" ]
Creates a new determinator instance which assumes the actor id, guid and properties given are always specified. This is useful for within a before filter in a webserver, for example, so that the determinator instance made available has the logged-in user's credentials prefilled. @param :id [#to_s] The ID of the actor being specified @param :guid [#to_s] The Anonymous ID of the actor being specified @param :default_properties [Hash<Symbol,String>] The default properties for the determinator being created @return [ActorControl] A helper object removing the need to know id and guid everywhere
[ "Creates", "a", "new", "determinator", "instance", "which", "assumes", "the", "actor", "id", "guid", "and", "properties", "given", "are", "always", "specified", ".", "This", "is", "useful", "for", "within", "a", "before", "filter", "in", "a", "webserver", "for", "example", "so", "that", "the", "determinator", "instance", "made", "available", "has", "the", "logged", "-", "in", "user", "s", "credentials", "prefilled", "." ]
baf890dcc852647e325b88738b9ab05ca2fad9d8
https://github.com/deliveroo/determinator/blob/baf890dcc852647e325b88738b9ab05ca2fad9d8/lib/determinator/control.rb#L20-L22
16,419
deliveroo/determinator
lib/determinator/control.rb
Determinator.Control.feature_flag_on?
def feature_flag_on?(name, id: nil, guid: nil, properties: {}) determinate_and_notice(name, id: id, guid: guid, properties: properties) do |feature| feature.feature_flag? end end
ruby
def feature_flag_on?(name, id: nil, guid: nil, properties: {}) determinate_and_notice(name, id: id, guid: guid, properties: properties) do |feature| feature.feature_flag? end end
[ "def", "feature_flag_on?", "(", "name", ",", "id", ":", "nil", ",", "guid", ":", "nil", ",", "properties", ":", "{", "}", ")", "determinate_and_notice", "(", "name", ",", "id", ":", "id", ",", "guid", ":", "guid", ",", "properties", ":", "properties", ")", "do", "|", "feature", "|", "feature", ".", "feature_flag?", "end", "end" ]
Determines whether a specific feature is on or off for the given actor @param name [#to_s] The name of the feature flag being checked @param :id [#to_s] The id of the actor being determinated for @param :guid [#to_s] The Anonymous id of the actor being determinated for @param :properties [Hash<Symbol,String>] The properties of this actor which will be used for including this actor or not @raise [ArgumentError] When the arguments given to this method aren't ever going to produce a useful response @return [true,false] Whether the feature is on (true) or off (false) for this actor
[ "Determines", "whether", "a", "specific", "feature", "is", "on", "or", "off", "for", "the", "given", "actor" ]
baf890dcc852647e325b88738b9ab05ca2fad9d8
https://github.com/deliveroo/determinator/blob/baf890dcc852647e325b88738b9ab05ca2fad9d8/lib/determinator/control.rb#L32-L36
16,420
deliveroo/determinator
lib/determinator/control.rb
Determinator.Control.which_variant
def which_variant(name, id: nil, guid: nil, properties: {}) determinate_and_notice(name, id: id, guid: guid, properties: properties) do |feature| feature.experiment? end end
ruby
def which_variant(name, id: nil, guid: nil, properties: {}) determinate_and_notice(name, id: id, guid: guid, properties: properties) do |feature| feature.experiment? end end
[ "def", "which_variant", "(", "name", ",", "id", ":", "nil", ",", "guid", ":", "nil", ",", "properties", ":", "{", "}", ")", "determinate_and_notice", "(", "name", ",", "id", ":", "id", ",", "guid", ":", "guid", ",", "properties", ":", "properties", ")", "do", "|", "feature", "|", "feature", ".", "experiment?", "end", "end" ]
Determines what an actor should see for a specific experiment @param name [#to_s] The name of the experiment being checked @param :id [#to_s] The id of the actor being determinated for @param :guid [#to_s] The Anonymous id of the actor being determinated for @param :properties [Hash<Symbol,String>] The properties of this actor which will be used for including this actor or not @raise [ArgumentError] When the arguments given to this method aren't ever going to produce a useful response @return [false,String] Returns false, if the actor is not in this experiment, or otherwise the variant name.
[ "Determines", "what", "an", "actor", "should", "see", "for", "a", "specific", "experiment" ]
baf890dcc852647e325b88738b9ab05ca2fad9d8
https://github.com/deliveroo/determinator/blob/baf890dcc852647e325b88738b9ab05ca2fad9d8/lib/determinator/control.rb#L46-L50
16,421
deliveroo/determinator
lib/determinator/feature.rb
Determinator.Feature.parse_outcome
def parse_outcome(outcome, allow_exclusion:) valid_outcomes = experiment? ? variants.keys : [true] valid_outcomes << false if allow_exclusion valid_outcomes.include?(outcome) ? outcome : nil end
ruby
def parse_outcome(outcome, allow_exclusion:) valid_outcomes = experiment? ? variants.keys : [true] valid_outcomes << false if allow_exclusion valid_outcomes.include?(outcome) ? outcome : nil end
[ "def", "parse_outcome", "(", "outcome", ",", "allow_exclusion", ":", ")", "valid_outcomes", "=", "experiment?", "?", "variants", ".", "keys", ":", "[", "true", "]", "valid_outcomes", "<<", "false", "if", "allow_exclusion", "valid_outcomes", ".", "include?", "(", "outcome", ")", "?", "outcome", ":", "nil", "end" ]
Validates the given outcome for this feature.
[ "Validates", "the", "given", "outcome", "for", "this", "feature", "." ]
baf890dcc852647e325b88738b9ab05ca2fad9d8
https://github.com/deliveroo/determinator/blob/baf890dcc852647e325b88738b9ab05ca2fad9d8/lib/determinator/feature.rb#L50-L54
16,422
deliveroo/roo_on_rails
spec/support/sub_process.rb
ROR.SubProcess.stop
def stop return self if @pid.nil? _log "stopping (##{@pid})" Process.kill('INT', @pid) Timeout::timeout(10) do sleep(10e-3) until Process.wait(@pid, Process::WNOHANG) @status = $? end @pid = nil self end
ruby
def stop return self if @pid.nil? _log "stopping (##{@pid})" Process.kill('INT', @pid) Timeout::timeout(10) do sleep(10e-3) until Process.wait(@pid, Process::WNOHANG) @status = $? end @pid = nil self end
[ "def", "stop", "return", "self", "if", "@pid", ".", "nil?", "_log", "\"stopping (##{@pid})\"", "Process", ".", "kill", "(", "'INT'", ",", "@pid", ")", "Timeout", "::", "timeout", "(", "10", ")", "do", "sleep", "(", "10e-3", ")", "until", "Process", ".", "wait", "(", "@pid", ",", "Process", "::", "WNOHANG", ")", "@status", "=", "$?", "end", "@pid", "=", "nil", "self", "end" ]
politely ask the process to stop, and wait for it to exit
[ "politely", "ask", "the", "process", "to", "stop", "and", "wait", "for", "it", "to", "exit" ]
29d664e3718278068bae08f5da9e51c88152059c
https://github.com/deliveroo/roo_on_rails/blob/29d664e3718278068bae08f5da9e51c88152059c/spec/support/sub_process.rb#L56-L68
16,423
deliveroo/roo_on_rails
spec/support/sub_process.rb
ROR.SubProcess.wait_log
def wait_log(regexp) cursor = 0 Timeout::timeout(10) do loop do line = @loglines[cursor] sleep(10e-3) if line.nil? break if line && line =~ regexp cursor += 1 unless line.nil? end end self end
ruby
def wait_log(regexp) cursor = 0 Timeout::timeout(10) do loop do line = @loglines[cursor] sleep(10e-3) if line.nil? break if line && line =~ regexp cursor += 1 unless line.nil? end end self end
[ "def", "wait_log", "(", "regexp", ")", "cursor", "=", "0", "Timeout", "::", "timeout", "(", "10", ")", "do", "loop", "do", "line", "=", "@loglines", "[", "cursor", "]", "sleep", "(", "10e-3", ")", "if", "line", ".", "nil?", "break", "if", "line", "&&", "line", "=~", "regexp", "cursor", "+=", "1", "unless", "line", ".", "nil?", "end", "end", "self", "end" ]
wait until a log line is seen that matches `regexp`, up to a timeout
[ "wait", "until", "a", "log", "line", "is", "seen", "that", "matches", "regexp", "up", "to", "a", "timeout" ]
29d664e3718278068bae08f5da9e51c88152059c
https://github.com/deliveroo/roo_on_rails/blob/29d664e3718278068bae08f5da9e51c88152059c/spec/support/sub_process.rb#L103-L114
16,424
ledermann/unread
lib/unread/garbage_collector.rb
Unread.GarbageCollector.readers_to_cleanup
def readers_to_cleanup(reader_class) reader_class. reader_scope. joins(:read_marks). where(ReadMark.table_name => { readable_type: readable_class.name }). group("#{ReadMark.quoted_table_name}.reader_type, #{ReadMark.quoted_table_name}.reader_id, #{reader_class.quoted_table_name}.#{reader_class.quoted_primary_key}"). having("COUNT(#{ReadMark.quoted_table_name}.id) > 1"). select("#{reader_class.quoted_table_name}.#{reader_class.quoted_primary_key}") end
ruby
def readers_to_cleanup(reader_class) reader_class. reader_scope. joins(:read_marks). where(ReadMark.table_name => { readable_type: readable_class.name }). group("#{ReadMark.quoted_table_name}.reader_type, #{ReadMark.quoted_table_name}.reader_id, #{reader_class.quoted_table_name}.#{reader_class.quoted_primary_key}"). having("COUNT(#{ReadMark.quoted_table_name}.id) > 1"). select("#{reader_class.quoted_table_name}.#{reader_class.quoted_primary_key}") end
[ "def", "readers_to_cleanup", "(", "reader_class", ")", "reader_class", ".", "reader_scope", ".", "joins", "(", ":read_marks", ")", ".", "where", "(", "ReadMark", ".", "table_name", "=>", "{", "readable_type", ":", "readable_class", ".", "name", "}", ")", ".", "group", "(", "\"#{ReadMark.quoted_table_name}.reader_type, #{ReadMark.quoted_table_name}.reader_id, #{reader_class.quoted_table_name}.#{reader_class.quoted_primary_key}\"", ")", ".", "having", "(", "\"COUNT(#{ReadMark.quoted_table_name}.id) > 1\"", ")", ".", "select", "(", "\"#{reader_class.quoted_table_name}.#{reader_class.quoted_primary_key}\"", ")", "end" ]
Not for every reader a cleanup is needed. Look for those readers with at least one single read mark
[ "Not", "for", "every", "reader", "a", "cleanup", "is", "needed", ".", "Look", "for", "those", "readers", "with", "at", "least", "one", "single", "read", "mark" ]
e765c8878f6c780dc1189ec11070b308428a78d9
https://github.com/ledermann/unread/blob/e765c8878f6c780dc1189ec11070b308428a78d9/lib/unread/garbage_collector.rb#L28-L36
16,425
chef/artifactory-client
lib/artifactory/util.rb
Artifactory.Util.truncate
def truncate(string, options = {}) length = options[:length] || 30 if string.length > length string[0..length - 3] + "..." else string end end
ruby
def truncate(string, options = {}) length = options[:length] || 30 if string.length > length string[0..length - 3] + "..." else string end end
[ "def", "truncate", "(", "string", ",", "options", "=", "{", "}", ")", "length", "=", "options", "[", ":length", "]", "||", "30", "if", "string", ".", "length", ">", "length", "string", "[", "0", "..", "length", "-", "3", "]", "+", "\"...\"", "else", "string", "end", "end" ]
Truncate the given string to a certain number of characters. @param [String] string the string to truncate @param [Hash] options the list of options (such as +length+)
[ "Truncate", "the", "given", "string", "to", "a", "certain", "number", "of", "characters", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/util.rb#L70-L78
16,426
chef/artifactory-client
lib/artifactory/util.rb
Artifactory.Util.rename_keys
def rename_keys(options, map = {}) Hash[options.map { |k, v| [map[k] || k, v] }] end
ruby
def rename_keys(options, map = {}) Hash[options.map { |k, v| [map[k] || k, v] }] end
[ "def", "rename_keys", "(", "options", ",", "map", "=", "{", "}", ")", "Hash", "[", "options", ".", "map", "{", "|", "k", ",", "v", "|", "[", "map", "[", "k", "]", "||", "k", ",", "v", "]", "}", "]", "end" ]
Rename a list of keys to the given map. @example Rename the given keys rename_keys(hash, foo: :bar, zip: :zap) @param [Hash] options the options to map @param [Hash] map the map of keys to map @return [Hash]
[ "Rename", "a", "list", "of", "keys", "to", "the", "given", "map", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/util.rb#L93-L95
16,427
chef/artifactory-client
lib/artifactory/util.rb
Artifactory.Util.slice
def slice(options, *keys) keys.inject({}) do |hash, key| hash[key] = options[key] if options[key] hash end end
ruby
def slice(options, *keys) keys.inject({}) do |hash, key| hash[key] = options[key] if options[key] hash end end
[ "def", "slice", "(", "options", ",", "*", "keys", ")", "keys", ".", "inject", "(", "{", "}", ")", "do", "|", "hash", ",", "key", "|", "hash", "[", "key", "]", "=", "options", "[", "key", "]", "if", "options", "[", "key", "]", "hash", "end", "end" ]
Slice the given list of options with the given keys. @param [Hash] options the list of options to slice @param [Array<Object>] keys the keys to slice @return [Hash] the sliced hash
[ "Slice", "the", "given", "list", "of", "options", "with", "the", "given", "keys", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/util.rb#L108-L113
16,428
chef/artifactory-client
lib/artifactory/util.rb
Artifactory.Util.xml_to_hash
def xml_to_hash(element, child_with_children = "", unique_children = true) properties = {} element.each_element_with_text do |e| if e.name.eql?(child_with_children) if unique_children e.each_element_with_text do |t| properties[t.name] = to_type(t.text) end else children = [] e.each_element_with_text do |t| properties[t.name] = children.push(to_type(t.text)) end end else properties[e.name] = to_type(e.text) end end properties end
ruby
def xml_to_hash(element, child_with_children = "", unique_children = true) properties = {} element.each_element_with_text do |e| if e.name.eql?(child_with_children) if unique_children e.each_element_with_text do |t| properties[t.name] = to_type(t.text) end else children = [] e.each_element_with_text do |t| properties[t.name] = children.push(to_type(t.text)) end end else properties[e.name] = to_type(e.text) end end properties end
[ "def", "xml_to_hash", "(", "element", ",", "child_with_children", "=", "\"\"", ",", "unique_children", "=", "true", ")", "properties", "=", "{", "}", "element", ".", "each_element_with_text", "do", "|", "e", "|", "if", "e", ".", "name", ".", "eql?", "(", "child_with_children", ")", "if", "unique_children", "e", ".", "each_element_with_text", "do", "|", "t", "|", "properties", "[", "t", ".", "name", "]", "=", "to_type", "(", "t", ".", "text", ")", "end", "else", "children", "=", "[", "]", "e", ".", "each_element_with_text", "do", "|", "t", "|", "properties", "[", "t", ".", "name", "]", "=", "children", ".", "push", "(", "to_type", "(", "t", ".", "text", ")", ")", "end", "end", "else", "properties", "[", "e", ".", "name", "]", "=", "to_type", "(", "e", ".", "text", ")", "end", "end", "properties", "end" ]
Flatten an xml element with at most one child node with children into a hash. @param [REXML] element xml element
[ "Flatten", "an", "xml", "element", "with", "at", "most", "one", "child", "node", "with", "children", "into", "a", "hash", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/util.rb#L122-L141
16,429
chef/artifactory-client
lib/artifactory/resources/artifact.rb
Artifactory.Resource::Artifact.properties
def properties(props = nil) if props.nil? || props.empty? get_properties else set_properties(props) get_properties(true) end end
ruby
def properties(props = nil) if props.nil? || props.empty? get_properties else set_properties(props) get_properties(true) end end
[ "def", "properties", "(", "props", "=", "nil", ")", "if", "props", ".", "nil?", "||", "props", ".", "empty?", "get_properties", "else", "set_properties", "(", "props", ")", "get_properties", "(", "true", ")", "end", "end" ]
Set properties for this object. If no properties are given it lists the properties for this object. @example List all properties for an artifact artifact.properties #=> { 'licenses'=>['Apache-2.0'] } @example Set new properties for an artifact artifact.properties(maintainer: 'SuperStartup01') #=> { 'licenses'=>['Apache-2.0'], 'maintainer'=>'SuperStartup01' } @param [Hash<String, Object>] props (default: +nil+) A hash of properties and corresponding values to set for the artifact @return [Hash<String, Object>] the list of properties
[ "Set", "properties", "for", "this", "object", ".", "If", "no", "properties", "are", "given", "it", "lists", "the", "properties", "for", "this", "object", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/artifact.rb#L447-L454
16,430
chef/artifactory-client
lib/artifactory/resources/artifact.rb
Artifactory.Resource::Artifact.download
def download(target = Dir.mktmpdir, options = {}) target = File.expand_path(target) # Make the directory if it doesn't yet exist FileUtils.mkdir_p(target) unless File.exist?(target) # Use the server artifact's filename if one wasn't given filename = options[:filename] || File.basename(download_uri) # Construct the full path for the file destination = File.join(target, filename) File.open(destination, "wb") do |file| client.get(download_uri) do |chunk| file.write chunk end end destination end
ruby
def download(target = Dir.mktmpdir, options = {}) target = File.expand_path(target) # Make the directory if it doesn't yet exist FileUtils.mkdir_p(target) unless File.exist?(target) # Use the server artifact's filename if one wasn't given filename = options[:filename] || File.basename(download_uri) # Construct the full path for the file destination = File.join(target, filename) File.open(destination, "wb") do |file| client.get(download_uri) do |chunk| file.write chunk end end destination end
[ "def", "download", "(", "target", "=", "Dir", ".", "mktmpdir", ",", "options", "=", "{", "}", ")", "target", "=", "File", ".", "expand_path", "(", "target", ")", "# Make the directory if it doesn't yet exist", "FileUtils", ".", "mkdir_p", "(", "target", ")", "unless", "File", ".", "exist?", "(", "target", ")", "# Use the server artifact's filename if one wasn't given", "filename", "=", "options", "[", ":filename", "]", "||", "File", ".", "basename", "(", "download_uri", ")", "# Construct the full path for the file", "destination", "=", "File", ".", "join", "(", "target", ",", "filename", ")", "File", ".", "open", "(", "destination", ",", "\"wb\"", ")", "do", "|", "file", "|", "client", ".", "get", "(", "download_uri", ")", "do", "|", "chunk", "|", "file", ".", "write", "chunk", "end", "end", "destination", "end" ]
Download the artifact onto the local disk. @example Download an artifact artifact.download #=> /tmp/cache/000adad0-bac/artifact.deb @example Download a remote artifact into a specific target artifact.download('~/Desktop') #=> ~/Desktop/artifact.deb @param [String] target the target directory where the artifact should be downloaded to (defaults to a temporary directory). **It is the user's responsibility to cleanup the temporary directory when finished!** @param [Hash] options @option options [String] filename the name of the file when downloaded to disk (defaults to the basename of the file on the server) @return [String] the path where the file was downloaded on disk
[ "Download", "the", "artifact", "onto", "the", "local", "disk", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/artifact.rb#L492-L511
16,431
chef/artifactory-client
lib/artifactory/resources/artifact.rb
Artifactory.Resource::Artifact.upload
def upload(repo, remote_path, properties = {}, headers = {}) file = File.new(File.expand_path(local_path)) matrix = to_matrix_properties(properties) endpoint = File.join("#{url_safe(repo)}#{matrix}", remote_path) # Include checksums in headers if given. headers["X-Checksum-Md5"] = md5 if md5 headers["X-Checksum-Sha1"] = sha1 if sha1 response = client.put(endpoint, file, headers) return unless response.is_a?(Hash) self.class.from_hash(response) end
ruby
def upload(repo, remote_path, properties = {}, headers = {}) file = File.new(File.expand_path(local_path)) matrix = to_matrix_properties(properties) endpoint = File.join("#{url_safe(repo)}#{matrix}", remote_path) # Include checksums in headers if given. headers["X-Checksum-Md5"] = md5 if md5 headers["X-Checksum-Sha1"] = sha1 if sha1 response = client.put(endpoint, file, headers) return unless response.is_a?(Hash) self.class.from_hash(response) end
[ "def", "upload", "(", "repo", ",", "remote_path", ",", "properties", "=", "{", "}", ",", "headers", "=", "{", "}", ")", "file", "=", "File", ".", "new", "(", "File", ".", "expand_path", "(", "local_path", ")", ")", "matrix", "=", "to_matrix_properties", "(", "properties", ")", "endpoint", "=", "File", ".", "join", "(", "\"#{url_safe(repo)}#{matrix}\"", ",", "remote_path", ")", "# Include checksums in headers if given.", "headers", "[", "\"X-Checksum-Md5\"", "]", "=", "md5", "if", "md5", "headers", "[", "\"X-Checksum-Sha1\"", "]", "=", "sha1", "if", "sha1", "response", "=", "client", ".", "put", "(", "endpoint", ",", "file", ",", "headers", ")", "return", "unless", "response", ".", "is_a?", "(", "Hash", ")", "self", ".", "class", ".", "from_hash", "(", "response", ")", "end" ]
Upload an artifact into the repository. If the first parameter is a File object, that file descriptor is passed to the uploader. If the first parameter is a string, it is assumed to be the path to a local file on disk. This method will automatically construct the File object from the given path. @see bit.ly/1dhJRMO Artifactory Matrix Properties @example Upload an artifact from a File instance artifact = Artifact.new(local_path: '/local/path/to/file.deb') artifact.upload('libs-release-local', '/remote/path') @example Upload an artifact with matrix properties artifact = Artifact.new(local_path: '/local/path/to/file.deb') artifact.upload('libs-release-local', '/remote/path', { status: 'DEV', rating: 5, branch: 'master' }) @param [String] repo the key of the repository to which to upload the file @param [String] remote_path the path where this resource will live in the remote artifactory repository, relative to the repository key @param [Hash] headers the list of headers to send with the request @param [Hash] properties a list of matrix properties @return [Resource::Artifact]
[ "Upload", "an", "artifact", "into", "the", "repository", ".", "If", "the", "first", "parameter", "is", "a", "File", "object", "that", "file", "descriptor", "is", "passed", "to", "the", "uploader", ".", "If", "the", "first", "parameter", "is", "a", "string", "it", "is", "assumed", "to", "be", "the", "path", "to", "a", "local", "file", "on", "disk", ".", "This", "method", "will", "automatically", "construct", "the", "File", "object", "from", "the", "given", "path", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/artifact.rb#L546-L559
16,432
chef/artifactory-client
lib/artifactory/resources/artifact.rb
Artifactory.Resource::Artifact.get_properties
def get_properties(refresh_cache = false) if refresh_cache || @properties.nil? @properties = client.get(File.join("/api/storage", relative_path), properties: nil)["properties"] end @properties end
ruby
def get_properties(refresh_cache = false) if refresh_cache || @properties.nil? @properties = client.get(File.join("/api/storage", relative_path), properties: nil)["properties"] end @properties end
[ "def", "get_properties", "(", "refresh_cache", "=", "false", ")", "if", "refresh_cache", "||", "@properties", ".", "nil?", "@properties", "=", "client", ".", "get", "(", "File", ".", "join", "(", "\"/api/storage\"", ",", "relative_path", ")", ",", "properties", ":", "nil", ")", "[", "\"properties\"", "]", "end", "@properties", "end" ]
Helper method for reading artifact properties @example List all properties for an artifact artifact.get_properties #=> { 'artifactory.licenses'=>['Apache-2.0'] } @param [TrueClass, FalseClass] refresh_cache (default: +false+) wether or not to use the locally cached value if it exists and is not nil @return [Hash<String, Object>] the list of properties
[ "Helper", "method", "for", "reading", "artifact", "properties" ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/artifact.rb#L647-L653
16,433
chef/artifactory-client
lib/artifactory/resources/artifact.rb
Artifactory.Resource::Artifact.set_properties
def set_properties(properties) matrix = to_matrix_properties(properties) endpoint = File.join("/api/storage", relative_path) + "?properties=#{matrix}" client.put(endpoint, nil) end
ruby
def set_properties(properties) matrix = to_matrix_properties(properties) endpoint = File.join("/api/storage", relative_path) + "?properties=#{matrix}" client.put(endpoint, nil) end
[ "def", "set_properties", "(", "properties", ")", "matrix", "=", "to_matrix_properties", "(", "properties", ")", "endpoint", "=", "File", ".", "join", "(", "\"/api/storage\"", ",", "relative_path", ")", "+", "\"?properties=#{matrix}\"", "client", ".", "put", "(", "endpoint", ",", "nil", ")", "end" ]
Helper method for setting artifact properties @example Set properties for an artifact artifact.set_properties({ prop1: 'value1', 'prop2' => 'value2' }) @param [Hash<String, Object>] properties A hash of properties and corresponding values to set for the artifact @return [Hash] the parsed JSON response from the server
[ "Helper", "method", "for", "setting", "artifact", "properties" ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/artifact.rb#L667-L672
16,434
chef/artifactory-client
lib/artifactory/resources/artifact.rb
Artifactory.Resource::Artifact.copy_or_move
def copy_or_move(action, destination, options = {}) params = {}.tap do |param| param[:to] = destination param[:failFast] = 1 if options[:fail_fast] param[:suppressLayouts] = 1 if options[:suppress_layouts] param[:dry] = 1 if options[:dry_run] end endpoint = File.join("/api", action.to_s, relative_path) + "?#{to_query_string_parameters(params)}" client.post(endpoint, {}) end
ruby
def copy_or_move(action, destination, options = {}) params = {}.tap do |param| param[:to] = destination param[:failFast] = 1 if options[:fail_fast] param[:suppressLayouts] = 1 if options[:suppress_layouts] param[:dry] = 1 if options[:dry_run] end endpoint = File.join("/api", action.to_s, relative_path) + "?#{to_query_string_parameters(params)}" client.post(endpoint, {}) end
[ "def", "copy_or_move", "(", "action", ",", "destination", ",", "options", "=", "{", "}", ")", "params", "=", "{", "}", ".", "tap", "do", "|", "param", "|", "param", "[", ":to", "]", "=", "destination", "param", "[", ":failFast", "]", "=", "1", "if", "options", "[", ":fail_fast", "]", "param", "[", ":suppressLayouts", "]", "=", "1", "if", "options", "[", ":suppress_layouts", "]", "param", "[", ":dry", "]", "=", "1", "if", "options", "[", ":dry_run", "]", "end", "endpoint", "=", "File", ".", "join", "(", "\"/api\"", ",", "action", ".", "to_s", ",", "relative_path", ")", "+", "\"?#{to_query_string_parameters(params)}\"", "client", ".", "post", "(", "endpoint", ",", "{", "}", ")", "end" ]
Copy or move current artifact to a new destination. @example Move the current artifact to +ext-releases-local+ artifact.move(to: '/ext-releaes-local/org/acme') @example Copy the current artifact to +ext-releases-local+ artifact.move(to: '/ext-releaes-local/org/acme') @param [Symbol] action the action (+:move+ or +:copy+) @param [String] destination the server-side destination to move or copy the artifact @param [Hash] options the list of options to pass @option options [Boolean] :fail_fast (default: +false+) fail on the first failure @option options [Boolean] :suppress_layouts (default: +false+) suppress cross-layout module path translation during copying or moving @option options [Boolean] :dry_run (default: +false+) pretend to do the copy or move @return [Hash] the parsed JSON response from the server
[ "Copy", "or", "move", "current", "artifact", "to", "a", "new", "destination", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/artifact.rb#L712-L723
16,435
chef/artifactory-client
lib/artifactory/resources/base.rb
Artifactory.Resource::Base.to_hash
def to_hash attributes.inject({}) do |hash, (key, value)| unless Resource::Base.has_attribute?(key) hash[Util.camelize(key, true)] = send(key.to_sym) end hash end end
ruby
def to_hash attributes.inject({}) do |hash, (key, value)| unless Resource::Base.has_attribute?(key) hash[Util.camelize(key, true)] = send(key.to_sym) end hash end end
[ "def", "to_hash", "attributes", ".", "inject", "(", "{", "}", ")", "do", "|", "hash", ",", "(", "key", ",", "value", ")", "|", "unless", "Resource", "::", "Base", ".", "has_attribute?", "(", "key", ")", "hash", "[", "Util", ".", "camelize", "(", "key", ",", "true", ")", "]", "=", "send", "(", "key", ".", "to_sym", ")", "end", "hash", "end", "end" ]
The hash representation @example An example hash response { 'key' => 'local-repo1', 'includesPattern' => '**/*' } @return [Hash]
[ "The", "hash", "representation" ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/base.rb#L306-L314
16,436
chef/artifactory-client
lib/artifactory/resources/base.rb
Artifactory.Resource::Base.to_matrix_properties
def to_matrix_properties(hash = {}) properties = hash.map do |k, v| key = CGI.escape(k.to_s) value = CGI.escape(v.to_s) "#{key}=#{value}" end if properties.empty? nil else ";#{properties.join(';')}" end end
ruby
def to_matrix_properties(hash = {}) properties = hash.map do |k, v| key = CGI.escape(k.to_s) value = CGI.escape(v.to_s) "#{key}=#{value}" end if properties.empty? nil else ";#{properties.join(';')}" end end
[ "def", "to_matrix_properties", "(", "hash", "=", "{", "}", ")", "properties", "=", "hash", ".", "map", "do", "|", "k", ",", "v", "|", "key", "=", "CGI", ".", "escape", "(", "k", ".", "to_s", ")", "value", "=", "CGI", ".", "escape", "(", "v", ".", "to_s", ")", "\"#{key}=#{value}\"", "end", "if", "properties", ".", "empty?", "nil", "else", "\";#{properties.join(';')}\"", "end", "end" ]
Create CGI-escaped string from matrix properties @see http://bit.ly/1qeVYQl
[ "Create", "CGI", "-", "escaped", "string", "from", "matrix", "properties" ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/base.rb#L332-L345
16,437
chef/artifactory-client
lib/artifactory/resources/base.rb
Artifactory.Resource::Base.to_query_string_parameters
def to_query_string_parameters(hash = {}) properties = hash.map do |k, v| key = URI.escape(k.to_s) value = URI.escape(v.to_s) "#{key}=#{value}" end if properties.empty? nil else properties.join("&") end end
ruby
def to_query_string_parameters(hash = {}) properties = hash.map do |k, v| key = URI.escape(k.to_s) value = URI.escape(v.to_s) "#{key}=#{value}" end if properties.empty? nil else properties.join("&") end end
[ "def", "to_query_string_parameters", "(", "hash", "=", "{", "}", ")", "properties", "=", "hash", ".", "map", "do", "|", "k", ",", "v", "|", "key", "=", "URI", ".", "escape", "(", "k", ".", "to_s", ")", "value", "=", "URI", ".", "escape", "(", "v", ".", "to_s", ")", "\"#{key}=#{value}\"", "end", "if", "properties", ".", "empty?", "nil", "else", "properties", ".", "join", "(", "\"&\"", ")", "end", "end" ]
Create URI-escaped querystring parameters @see http://bit.ly/1qeVYQl
[ "Create", "URI", "-", "escaped", "querystring", "parameters" ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/base.rb#L352-L365
16,438
chef/artifactory-client
lib/artifactory/resources/build.rb
Artifactory.Resource::Build.promote
def promote(target_repo, options = {}) request_body = {}.tap do |body| body[:status] = options[:status] || "promoted" body[:comment] = options[:comment] || "" body[:ciUser] = options[:user] || Artifactory.username body[:dryRun] = options[:dry_run] || false body[:targetRepo] = target_repo body[:copy] = options[:copy] || false body[:artifacts] = true # always move/copy the build's artifacts body[:dependencies] = options[:dependencies] || false body[:scopes] = options[:scopes] || [] body[:properties] = options[:properties] || {} body[:failFast] = options[:fail_fast] || true end endpoint = "/api/build/promote/#{url_safe(name)}/#{url_safe(number)}" client.post(endpoint, JSON.fast_generate(request_body), "Content-Type" => "application/json" ) end
ruby
def promote(target_repo, options = {}) request_body = {}.tap do |body| body[:status] = options[:status] || "promoted" body[:comment] = options[:comment] || "" body[:ciUser] = options[:user] || Artifactory.username body[:dryRun] = options[:dry_run] || false body[:targetRepo] = target_repo body[:copy] = options[:copy] || false body[:artifacts] = true # always move/copy the build's artifacts body[:dependencies] = options[:dependencies] || false body[:scopes] = options[:scopes] || [] body[:properties] = options[:properties] || {} body[:failFast] = options[:fail_fast] || true end endpoint = "/api/build/promote/#{url_safe(name)}/#{url_safe(number)}" client.post(endpoint, JSON.fast_generate(request_body), "Content-Type" => "application/json" ) end
[ "def", "promote", "(", "target_repo", ",", "options", "=", "{", "}", ")", "request_body", "=", "{", "}", ".", "tap", "do", "|", "body", "|", "body", "[", ":status", "]", "=", "options", "[", ":status", "]", "||", "\"promoted\"", "body", "[", ":comment", "]", "=", "options", "[", ":comment", "]", "||", "\"\"", "body", "[", ":ciUser", "]", "=", "options", "[", ":user", "]", "||", "Artifactory", ".", "username", "body", "[", ":dryRun", "]", "=", "options", "[", ":dry_run", "]", "||", "false", "body", "[", ":targetRepo", "]", "=", "target_repo", "body", "[", ":copy", "]", "=", "options", "[", ":copy", "]", "||", "false", "body", "[", ":artifacts", "]", "=", "true", "# always move/copy the build's artifacts", "body", "[", ":dependencies", "]", "=", "options", "[", ":dependencies", "]", "||", "false", "body", "[", ":scopes", "]", "=", "options", "[", ":scopes", "]", "||", "[", "]", "body", "[", ":properties", "]", "=", "options", "[", ":properties", "]", "||", "{", "}", "body", "[", ":failFast", "]", "=", "options", "[", ":fail_fast", "]", "||", "true", "end", "endpoint", "=", "\"/api/build/promote/#{url_safe(name)}/#{url_safe(number)}\"", "client", ".", "post", "(", "endpoint", ",", "JSON", ".", "fast_generate", "(", "request_body", ")", ",", "\"Content-Type\"", "=>", "\"application/json\"", ")", "end" ]
Move a build's artifacts to a new repository optionally moving or copying the build's dependencies to the target repository and setting properties on promoted artifacts. @example promote the build to 'omnibus-stable-local' build.promote('omnibus-stable-local') @example promote a build attaching some new properites build.promote('omnibus-stable-local' properties: { 'promoted_by' => 'hipchat:schisamo@chef.io' } ) @param [String] target_repo repository to move or copy the build's artifacts and/or dependencies @param [Hash] options the list of options to pass @option options [String] :status (default: 'promoted') new build status (any string) @option options [String] :comment (default: '') an optional comment describing the reason for promotion @option options [String] :user (default: +Artifactory.username+) the user that invoked promotion @option options [Boolean] :dry_run (default: +false+) pretend to do the promotion @option options [Boolean] :copy (default: +false+) whether to copy instead of move @option options [Boolean] :dependencies (default: +false+) whether to move/copy the build's dependencies @option options [Array] :scopes (default: []) an array of dependency scopes to include when "dependencies" is true @option options [Hash<String, Array<String>>] :properties (default: []) a list of properties to attach to the build's artifacts @option options [Boolean] :fail_fast (default: +true+) fail and abort the operation upon receiving an error @return [Hash] the parsed JSON response from the server
[ "Move", "a", "build", "s", "artifacts", "to", "a", "new", "repository", "optionally", "moving", "or", "copying", "the", "build", "s", "dependencies", "to", "the", "target", "repository", "and", "setting", "properties", "on", "promoted", "artifacts", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/build.rb#L175-L194
16,439
chef/artifactory-client
lib/artifactory/resources/build.rb
Artifactory.Resource::Build.save
def save raise Error::InvalidBuildType.new(type) unless BUILD_TYPES.include?(type) file = Tempfile.new("build.json") file.write(to_json) file.rewind client.put("/api/build", file, "Content-Type" => "application/json" ) true ensure if file file.close file.unlink end end
ruby
def save raise Error::InvalidBuildType.new(type) unless BUILD_TYPES.include?(type) file = Tempfile.new("build.json") file.write(to_json) file.rewind client.put("/api/build", file, "Content-Type" => "application/json" ) true ensure if file file.close file.unlink end end
[ "def", "save", "raise", "Error", "::", "InvalidBuildType", ".", "new", "(", "type", ")", "unless", "BUILD_TYPES", ".", "include?", "(", "type", ")", "file", "=", "Tempfile", ".", "new", "(", "\"build.json\"", ")", "file", ".", "write", "(", "to_json", ")", "file", ".", "rewind", "client", ".", "put", "(", "\"/api/build\"", ",", "file", ",", "\"Content-Type\"", "=>", "\"application/json\"", ")", "true", "ensure", "if", "file", "file", ".", "close", "file", ".", "unlink", "end", "end" ]
Creates data about a build. @return [Boolean]
[ "Creates", "data", "about", "a", "build", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/build.rb#L201-L217
16,440
chef/artifactory-client
lib/artifactory/resources/build_component.rb
Artifactory.Resource::BuildComponent.builds
def builds @builds ||= Collection::Build.new(self, name: name) do Resource::Build.all(name) end end
ruby
def builds @builds ||= Collection::Build.new(self, name: name) do Resource::Build.all(name) end end
[ "def", "builds", "@builds", "||=", "Collection", "::", "Build", ".", "new", "(", "self", ",", "name", ":", "name", ")", "do", "Resource", "::", "Build", ".", "all", "(", "name", ")", "end", "end" ]
The list of build data for this component. @example Get the list of artifacts for a repository component = BuildComponent.new(name: 'wicket') component.builds #=> [#<Resource::Build>, ...] @return [Collection::Build] the list of builds
[ "The", "list", "of", "build", "data", "for", "this", "component", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/build_component.rb#L98-L102
16,441
chef/artifactory-client
lib/artifactory/resources/build_component.rb
Artifactory.Resource::BuildComponent.delete
def delete(options = {}) params = {}.tap do |param| param[:buildNumbers] = options[:build_numbers].join(",") if options[:build_numbers] param[:artifacts] = 1 if options[:artifacts] param[:deleteAll] = 1 if options[:delete_all] end endpoint = api_path + "?#{to_query_string_parameters(params)}" client.delete(endpoint, {}) true rescue Error::HTTPError => e false end
ruby
def delete(options = {}) params = {}.tap do |param| param[:buildNumbers] = options[:build_numbers].join(",") if options[:build_numbers] param[:artifacts] = 1 if options[:artifacts] param[:deleteAll] = 1 if options[:delete_all] end endpoint = api_path + "?#{to_query_string_parameters(params)}" client.delete(endpoint, {}) true rescue Error::HTTPError => e false end
[ "def", "delete", "(", "options", "=", "{", "}", ")", "params", "=", "{", "}", ".", "tap", "do", "|", "param", "|", "param", "[", ":buildNumbers", "]", "=", "options", "[", ":build_numbers", "]", ".", "join", "(", "\",\"", ")", "if", "options", "[", ":build_numbers", "]", "param", "[", ":artifacts", "]", "=", "1", "if", "options", "[", ":artifacts", "]", "param", "[", ":deleteAll", "]", "=", "1", "if", "options", "[", ":delete_all", "]", "end", "endpoint", "=", "api_path", "+", "\"?#{to_query_string_parameters(params)}\"", "client", ".", "delete", "(", "endpoint", ",", "{", "}", ")", "true", "rescue", "Error", "::", "HTTPError", "=>", "e", "false", "end" ]
Remove this component's build data stored in Artifactory @option options [Array<String>] :build_numbers (default: nil) an array of build numbers that should be deleted; if not given all builds (for this component) are deleted @option options [Boolean] :artifacts (default: +false+) if true the component's artifacts are also removed @option options [Boolean] :delete_all (default: +false+) if true the entire component is removed @return [Boolean] true if the object was deleted successfully, false otherwise
[ "Remove", "this", "component", "s", "build", "data", "stored", "in", "Artifactory" ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/build_component.rb#L118-L130
16,442
chef/artifactory-client
lib/artifactory/resources/build_component.rb
Artifactory.Resource::BuildComponent.rename
def rename(new_name, options = {}) endpoint = "/api/build/rename/#{url_safe(name)}" + "?to=#{new_name}" client.post(endpoint, {}) true rescue Error::HTTPError => e false end
ruby
def rename(new_name, options = {}) endpoint = "/api/build/rename/#{url_safe(name)}" + "?to=#{new_name}" client.post(endpoint, {}) true rescue Error::HTTPError => e false end
[ "def", "rename", "(", "new_name", ",", "options", "=", "{", "}", ")", "endpoint", "=", "\"/api/build/rename/#{url_safe(name)}\"", "+", "\"?to=#{new_name}\"", "client", ".", "post", "(", "endpoint", ",", "{", "}", ")", "true", "rescue", "Error", "::", "HTTPError", "=>", "e", "false", "end" ]
Rename a build component. @param [String] new_name new name for the component @return [Boolean] true if the object was renamed successfully, false otherwise
[ "Rename", "a", "build", "component", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/build_component.rb#L141-L147
16,443
chef/artifactory-client
lib/artifactory/resources/repository.rb
Artifactory.Resource::Repository.upload
def upload(local_path, remote_path, properties = {}, headers = {}) artifact = Resource::Artifact.new(local_path: local_path) artifact.upload(key, remote_path, properties, headers) end
ruby
def upload(local_path, remote_path, properties = {}, headers = {}) artifact = Resource::Artifact.new(local_path: local_path) artifact.upload(key, remote_path, properties, headers) end
[ "def", "upload", "(", "local_path", ",", "remote_path", ",", "properties", "=", "{", "}", ",", "headers", "=", "{", "}", ")", "artifact", "=", "Resource", "::", "Artifact", ".", "new", "(", "local_path", ":", "local_path", ")", "artifact", ".", "upload", "(", "key", ",", "remote_path", ",", "properties", ",", "headers", ")", "end" ]
Upload to a given repository @see Artifact#upload Upload syntax examples @return [Resource::Artifact]
[ "Upload", "to", "a", "given", "repository" ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/repository.rb#L114-L117
16,444
chef/artifactory-client
lib/artifactory/resources/repository.rb
Artifactory.Resource::Repository.upload_from_archive
def upload_from_archive(local_path, remote_path, properties = {}) artifact = Resource::Artifact.new(local_path: local_path) artifact.upload_from_archive(key, remote_path, properties) end
ruby
def upload_from_archive(local_path, remote_path, properties = {}) artifact = Resource::Artifact.new(local_path: local_path) artifact.upload_from_archive(key, remote_path, properties) end
[ "def", "upload_from_archive", "(", "local_path", ",", "remote_path", ",", "properties", "=", "{", "}", ")", "artifact", "=", "Resource", "::", "Artifact", ".", "new", "(", "local_path", ":", "local_path", ")", "artifact", ".", "upload_from_archive", "(", "key", ",", "remote_path", ",", "properties", ")", "end" ]
Upload an artifact with the given archive. Consult the artifactory documentation for the format of the archive to upload. @see Artifact#upload_from_archive More syntax examples
[ "Upload", "an", "artifact", "with", "the", "given", "archive", ".", "Consult", "the", "artifactory", "documentation", "for", "the", "format", "of", "the", "archive", "to", "upload", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/repository.rb#L137-L140
16,445
chef/artifactory-client
lib/artifactory/resources/repository.rb
Artifactory.Resource::Repository.artifacts
def artifacts @artifacts ||= Collection::Artifact.new(self, repos: key) do Resource::Artifact.search(name: ".*", repos: key) end end
ruby
def artifacts @artifacts ||= Collection::Artifact.new(self, repos: key) do Resource::Artifact.search(name: ".*", repos: key) end end
[ "def", "artifacts", "@artifacts", "||=", "Collection", "::", "Artifact", ".", "new", "(", "self", ",", "repos", ":", "key", ")", "do", "Resource", "::", "Artifact", ".", "search", "(", "name", ":", "\".*\"", ",", "repos", ":", "key", ")", "end", "end" ]
The list of artifacts in this repository on the remote artifactory server. @see Artifact.search Search syntax examples @example Get the list of artifacts for a repository repo = Repository.new('libs-release-local') repo.artifacts #=> [#<Resource::Artifacts>, ...] @return [Collection::Artifact] the list of artifacts
[ "The", "list", "of", "artifacts", "in", "this", "repository", "on", "the", "remote", "artifactory", "server", "." ]
01ce896edcda5410fa86f23f4c8096a1da91442e
https://github.com/chef/artifactory-client/blob/01ce896edcda5410fa86f23f4c8096a1da91442e/lib/artifactory/resources/repository.rb#L155-L159
16,446
stripe/subprocess
lib/subprocess.rb
Subprocess.Process.drain_fd
def drain_fd(fd, buf=nil) loop do tmp = fd.read_nonblock(4096) buf << tmp unless buf.nil? end rescue EOFError, Errno::EPIPE fd.close true rescue Errno::EINTR rescue Errno::EWOULDBLOCK, Errno::EAGAIN false end
ruby
def drain_fd(fd, buf=nil) loop do tmp = fd.read_nonblock(4096) buf << tmp unless buf.nil? end rescue EOFError, Errno::EPIPE fd.close true rescue Errno::EINTR rescue Errno::EWOULDBLOCK, Errno::EAGAIN false end
[ "def", "drain_fd", "(", "fd", ",", "buf", "=", "nil", ")", "loop", "do", "tmp", "=", "fd", ".", "read_nonblock", "(", "4096", ")", "buf", "<<", "tmp", "unless", "buf", ".", "nil?", "end", "rescue", "EOFError", ",", "Errno", "::", "EPIPE", "fd", ".", "close", "true", "rescue", "Errno", "::", "EINTR", "rescue", "Errno", "::", "EWOULDBLOCK", ",", "Errno", "::", "EAGAIN", "false", "end" ]
Do nonblocking reads from `fd`, appending all data read into `buf`. @param [IO] fd The file to read from. @param [String] buf A buffer to append the read data to. @return [true, false] Whether `fd` was closed due to an exceptional condition (`EOFError` or `EPIPE`).
[ "Do", "nonblocking", "reads", "from", "fd", "appending", "all", "data", "read", "into", "buf", "." ]
5bb3679fe8b155d15f708ad6b9a3dc65d3679e1a
https://github.com/stripe/subprocess/blob/5bb3679fe8b155d15f708ad6b9a3dc65d3679e1a/lib/subprocess.rb#L371-L382
16,447
stripe/subprocess
lib/subprocess.rb
Subprocess.Process.select_until
def select_until(read_array, write_array, err_array, timeout_at) if !timeout_at return IO.select(read_array, write_array, err_array) end remaining = (timeout_at - Time.now) return nil if remaining <= 0 IO.select(read_array, write_array, err_array, remaining) end
ruby
def select_until(read_array, write_array, err_array, timeout_at) if !timeout_at return IO.select(read_array, write_array, err_array) end remaining = (timeout_at - Time.now) return nil if remaining <= 0 IO.select(read_array, write_array, err_array, remaining) end
[ "def", "select_until", "(", "read_array", ",", "write_array", ",", "err_array", ",", "timeout_at", ")", "if", "!", "timeout_at", "return", "IO", ".", "select", "(", "read_array", ",", "write_array", ",", "err_array", ")", "end", "remaining", "=", "(", "timeout_at", "-", "Time", ".", "now", ")", "return", "nil", "if", "remaining", "<=", "0", "IO", ".", "select", "(", "read_array", ",", "write_array", ",", "err_array", ",", "remaining", ")", "end" ]
Call IO.select timing out at Time `timeout_at`. If `timeout_at` is nil, never times out.
[ "Call", "IO", ".", "select", "timing", "out", "at", "Time", "timeout_at", ".", "If", "timeout_at", "is", "nil", "never", "times", "out", "." ]
5bb3679fe8b155d15f708ad6b9a3dc65d3679e1a
https://github.com/stripe/subprocess/blob/5bb3679fe8b155d15f708ad6b9a3dc65d3679e1a/lib/subprocess.rb#L551-L560
16,448
Pathgather/predictor
lib/predictor/input_matrix.rb
Predictor.InputMatrix.remove_from_set
def remove_from_set(set, item) Predictor.redis.multi do |redis| redis.srem(redis_key(:items, set), item) redis.srem(redis_key(:sets, item), set) end end
ruby
def remove_from_set(set, item) Predictor.redis.multi do |redis| redis.srem(redis_key(:items, set), item) redis.srem(redis_key(:sets, item), set) end end
[ "def", "remove_from_set", "(", "set", ",", "item", ")", "Predictor", ".", "redis", ".", "multi", "do", "|", "redis", "|", "redis", ".", "srem", "(", "redis_key", "(", ":items", ",", "set", ")", ",", "item", ")", "redis", ".", "srem", "(", "redis_key", "(", ":sets", ",", "item", ")", ",", "set", ")", "end", "end" ]
Delete a specific relationship
[ "Delete", "a", "specific", "relationship" ]
09b7a98293ca976fed643d6b72498defe89b2779
https://github.com/Pathgather/predictor/blob/09b7a98293ca976fed643d6b72498defe89b2779/lib/predictor/input_matrix.rb#L43-L48
16,449
Pathgather/predictor
lib/predictor/input_matrix.rb
Predictor.InputMatrix.delete_item
def delete_item(item) Predictor.redis.watch(redis_key(:sets, item)) do sets = Predictor.redis.smembers(redis_key(:sets, item)) Predictor.redis.multi do |multi| sets.each do |set| multi.srem(redis_key(:items, set), item) end multi.del redis_key(:sets, item) end end end
ruby
def delete_item(item) Predictor.redis.watch(redis_key(:sets, item)) do sets = Predictor.redis.smembers(redis_key(:sets, item)) Predictor.redis.multi do |multi| sets.each do |set| multi.srem(redis_key(:items, set), item) end multi.del redis_key(:sets, item) end end end
[ "def", "delete_item", "(", "item", ")", "Predictor", ".", "redis", ".", "watch", "(", "redis_key", "(", ":sets", ",", "item", ")", ")", "do", "sets", "=", "Predictor", ".", "redis", ".", "smembers", "(", "redis_key", "(", ":sets", ",", "item", ")", ")", "Predictor", ".", "redis", ".", "multi", "do", "|", "multi", "|", "sets", ".", "each", "do", "|", "set", "|", "multi", ".", "srem", "(", "redis_key", "(", ":items", ",", "set", ")", ",", "item", ")", "end", "multi", ".", "del", "redis_key", "(", ":sets", ",", "item", ")", "end", "end", "end" ]
delete item from the matrix
[ "delete", "item", "from", "the", "matrix" ]
09b7a98293ca976fed643d6b72498defe89b2779
https://github.com/Pathgather/predictor/blob/09b7a98293ca976fed643d6b72498defe89b2779/lib/predictor/input_matrix.rb#L73-L84
16,450
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/authentication_context.rb
ADAL.AuthenticationContext.acquire_token_for_client
def acquire_token_for_client(resource, client_cred) fail_if_arguments_nil(resource, client_cred) token_request_for(client_cred).get_for_client(resource) end
ruby
def acquire_token_for_client(resource, client_cred) fail_if_arguments_nil(resource, client_cred) token_request_for(client_cred).get_for_client(resource) end
[ "def", "acquire_token_for_client", "(", "resource", ",", "client_cred", ")", "fail_if_arguments_nil", "(", "resource", ",", "client_cred", ")", "token_request_for", "(", "client_cred", ")", ".", "get_for_client", "(", "resource", ")", "end" ]
Gets an access token with only the clients credentials and no user information. @param String resource The resource being requested. @param ClientCredential|ClientAssertion|ClientAssertionCertificate An object that validates the client application by adding #request_params to the OAuth request. @return TokenResponse
[ "Gets", "an", "access", "token", "with", "only", "the", "clients", "credentials", "and", "no", "user", "information", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/authentication_context.rb#L76-L79
16,451
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/authentication_context.rb
ADAL.AuthenticationContext.acquire_token_with_authorization_code
def acquire_token_with_authorization_code( auth_code, redirect_uri, client_cred, resource = nil) fail_if_arguments_nil(auth_code, redirect_uri, client_cred) token_request_for(client_cred) .get_with_authorization_code(auth_code, redirect_uri, resource) end
ruby
def acquire_token_with_authorization_code( auth_code, redirect_uri, client_cred, resource = nil) fail_if_arguments_nil(auth_code, redirect_uri, client_cred) token_request_for(client_cred) .get_with_authorization_code(auth_code, redirect_uri, resource) end
[ "def", "acquire_token_with_authorization_code", "(", "auth_code", ",", "redirect_uri", ",", "client_cred", ",", "resource", "=", "nil", ")", "fail_if_arguments_nil", "(", "auth_code", ",", "redirect_uri", ",", "client_cred", ")", "token_request_for", "(", "client_cred", ")", ".", "get_with_authorization_code", "(", "auth_code", ",", "redirect_uri", ",", "resource", ")", "end" ]
Gets an access token with a previously acquire authorization code. @param String auth_code The authorization code that was issued by the authorization server. @param URI redirect_uri The URI that was passed to the authorization server with the request for the authorization code. @param ClientCredential|ClientAssertion|ClientAssertionCertificate An object that validates the client application by adding #request_params to the OAuth request. @optional String resource The resource being requested. @return TokenResponse
[ "Gets", "an", "access", "token", "with", "a", "previously", "acquire", "authorization", "code", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/authentication_context.rb#L95-L100
16,452
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/authentication_context.rb
ADAL.AuthenticationContext.acquire_token_with_refresh_token
def acquire_token_with_refresh_token( refresh_token, client_cred, resource = nil) fail_if_arguments_nil(refresh_token, client_cred) token_request_for(client_cred) .get_with_refresh_token(refresh_token, resource) end
ruby
def acquire_token_with_refresh_token( refresh_token, client_cred, resource = nil) fail_if_arguments_nil(refresh_token, client_cred) token_request_for(client_cred) .get_with_refresh_token(refresh_token, resource) end
[ "def", "acquire_token_with_refresh_token", "(", "refresh_token", ",", "client_cred", ",", "resource", "=", "nil", ")", "fail_if_arguments_nil", "(", "refresh_token", ",", "client_cred", ")", "token_request_for", "(", "client_cred", ")", ".", "get_with_refresh_token", "(", "refresh_token", ",", "resource", ")", "end" ]
Gets an access token using a previously acquire refresh token. @param String refresh_token The previously acquired refresh token. @param String|ClientCredential|ClientAssertion|ClientAssertionCertificate The client application can be validated in four different manners, depending on the OAuth flow. This object must support #request_params. @optional String resource The resource being requested. @return TokenResponse
[ "Gets", "an", "access", "token", "using", "a", "previously", "acquire", "refresh", "token", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/authentication_context.rb#L113-L118
16,453
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/authentication_context.rb
ADAL.AuthenticationContext.authorization_request_url
def authorization_request_url( resource, client_id, redirect_uri, extra_query_params = {}) @authority.authorize_endpoint( extra_query_params.reverse_merge( client_id: client_id, response_mode: FORM_POST, redirect_uri: redirect_uri, resource: resource, response_type: CODE)) end
ruby
def authorization_request_url( resource, client_id, redirect_uri, extra_query_params = {}) @authority.authorize_endpoint( extra_query_params.reverse_merge( client_id: client_id, response_mode: FORM_POST, redirect_uri: redirect_uri, resource: resource, response_type: CODE)) end
[ "def", "authorization_request_url", "(", "resource", ",", "client_id", ",", "redirect_uri", ",", "extra_query_params", "=", "{", "}", ")", "@authority", ".", "authorize_endpoint", "(", "extra_query_params", ".", "reverse_merge", "(", "client_id", ":", "client_id", ",", "response_mode", ":", "FORM_POST", ",", "redirect_uri", ":", "redirect_uri", ",", "resource", ":", "resource", ",", "response_type", ":", "CODE", ")", ")", "end" ]
Constructs a URL for an authorization endpoint using query parameters. @param String resource The intended recipient of the requested token. @param String client_id The identifier of the calling client application. @param URI redirect_uri The URI that the the authorization code should be sent back to. @optional Hash extra_query_params Any remaining query parameters to add to the URI. @return URI
[ "Constructs", "a", "URL", "for", "an", "authorization", "endpoint", "using", "query", "parameters", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/authentication_context.rb#L165-L174
16,454
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/client_assertion_certificate.rb
ADAL.ClientAssertionCertificate.request_params
def request_params jwt_assertion = SelfSignedJwtFactory .new(@client_id, @authority.token_endpoint) .create_and_sign_jwt(@certificate, @private_key) ClientAssertion.new(client_id, jwt_assertion).request_params end
ruby
def request_params jwt_assertion = SelfSignedJwtFactory .new(@client_id, @authority.token_endpoint) .create_and_sign_jwt(@certificate, @private_key) ClientAssertion.new(client_id, jwt_assertion).request_params end
[ "def", "request_params", "jwt_assertion", "=", "SelfSignedJwtFactory", ".", "new", "(", "@client_id", ",", "@authority", ".", "token_endpoint", ")", ".", "create_and_sign_jwt", "(", "@certificate", ",", "@private_key", ")", "ClientAssertion", ".", "new", "(", "client_id", ",", "jwt_assertion", ")", ".", "request_params", "end" ]
Creates a new ClientAssertionCertificate. @param Authority authority The authority object that will recognize this certificate. @param [String] client_id The client id of the calling application. @param [OpenSSL::PKCS12] pkcs12_file The PKCS12 file containing the certificate and private key. The relevant parameters from this credential for OAuth.
[ "Creates", "a", "new", "ClientAssertionCertificate", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/client_assertion_certificate.rb#L59-L64
16,455
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/user_credential.rb
ADAL.UserCredential.request_params
def request_params case account_type when AccountType::MANAGED managed_request_params when AccountType::FEDERATED federated_request_params else fail UnsupportedAccountTypeError, account_type end end
ruby
def request_params case account_type when AccountType::MANAGED managed_request_params when AccountType::FEDERATED federated_request_params else fail UnsupportedAccountTypeError, account_type end end
[ "def", "request_params", "case", "account_type", "when", "AccountType", "::", "MANAGED", "managed_request_params", "when", "AccountType", "::", "FEDERATED", "federated_request_params", "else", "fail", "UnsupportedAccountTypeError", ",", "account_type", "end", "end" ]
The OAuth parameters that respresent this UserCredential. @return Hash
[ "The", "OAuth", "parameters", "that", "respresent", "this", "UserCredential", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/user_credential.rb#L83-L92
16,456
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/wstrust_request.rb
ADAL.WSTrustRequest.execute
def execute(username, password) logger.verbose("Making a WSTrust request with action #{@action}.") request = Net::HTTP::Get.new(@endpoint.path) add_headers(request) request.body = rst(username, password) response = http(@endpoint).request(request) if response.code == '200' WSTrustResponse.parse(response.body) else fail WSTrustResponse::WSTrustError, "Failed request: code #{response.code}." end end
ruby
def execute(username, password) logger.verbose("Making a WSTrust request with action #{@action}.") request = Net::HTTP::Get.new(@endpoint.path) add_headers(request) request.body = rst(username, password) response = http(@endpoint).request(request) if response.code == '200' WSTrustResponse.parse(response.body) else fail WSTrustResponse::WSTrustError, "Failed request: code #{response.code}." end end
[ "def", "execute", "(", "username", ",", "password", ")", "logger", ".", "verbose", "(", "\"Making a WSTrust request with action #{@action}.\"", ")", "request", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "@endpoint", ".", "path", ")", "add_headers", "(", "request", ")", "request", ".", "body", "=", "rst", "(", "username", ",", "password", ")", "response", "=", "http", "(", "@endpoint", ")", ".", "request", "(", "request", ")", "if", "response", ".", "code", "==", "'200'", "WSTrustResponse", ".", "parse", "(", "response", ".", "body", ")", "else", "fail", "WSTrustResponse", "::", "WSTrustError", ",", "\"Failed request: code #{response.code}.\"", "end", "end" ]
Constructs a new WSTrustRequest. @param String|URI endpoint @param String action @param String applies_to Performs a WS-Trust RequestSecurityToken request with a username and password to obtain a federated token. @param String username @param String password @return WSTrustResponse
[ "Constructs", "a", "new", "WSTrustRequest", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/wstrust_request.rb#L69-L80
16,457
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/mex_request.rb
ADAL.MexRequest.execute
def execute request = Net::HTTP::Get.new(@endpoint.path) request.add_field('Content-Type', 'application/soap+xml') MexResponse.parse(http(@endpoint).request(request).body) end
ruby
def execute request = Net::HTTP::Get.new(@endpoint.path) request.add_field('Content-Type', 'application/soap+xml') MexResponse.parse(http(@endpoint).request(request).body) end
[ "def", "execute", "request", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "@endpoint", ".", "path", ")", "request", ".", "add_field", "(", "'Content-Type'", ",", "'application/soap+xml'", ")", "MexResponse", ".", "parse", "(", "http", "(", "@endpoint", ")", ".", "request", "(", "request", ")", ".", "body", ")", "end" ]
Constructs a MexRequest object for a specific URL endpoint. @param String|URI endpoint The Metadata Exchange endpoint. @return MexResponse
[ "Constructs", "a", "MexRequest", "object", "for", "a", "specific", "URL", "endpoint", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/mex_request.rb#L46-L50
16,458
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/authority.rb
ADAL.Authority.authorize_endpoint
def authorize_endpoint(params = nil) params = params.select { |_, v| !v.nil? } if params.respond_to? :select if params.nil? || params.empty? URI::HTTPS.build(host: @host, path: '/' + @tenant + AUTHORIZE_PATH) else URI::HTTPS.build(host: @host, path: '/' + @tenant + AUTHORIZE_PATH, query: URI.encode_www_form(params)) end end
ruby
def authorize_endpoint(params = nil) params = params.select { |_, v| !v.nil? } if params.respond_to? :select if params.nil? || params.empty? URI::HTTPS.build(host: @host, path: '/' + @tenant + AUTHORIZE_PATH) else URI::HTTPS.build(host: @host, path: '/' + @tenant + AUTHORIZE_PATH, query: URI.encode_www_form(params)) end end
[ "def", "authorize_endpoint", "(", "params", "=", "nil", ")", "params", "=", "params", ".", "select", "{", "|", "_", ",", "v", "|", "!", "v", ".", "nil?", "}", "if", "params", ".", "respond_to?", ":select", "if", "params", ".", "nil?", "||", "params", ".", "empty?", "URI", "::", "HTTPS", ".", "build", "(", "host", ":", "@host", ",", "path", ":", "'/'", "+", "@tenant", "+", "AUTHORIZE_PATH", ")", "else", "URI", "::", "HTTPS", ".", "build", "(", "host", ":", "@host", ",", "path", ":", "'/'", "+", "@tenant", "+", "AUTHORIZE_PATH", ",", "query", ":", "URI", ".", "encode_www_form", "(", "params", ")", ")", "end", "end" ]
URI that can be used to acquire authorization codes. @optional Hash params Query parameters that will added to the endpoint. @return [URI]
[ "URI", "that", "can", "be", "used", "to", "acquire", "authorization", "codes", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/authority.rb#L79-L88
16,459
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/authority.rb
ADAL.Authority.discovery_uri
def discovery_uri(host = WORLD_WIDE_AUTHORITY) URI(DISCOVERY_TEMPLATE.expand(host: host, endpoint: authorize_endpoint)) end
ruby
def discovery_uri(host = WORLD_WIDE_AUTHORITY) URI(DISCOVERY_TEMPLATE.expand(host: host, endpoint: authorize_endpoint)) end
[ "def", "discovery_uri", "(", "host", "=", "WORLD_WIDE_AUTHORITY", ")", "URI", "(", "DISCOVERY_TEMPLATE", ".", "expand", "(", "host", ":", "host", ",", "endpoint", ":", "authorize_endpoint", ")", ")", "end" ]
Creates an instance discovery endpoint url for authority that this object represents. @return [URI]
[ "Creates", "an", "instance", "discovery", "endpoint", "url", "for", "authority", "that", "this", "object", "represents", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/authority.rb#L122-L124
16,460
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/authority.rb
ADAL.Authority.validated_dynamically?
def validated_dynamically? logger.verbose("Attempting instance discovery at: #{discovery_uri}.") http_response = Net::HTTP.get(discovery_uri) if http_response.nil? logger.error('Dynamic validation received no response from endpoint.') return false end parse_dynamic_validation(JSON.parse(http_response)) end
ruby
def validated_dynamically? logger.verbose("Attempting instance discovery at: #{discovery_uri}.") http_response = Net::HTTP.get(discovery_uri) if http_response.nil? logger.error('Dynamic validation received no response from endpoint.') return false end parse_dynamic_validation(JSON.parse(http_response)) end
[ "def", "validated_dynamically?", "logger", ".", "verbose", "(", "\"Attempting instance discovery at: #{discovery_uri}.\"", ")", "http_response", "=", "Net", "::", "HTTP", ".", "get", "(", "discovery_uri", ")", "if", "http_response", ".", "nil?", "logger", ".", "error", "(", "'Dynamic validation received no response from endpoint.'", ")", "return", "false", "end", "parse_dynamic_validation", "(", "JSON", ".", "parse", "(", "http_response", ")", ")", "end" ]
Performs instance discovery via a network call to well known authorities. @return [String] The tenant discovery endpoint, if found. Otherwise nil.
[ "Performs", "instance", "discovery", "via", "a", "network", "call", "to", "well", "known", "authorities", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/authority.rb#L131-L139
16,461
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/wstrust_response.rb
ADAL.WSTrustResponse.grant_type
def grant_type case @token_type when TokenType::V1 TokenRequest::GrantType::SAML1 when TokenType::V2 TokenRequest::GrantType::SAML2 end end
ruby
def grant_type case @token_type when TokenType::V1 TokenRequest::GrantType::SAML1 when TokenType::V2 TokenRequest::GrantType::SAML2 end end
[ "def", "grant_type", "case", "@token_type", "when", "TokenType", "::", "V1", "TokenRequest", "::", "GrantType", "::", "SAML1", "when", "TokenType", "::", "V2", "TokenRequest", "::", "GrantType", "::", "SAML2", "end", "end" ]
Constructs a WSTrustResponse. @param String token The content of the returned token. @param WSTrustResponse::TokenType token_type The type of the token contained within the WS-Trust response. Gets the OAuth grant type for the SAML token type of the response. @return TokenRequest::GrantType
[ "Constructs", "a", "WSTrustResponse", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/wstrust_response.rb#L159-L166
16,462
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/self_signed_jwt_factory.rb
ADAL.SelfSignedJwtFactory.create_and_sign_jwt
def create_and_sign_jwt(certificate, private_key) JWT.encode(payload, private_key, RS256, header(certificate)) end
ruby
def create_and_sign_jwt(certificate, private_key) JWT.encode(payload, private_key, RS256, header(certificate)) end
[ "def", "create_and_sign_jwt", "(", "certificate", ",", "private_key", ")", "JWT", ".", "encode", "(", "payload", ",", "private_key", ",", "RS256", ",", "header", "(", "certificate", ")", ")", "end" ]
Constructs a new SelfSignedJwtFactory. @param String client_id The client id of the calling application. @param String token_endpoint The token endpoint that will accept the certificate. Creates a JWT from a client certificate and signs it with a private key. @param OpenSSL::X509::Certificate certificate The certifcate object to be converted to a JWT and signed for use in an authentication flow. @param OpenSSL::PKey::RSA private_key The private key used to sign the certificate. @return String
[ "Constructs", "a", "new", "SelfSignedJwtFactory", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/self_signed_jwt_factory.rb#L57-L59
16,463
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/self_signed_jwt_factory.rb
ADAL.SelfSignedJwtFactory.header
def header(certificate) x5t = thumbprint(certificate) logger.verbose("Creating self signed JWT header with thumbprint: #{x5t}.") { TYPE => TYPE_JWT, ALGORITHM => RS256, THUMBPRINT => x5t } end
ruby
def header(certificate) x5t = thumbprint(certificate) logger.verbose("Creating self signed JWT header with thumbprint: #{x5t}.") { TYPE => TYPE_JWT, ALGORITHM => RS256, THUMBPRINT => x5t } end
[ "def", "header", "(", "certificate", ")", "x5t", "=", "thumbprint", "(", "certificate", ")", "logger", ".", "verbose", "(", "\"Creating self signed JWT header with thumbprint: #{x5t}.\"", ")", "{", "TYPE", "=>", "TYPE_JWT", ",", "ALGORITHM", "=>", "RS256", ",", "THUMBPRINT", "=>", "x5t", "}", "end" ]
The JWT header for a certificate to be encoded.
[ "The", "JWT", "header", "for", "a", "certificate", "to", "be", "encoded", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/self_signed_jwt_factory.rb#L64-L70
16,464
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/self_signed_jwt_factory.rb
ADAL.SelfSignedJwtFactory.payload
def payload now = Time.now - 1 expires = now + 60 * SELF_SIGNED_JWT_LIFETIME logger.verbose("Creating self signed JWT payload. Expires: #{expires}. " \ "NotBefore: #{now}.") { AUDIENCE => @token_endpoint, ISSUER => @client_id, SUBJECT => @client_id, NOT_BEFORE => now.to_i, EXPIRES_ON => expires.to_i, JWT_ID => SecureRandom.uuid } end
ruby
def payload now = Time.now - 1 expires = now + 60 * SELF_SIGNED_JWT_LIFETIME logger.verbose("Creating self signed JWT payload. Expires: #{expires}. " \ "NotBefore: #{now}.") { AUDIENCE => @token_endpoint, ISSUER => @client_id, SUBJECT => @client_id, NOT_BEFORE => now.to_i, EXPIRES_ON => expires.to_i, JWT_ID => SecureRandom.uuid } end
[ "def", "payload", "now", "=", "Time", ".", "now", "-", "1", "expires", "=", "now", "+", "60", "*", "SELF_SIGNED_JWT_LIFETIME", "logger", ".", "verbose", "(", "\"Creating self signed JWT payload. Expires: #{expires}. \"", "\"NotBefore: #{now}.\"", ")", "{", "AUDIENCE", "=>", "@token_endpoint", ",", "ISSUER", "=>", "@client_id", ",", "SUBJECT", "=>", "@client_id", ",", "NOT_BEFORE", "=>", "now", ".", "to_i", ",", "EXPIRES_ON", "=>", "expires", ".", "to_i", ",", "JWT_ID", "=>", "SecureRandom", ".", "uuid", "}", "end" ]
The JWT payload.
[ "The", "JWT", "payload", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/self_signed_jwt_factory.rb#L73-L84
16,465
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/token_request.rb
ADAL.TokenRequest.get_for_client
def get_for_client(resource) logger.verbose("TokenRequest getting token for client for #{resource}.") request(GRANT_TYPE => GrantType::CLIENT_CREDENTIALS, RESOURCE => resource) end
ruby
def get_for_client(resource) logger.verbose("TokenRequest getting token for client for #{resource}.") request(GRANT_TYPE => GrantType::CLIENT_CREDENTIALS, RESOURCE => resource) end
[ "def", "get_for_client", "(", "resource", ")", "logger", ".", "verbose", "(", "\"TokenRequest getting token for client for #{resource}.\"", ")", "request", "(", "GRANT_TYPE", "=>", "GrantType", "::", "CLIENT_CREDENTIALS", ",", "RESOURCE", "=>", "resource", ")", "end" ]
Gets a token based solely on the clients credentials that were used to initialize the token request. @param String resource The resource for which the requested access token will provide access. @return TokenResponse
[ "Gets", "a", "token", "based", "solely", "on", "the", "clients", "credentials", "that", "were", "used", "to", "initialize", "the", "token", "request", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/token_request.rb#L82-L86
16,466
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/token_request.rb
ADAL.TokenRequest.get_with_authorization_code
def get_with_authorization_code(auth_code, redirect_uri, resource = nil) logger.verbose('TokenRequest getting token with authorization code ' \ "#{auth_code}, redirect_uri #{redirect_uri} and " \ "resource #{resource}.") request(CODE => auth_code, GRANT_TYPE => GrantType::AUTHORIZATION_CODE, REDIRECT_URI => URI.parse(redirect_uri.to_s), RESOURCE => resource) end
ruby
def get_with_authorization_code(auth_code, redirect_uri, resource = nil) logger.verbose('TokenRequest getting token with authorization code ' \ "#{auth_code}, redirect_uri #{redirect_uri} and " \ "resource #{resource}.") request(CODE => auth_code, GRANT_TYPE => GrantType::AUTHORIZATION_CODE, REDIRECT_URI => URI.parse(redirect_uri.to_s), RESOURCE => resource) end
[ "def", "get_with_authorization_code", "(", "auth_code", ",", "redirect_uri", ",", "resource", "=", "nil", ")", "logger", ".", "verbose", "(", "'TokenRequest getting token with authorization code '", "\"#{auth_code}, redirect_uri #{redirect_uri} and \"", "\"resource #{resource}.\"", ")", "request", "(", "CODE", "=>", "auth_code", ",", "GRANT_TYPE", "=>", "GrantType", "::", "AUTHORIZATION_CODE", ",", "REDIRECT_URI", "=>", "URI", ".", "parse", "(", "redirect_uri", ".", "to_s", ")", ",", "RESOURCE", "=>", "resource", ")", "end" ]
Gets a token based on a previously acquired authentication code. @param String auth_code An authentication code that was previously acquired from an authentication endpoint. @param String redirect_uri The redirect uri that was passed to the authentication endpoint when the auth code was acquired. @optional String resource The resource for which the requested access token will provide access. @return TokenResponse
[ "Gets", "a", "token", "based", "on", "a", "previously", "acquired", "authentication", "code", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/token_request.rb#L100-L108
16,467
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/token_request.rb
ADAL.TokenRequest.get_with_refresh_token
def get_with_refresh_token(refresh_token, resource = nil) logger.verbose('TokenRequest getting token with refresh token digest ' \ "#{Digest::SHA256.hexdigest refresh_token} and resource " \ "#{resource}.") request_no_cache(GRANT_TYPE => GrantType::REFRESH_TOKEN, REFRESH_TOKEN => refresh_token, RESOURCE => resource) end
ruby
def get_with_refresh_token(refresh_token, resource = nil) logger.verbose('TokenRequest getting token with refresh token digest ' \ "#{Digest::SHA256.hexdigest refresh_token} and resource " \ "#{resource}.") request_no_cache(GRANT_TYPE => GrantType::REFRESH_TOKEN, REFRESH_TOKEN => refresh_token, RESOURCE => resource) end
[ "def", "get_with_refresh_token", "(", "refresh_token", ",", "resource", "=", "nil", ")", "logger", ".", "verbose", "(", "'TokenRequest getting token with refresh token digest '", "\"#{Digest::SHA256.hexdigest refresh_token} and resource \"", "\"#{resource}.\"", ")", "request_no_cache", "(", "GRANT_TYPE", "=>", "GrantType", "::", "REFRESH_TOKEN", ",", "REFRESH_TOKEN", "=>", "refresh_token", ",", "RESOURCE", "=>", "resource", ")", "end" ]
Gets a token based on a previously acquired refresh token. @param String refresh_token The refresh token that was previously acquired from a token response. @optional String resource The resource for which the requested access token will provide access. @return TokenResponse
[ "Gets", "a", "token", "based", "on", "a", "previously", "acquired", "refresh", "token", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/token_request.rb#L118-L125
16,468
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/token_request.rb
ADAL.TokenRequest.get_with_user_credential
def get_with_user_credential(user_cred, resource = nil) logger.verbose('TokenRequest getting token with user credential ' \ "#{user_cred} and resource #{resource}.") oauth = if user_cred.is_a? UserIdentifier lambda do fail UserCredentialError, 'UserIdentifier can only be used once there is a ' \ 'matching token in the cache.' end end || -> {} request(user_cred.request_params.merge(RESOURCE => resource), &oauth) end
ruby
def get_with_user_credential(user_cred, resource = nil) logger.verbose('TokenRequest getting token with user credential ' \ "#{user_cred} and resource #{resource}.") oauth = if user_cred.is_a? UserIdentifier lambda do fail UserCredentialError, 'UserIdentifier can only be used once there is a ' \ 'matching token in the cache.' end end || -> {} request(user_cred.request_params.merge(RESOURCE => resource), &oauth) end
[ "def", "get_with_user_credential", "(", "user_cred", ",", "resource", "=", "nil", ")", "logger", ".", "verbose", "(", "'TokenRequest getting token with user credential '", "\"#{user_cred} and resource #{resource}.\"", ")", "oauth", "=", "if", "user_cred", ".", "is_a?", "UserIdentifier", "lambda", "do", "fail", "UserCredentialError", ",", "'UserIdentifier can only be used once there is a '", "'matching token in the cache.'", "end", "end", "||", "->", "{", "}", "request", "(", "user_cred", ".", "request_params", ".", "merge", "(", "RESOURCE", "=>", "resource", ")", ",", "oauth", ")", "end" ]
Gets a token based on possessing the users credentials. @param UserCredential|UserIdentifier user_cred Something that can be used to verify the user. Typically a username and password. If it is a UserIdentifier, only the cache will be checked. If a matching token is not there, it will fail. @optional String resource The resource for which the requested access token will provide access. @return TokenResponse
[ "Gets", "a", "token", "based", "on", "possessing", "the", "users", "credentials", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/token_request.rb#L137-L148
16,469
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/token_request.rb
ADAL.TokenRequest.request
def request(params, &block) cached_token = check_cache(request_params(params)) return cached_token if cached_token cache_response(request_no_cache(request_params(params), &block)) end
ruby
def request(params, &block) cached_token = check_cache(request_params(params)) return cached_token if cached_token cache_response(request_no_cache(request_params(params), &block)) end
[ "def", "request", "(", "params", ",", "&", "block", ")", "cached_token", "=", "check_cache", "(", "request_params", "(", "params", ")", ")", "return", "cached_token", "if", "cached_token", "cache_response", "(", "request_no_cache", "(", "request_params", "(", "params", ")", ",", "block", ")", ")", "end" ]
Attempts to fulfill a token request, first via the token cache and then through OAuth. @param Hash params Any additional request parameters that should be used. @return TokenResponse
[ "Attempts", "to", "fulfill", "a", "token", "request", "first", "via", "the", "token", "cache", "and", "then", "through", "OAuth", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/token_request.rb#L168-L172
16,470
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/cache_driver.rb
ADAL.CacheDriver.add
def add(token_response) return unless token_response.instance_of? SuccessResponse logger.verbose('Adding successful TokenResponse to cache.') entry = CachedTokenResponse.new(@client, @authority, token_response) update_refresh_tokens(entry) if entry.mrrt? @token_cache.add(entry) end
ruby
def add(token_response) return unless token_response.instance_of? SuccessResponse logger.verbose('Adding successful TokenResponse to cache.') entry = CachedTokenResponse.new(@client, @authority, token_response) update_refresh_tokens(entry) if entry.mrrt? @token_cache.add(entry) end
[ "def", "add", "(", "token_response", ")", "return", "unless", "token_response", ".", "instance_of?", "SuccessResponse", "logger", ".", "verbose", "(", "'Adding successful TokenResponse to cache.'", ")", "entry", "=", "CachedTokenResponse", ".", "new", "(", "@client", ",", "@authority", ",", "token_response", ")", "update_refresh_tokens", "(", "entry", ")", "if", "entry", ".", "mrrt?", "@token_cache", ".", "add", "(", "entry", ")", "end" ]
Constructs a CacheDriver to interact with a token cache. @param String authority The URL of the authority endpoint. @param ClientAssertion|ClientCredential|etc client The credentials representing the calling application. We need this instead of just the client id so that the tokens can be refreshed if necessary. @param TokenCache token_cache The cache implementation to store tokens. @optional Fixnum expiration_buffer_sec The number of seconds to use as a leeway when dealing with cache expiry. Checks if a TokenResponse is successful and if so adds it to the token cache for future retrieval. @param SuccessResponse token_response The successful token response to be cached. If it is not successful, it fails silently.
[ "Constructs", "a", "CacheDriver", "to", "interact", "with", "a", "token", "cache", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/cache_driver.rb#L69-L75
16,471
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/cache_driver.rb
ADAL.CacheDriver.find
def find(query = {}) query = query.map { |k, v| [FIELDS[k], v] if FIELDS[k] }.compact.to_h resource = query.delete(RESOURCE) matches = validate( find_all_cached_entries( query.reverse_merge( authority: @authority, client_id: @client.client_id)) ) resource_specific(matches, resource) || refresh_mrrt(matches, resource) end
ruby
def find(query = {}) query = query.map { |k, v| [FIELDS[k], v] if FIELDS[k] }.compact.to_h resource = query.delete(RESOURCE) matches = validate( find_all_cached_entries( query.reverse_merge( authority: @authority, client_id: @client.client_id)) ) resource_specific(matches, resource) || refresh_mrrt(matches, resource) end
[ "def", "find", "(", "query", "=", "{", "}", ")", "query", "=", "query", ".", "map", "{", "|", "k", ",", "v", "|", "[", "FIELDS", "[", "k", "]", ",", "v", "]", "if", "FIELDS", "[", "k", "]", "}", ".", "compact", ".", "to_h", "resource", "=", "query", ".", "delete", "(", "RESOURCE", ")", "matches", "=", "validate", "(", "find_all_cached_entries", "(", "query", ".", "reverse_merge", "(", "authority", ":", "@authority", ",", "client_id", ":", "@client", ".", "client_id", ")", ")", ")", "resource_specific", "(", "matches", ",", "resource", ")", "||", "refresh_mrrt", "(", "matches", ",", "resource", ")", "end" ]
Searches the cache for a token matching a specific query of fields. @param Hash query The fields to match against. @return TokenResponse
[ "Searches", "the", "cache", "for", "a", "token", "matching", "a", "specific", "query", "of", "fields", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/cache_driver.rb#L83-L92
16,472
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/cache_driver.rb
ADAL.CacheDriver.find_all_cached_entries
def find_all_cached_entries(query) logger.verbose("Searching cache for tokens by keys: #{query.keys}.") @token_cache.find do |entry| query.map do |k, v| (entry.respond_to? k.to_sym) && (v == entry.send(k.to_sym)) end.reduce(:&) end end
ruby
def find_all_cached_entries(query) logger.verbose("Searching cache for tokens by keys: #{query.keys}.") @token_cache.find do |entry| query.map do |k, v| (entry.respond_to? k.to_sym) && (v == entry.send(k.to_sym)) end.reduce(:&) end end
[ "def", "find_all_cached_entries", "(", "query", ")", "logger", ".", "verbose", "(", "\"Searching cache for tokens by keys: #{query.keys}.\"", ")", "@token_cache", ".", "find", "do", "|", "entry", "|", "query", ".", "map", "do", "|", "k", ",", "v", "|", "(", "entry", ".", "respond_to?", "k", ".", "to_sym", ")", "&&", "(", "v", "==", "entry", ".", "send", "(", "k", ".", "to_sym", ")", ")", "end", ".", "reduce", "(", ":&", ")", "end", "end" ]
All cache entries that match a query. This matches keys in values against a hash to method calls on an object. @param Hash query The fields to be matched and the values to match them to. @return Array<CachedTokenResponse>
[ "All", "cache", "entries", "that", "match", "a", "query", ".", "This", "matches", "keys", "in", "values", "against", "a", "hash", "to", "method", "calls", "on", "an", "object", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/cache_driver.rb#L103-L110
16,473
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/cache_driver.rb
ADAL.CacheDriver.refresh_mrrt
def refresh_mrrt(responses, resource) logger.verbose("Attempting to obtain access token for #{resource} by " \ "refreshing 1 of #{responses.count(&:mrrt?)} matching " \ 'MRRTs.') responses.each do |response| if response.mrrt? refresh_response = response.refresh(resource) return refresh_response if add(refresh_response) end end nil end
ruby
def refresh_mrrt(responses, resource) logger.verbose("Attempting to obtain access token for #{resource} by " \ "refreshing 1 of #{responses.count(&:mrrt?)} matching " \ 'MRRTs.') responses.each do |response| if response.mrrt? refresh_response = response.refresh(resource) return refresh_response if add(refresh_response) end end nil end
[ "def", "refresh_mrrt", "(", "responses", ",", "resource", ")", "logger", ".", "verbose", "(", "\"Attempting to obtain access token for #{resource} by \"", "\"refreshing 1 of #{responses.count(&:mrrt?)} matching \"", "'MRRTs.'", ")", "responses", ".", "each", "do", "|", "response", "|", "if", "response", ".", "mrrt?", "refresh_response", "=", "response", ".", "refresh", "(", "resource", ")", "return", "refresh_response", "if", "add", "(", "refresh_response", ")", "end", "end", "nil", "end" ]
Attempts to obtain an access token for a resource with refresh tokens from a list of MRRTs. @param Array[CachedTokenResponse] @return SuccessResponse|nil
[ "Attempts", "to", "obtain", "an", "access", "token", "for", "a", "resource", "with", "refresh", "tokens", "from", "a", "list", "of", "MRRTs", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/cache_driver.rb#L118-L129
16,474
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/cache_driver.rb
ADAL.CacheDriver.resource_specific
def resource_specific(responses, resource) logger.verbose("Looking through #{responses.size} matching cache " \ "entries for resource #{resource}.") responses.select { |response| response.resource == resource } .map(&:token_response).first end
ruby
def resource_specific(responses, resource) logger.verbose("Looking through #{responses.size} matching cache " \ "entries for resource #{resource}.") responses.select { |response| response.resource == resource } .map(&:token_response).first end
[ "def", "resource_specific", "(", "responses", ",", "resource", ")", "logger", ".", "verbose", "(", "\"Looking through #{responses.size} matching cache \"", "\"entries for resource #{resource}.\"", ")", "responses", ".", "select", "{", "|", "response", "|", "response", ".", "resource", "==", "resource", "}", ".", "map", "(", ":token_response", ")", ".", "first", "end" ]
Searches a list of CachedTokenResponses for one that matches the resource. @param Array[CachedTokenResponse] @return SuccessResponse|nil
[ "Searches", "a", "list", "of", "CachedTokenResponses", "for", "one", "that", "matches", "the", "resource", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/cache_driver.rb#L136-L141
16,475
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/cache_driver.rb
ADAL.CacheDriver.update_refresh_tokens
def update_refresh_tokens(mrrt) fail ArgumentError, 'Token must contain an MRRT.' unless mrrt.mrrt? @token_cache.find.each do |entry| entry.refresh_token = mrrt.refresh_token if mrrt.can_refresh?(entry) end end
ruby
def update_refresh_tokens(mrrt) fail ArgumentError, 'Token must contain an MRRT.' unless mrrt.mrrt? @token_cache.find.each do |entry| entry.refresh_token = mrrt.refresh_token if mrrt.can_refresh?(entry) end end
[ "def", "update_refresh_tokens", "(", "mrrt", ")", "fail", "ArgumentError", ",", "'Token must contain an MRRT.'", "unless", "mrrt", ".", "mrrt?", "@token_cache", ".", "find", ".", "each", "do", "|", "entry", "|", "entry", ".", "refresh_token", "=", "mrrt", ".", "refresh_token", "if", "mrrt", ".", "can_refresh?", "(", "entry", ")", "end", "end" ]
Updates the refresh tokens of all tokens in the cache that match a given MRRT. @param CachedTokenResponse mrrt A new MRRT containing a refresh token to update other matching cache entries with.
[ "Updates", "the", "refresh", "tokens", "of", "all", "tokens", "in", "the", "cache", "that", "match", "a", "given", "MRRT", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/cache_driver.rb#L150-L155
16,476
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/cache_driver.rb
ADAL.CacheDriver.validate
def validate(entries) logger.verbose("Validating #{entries.size} possible cache matches.") valid_entries = entries.group_by(&:validate) @token_cache.remove(valid_entries[false] || []) valid_entries[true] || [] end
ruby
def validate(entries) logger.verbose("Validating #{entries.size} possible cache matches.") valid_entries = entries.group_by(&:validate) @token_cache.remove(valid_entries[false] || []) valid_entries[true] || [] end
[ "def", "validate", "(", "entries", ")", "logger", ".", "verbose", "(", "\"Validating #{entries.size} possible cache matches.\"", ")", "valid_entries", "=", "entries", ".", "group_by", "(", ":validate", ")", "@token_cache", ".", "remove", "(", "valid_entries", "[", "false", "]", "||", "[", "]", ")", "valid_entries", "[", "true", "]", "||", "[", "]", "end" ]
Checks if an array of current cache entries are still valid, attempts to refresh those that have expired and discards those that cannot be. @param Array[CachedTokenResponse] entries The tokens to validate. @return Array[CachedTokenResponse]
[ "Checks", "if", "an", "array", "of", "current", "cache", "entries", "are", "still", "valid", "attempts", "to", "refresh", "those", "that", "have", "expired", "and", "discards", "those", "that", "cannot", "be", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/cache_driver.rb#L164-L169
16,477
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/cached_token_response.rb
ADAL.CachedTokenResponse.to_json
def to_json(_ = nil) JSON.unparse(authority: [authority.host, authority.tenant], client_id: client_id, token_response: token_response) end
ruby
def to_json(_ = nil) JSON.unparse(authority: [authority.host, authority.tenant], client_id: client_id, token_response: token_response) end
[ "def", "to_json", "(", "_", "=", "nil", ")", "JSON", ".", "unparse", "(", "authority", ":", "[", "authority", ".", "host", ",", "authority", ".", "tenant", "]", ",", "client_id", ":", "client_id", ",", "token_response", ":", "token_response", ")", "end" ]
Constructs a new CachedTokenResponse. @param ClientCredential|ClientAssertion|ClientAssertionCertificate The credentials of the calling client application. @param Authority authority The ADAL::Authority object that the response was retrieved from. @param SuccessResponse token_response The token response to be cached. Converts the fields in this object and its proxied SuccessResponse into a JSON string. @param JSON::Ext::Generator::State We don't care about the state, but JSON::unparse requires this. @return String
[ "Constructs", "a", "new", "CachedTokenResponse", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/cached_token_response.rb#L61-L65
16,478
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/cached_token_response.rb
ADAL.CachedTokenResponse.can_refresh?
def can_refresh?(other) mrrt? && (authority == other.authority) && (user_info == other.user_info) && (client_id == other.client_id) end
ruby
def can_refresh?(other) mrrt? && (authority == other.authority) && (user_info == other.user_info) && (client_id == other.client_id) end
[ "def", "can_refresh?", "(", "other", ")", "mrrt?", "&&", "(", "authority", "==", "other", ".", "authority", ")", "&&", "(", "user_info", "==", "other", ".", "user_info", ")", "&&", "(", "client_id", "==", "other", ".", "client_id", ")", "end" ]
Determines if self can be used to refresh other. @param CachedTokenResponse other @return Boolean
[ "Determines", "if", "self", "can", "be", "used", "to", "refresh", "other", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/cached_token_response.rb#L85-L88
16,479
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/cached_token_response.rb
ADAL.CachedTokenResponse.validate
def validate(expiration_buffer_sec = 0) return true if (Time.now + expiration_buffer_sec).to_i < expires_on unless refresh_token logger.verbose('Cached token is almost expired but no refresh token ' \ 'is available.') return false end logger.verbose('Cached token is almost expired, attempting to refresh ' \ ' with refresh token.') refresh_response = refresh if refresh_response.instance_of? SuccessResponse logger.verbose('Successfully refreshed token in cache.') @token_response = refresh_response true else logger.warn('Failed to refresh token in cache with refresh token.') false end end
ruby
def validate(expiration_buffer_sec = 0) return true if (Time.now + expiration_buffer_sec).to_i < expires_on unless refresh_token logger.verbose('Cached token is almost expired but no refresh token ' \ 'is available.') return false end logger.verbose('Cached token is almost expired, attempting to refresh ' \ ' with refresh token.') refresh_response = refresh if refresh_response.instance_of? SuccessResponse logger.verbose('Successfully refreshed token in cache.') @token_response = refresh_response true else logger.warn('Failed to refresh token in cache with refresh token.') false end end
[ "def", "validate", "(", "expiration_buffer_sec", "=", "0", ")", "return", "true", "if", "(", "Time", ".", "now", "+", "expiration_buffer_sec", ")", ".", "to_i", "<", "expires_on", "unless", "refresh_token", "logger", ".", "verbose", "(", "'Cached token is almost expired but no refresh token '", "'is available.'", ")", "return", "false", "end", "logger", ".", "verbose", "(", "'Cached token is almost expired, attempting to refresh '", "' with refresh token.'", ")", "refresh_response", "=", "refresh", "if", "refresh_response", ".", "instance_of?", "SuccessResponse", "logger", ".", "verbose", "(", "'Successfully refreshed token in cache.'", ")", "@token_response", "=", "refresh_response", "true", "else", "logger", ".", "warn", "(", "'Failed to refresh token in cache with refresh token.'", ")", "false", "end", "end" ]
If the access token is within the expiration buffer of expiring, an attempt will be made to retrieve a new token with the refresh token. @param Fixnum expiration_buffer_sec The number of seconds to use as leeway in determining if the token is expired. A positive buffer will refresh the token early while a negative buffer will refresh it late. Used to counter clock skew and network latency. @return Boolean True if the token is still valid (even if it was refreshed). False if the token is expired an unable to be refreshed.
[ "If", "the", "access", "token", "is", "within", "the", "expiration", "buffer", "of", "expiring", "an", "attempt", "will", "be", "made", "to", "retrieve", "a", "new", "token", "with", "the", "refresh", "token", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/cached_token_response.rb#L102-L120
16,480
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/cached_token_response.rb
ADAL.CachedTokenResponse.refresh
def refresh(new_resource = resource) token_response = TokenRequest .new(authority, @client) .get_with_refresh_token(refresh_token, new_resource) if token_response.instance_of? SuccessResponse token_response.parse_id_token(id_token) end token_response end
ruby
def refresh(new_resource = resource) token_response = TokenRequest .new(authority, @client) .get_with_refresh_token(refresh_token, new_resource) if token_response.instance_of? SuccessResponse token_response.parse_id_token(id_token) end token_response end
[ "def", "refresh", "(", "new_resource", "=", "resource", ")", "token_response", "=", "TokenRequest", ".", "new", "(", "authority", ",", "@client", ")", ".", "get_with_refresh_token", "(", "refresh_token", ",", "new_resource", ")", "if", "token_response", ".", "instance_of?", "SuccessResponse", "token_response", ".", "parse_id_token", "(", "id_token", ")", "end", "token_response", "end" ]
Attempts to refresh the access token for a given resource. Note that you can call this method with a different resource even if the token is not an MRRT, but it will fail @param String resource The resource that the new access token is beign requested for. Defaults to using the same resource as the original token. @return TokenResponse
[ "Attempts", "to", "refresh", "the", "access", "token", "for", "a", "given", "resource", ".", "Note", "that", "you", "can", "call", "this", "method", "with", "a", "different", "resource", "even", "if", "the", "token", "is", "not", "an", "MRRT", "but", "it", "will", "fail" ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/cached_token_response.rb#L131-L139
16,481
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/util.rb
ADAL.Util.string_hash
def string_hash(hash) hash.map { |k, v| [k.to_s, v.to_s] }.to_h end
ruby
def string_hash(hash) hash.map { |k, v| [k.to_s, v.to_s] }.to_h end
[ "def", "string_hash", "(", "hash", ")", "hash", ".", "map", "{", "|", "k", ",", "v", "|", "[", "k", ".", "to_s", ",", "v", ".", "to_s", "]", "}", ".", "to_h", "end" ]
Converts every key and value of a hash to string. @param Hash @return Hash
[ "Converts", "every", "key", "and", "value", "of", "a", "hash", "to", "string", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/util.rb#L45-L47
16,482
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/memory_cache.rb
ADAL.MemoryCache.add
def add(entries) entries = Array(entries) # If entries is an array, this is a no-op. old_size = @entries.size @entries |= entries logger.verbose("Added #{entries.size - old_size} new entries to cache.") end
ruby
def add(entries) entries = Array(entries) # If entries is an array, this is a no-op. old_size = @entries.size @entries |= entries logger.verbose("Added #{entries.size - old_size} new entries to cache.") end
[ "def", "add", "(", "entries", ")", "entries", "=", "Array", "(", "entries", ")", "# If entries is an array, this is a no-op.", "old_size", "=", "@entries", ".", "size", "@entries", "|=", "entries", "logger", ".", "verbose", "(", "\"Added #{entries.size - old_size} new entries to cache.\"", ")", "end" ]
Adds an array of objects to the cache. @param Array The entries to add. @return Array The entries after the addition.
[ "Adds", "an", "array", "of", "objects", "to", "the", "cache", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/memory_cache.rb#L43-L48
16,483
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/oauth_request.rb
ADAL.OAuthRequest.execute
def execute request = Net::HTTP::Post.new(@endpoint_uri.path) add_headers(request) request.body = URI.encode_www_form(string_hash(params)) TokenResponse.parse(http(@endpoint_uri).request(request).body) end
ruby
def execute request = Net::HTTP::Post.new(@endpoint_uri.path) add_headers(request) request.body = URI.encode_www_form(string_hash(params)) TokenResponse.parse(http(@endpoint_uri).request(request).body) end
[ "def", "execute", "request", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "@endpoint_uri", ".", "path", ")", "add_headers", "(", "request", ")", "request", ".", "body", "=", "URI", ".", "encode_www_form", "(", "string_hash", "(", "params", ")", ")", "TokenResponse", ".", "parse", "(", "http", "(", "@endpoint_uri", ")", ".", "request", "(", "request", ")", ".", "body", ")", "end" ]
Requests and waits for a token from the endpoint. @return TokenResponse
[ "Requests", "and", "waits", "for", "a", "token", "from", "the", "endpoint", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/oauth_request.rb#L52-L57
16,484
AzureAD/azure-activedirectory-library-for-ruby
lib/adal/oauth_request.rb
ADAL.OAuthRequest.add_headers
def add_headers(request) return if Logging.correlation_id.nil? request.add_field(CLIENT_REQUEST_ID.to_s, Logging.correlation_id) request.add_field(CLIENT_RETURN_CLIENT_REQUEST_ID.to_s, true) end
ruby
def add_headers(request) return if Logging.correlation_id.nil? request.add_field(CLIENT_REQUEST_ID.to_s, Logging.correlation_id) request.add_field(CLIENT_RETURN_CLIENT_REQUEST_ID.to_s, true) end
[ "def", "add_headers", "(", "request", ")", "return", "if", "Logging", ".", "correlation_id", ".", "nil?", "request", ".", "add_field", "(", "CLIENT_REQUEST_ID", ".", "to_s", ",", "Logging", ".", "correlation_id", ")", "request", ".", "add_field", "(", "CLIENT_RETURN_CLIENT_REQUEST_ID", ".", "to_s", ",", "true", ")", "end" ]
Adds the necessary OAuth headers. @param Net::HTTPGenericRequest
[ "Adds", "the", "necessary", "OAuth", "headers", "." ]
5d2f2530298a2545ca8caf688eabcd1143ffa304
https://github.com/AzureAD/azure-activedirectory-library-for-ruby/blob/5d2f2530298a2545ca8caf688eabcd1143ffa304/lib/adal/oauth_request.rb#L65-L69
16,485
castle/ruby-u2f
lib/u2f/u2f.rb
U2F.U2F.authenticate!
def authenticate!(challenge, response, registration_public_key, registration_counter) # TODO: check that it's the correct key_handle as well raise NoMatchingRequestError unless challenge == response.client_data.challenge raise ClientDataTypeError unless response.client_data.authentication? pem = U2F.public_key_pem(registration_public_key) raise AuthenticationFailedError unless response.verify(app_id, pem) raise UserNotPresentError unless response.user_present? unless response.counter > registration_counter raise CounterTooLowError unless response.counter.zero? && registration_counter.zero? end end
ruby
def authenticate!(challenge, response, registration_public_key, registration_counter) # TODO: check that it's the correct key_handle as well raise NoMatchingRequestError unless challenge == response.client_data.challenge raise ClientDataTypeError unless response.client_data.authentication? pem = U2F.public_key_pem(registration_public_key) raise AuthenticationFailedError unless response.verify(app_id, pem) raise UserNotPresentError unless response.user_present? unless response.counter > registration_counter raise CounterTooLowError unless response.counter.zero? && registration_counter.zero? end end
[ "def", "authenticate!", "(", "challenge", ",", "response", ",", "registration_public_key", ",", "registration_counter", ")", "# TODO: check that it's the correct key_handle as well", "raise", "NoMatchingRequestError", "unless", "challenge", "==", "response", ".", "client_data", ".", "challenge", "raise", "ClientDataTypeError", "unless", "response", ".", "client_data", ".", "authentication?", "pem", "=", "U2F", ".", "public_key_pem", "(", "registration_public_key", ")", "raise", "AuthenticationFailedError", "unless", "response", ".", "verify", "(", "app_id", ",", "pem", ")", "raise", "UserNotPresentError", "unless", "response", ".", "user_present?", "unless", "response", ".", "counter", ">", "registration_counter", "raise", "CounterTooLowError", "unless", "response", ".", "counter", ".", "zero?", "&&", "registration_counter", ".", "zero?", "end", "end" ]
Authenticate a response from the U2F device * *Args*: - +challenge+:: Challenge string - +response+:: Response from the U2F device as a +SignResponse+ object - +registration_public_key+:: Public key of the registered U2F device as binary string - +registration_counter+:: +Integer+ with the current counter value of the registered device * *Raises*: - +NoMatchingRequestError+:: if the challenge in the response doesn't match any of the provided ones - +ClientDataTypeError+:: if the response is of the wrong type - +AuthenticationFailedError+:: if the authentication failed - +UserNotPresentError+:: if the user wasn't present during the authentication - +CounterTooLowError+:: if there is a counter mismatch between the registered one and the one in the response
[ "Authenticate", "a", "response", "from", "the", "U2F", "device" ]
1daa303669b589fced6f91c1b5d60cfa5dc14524
https://github.com/castle/ruby-u2f/blob/1daa303669b589fced6f91c1b5d60cfa5dc14524/lib/u2f/u2f.rb#L49-L64
16,486
castle/ruby-u2f
lib/u2f/u2f.rb
U2F.U2F.register!
def register!(challenges, response) challenges = [challenges] unless challenges.is_a? Array challenge = challenges.detect do |chg| chg == response.client_data.challenge end raise UnmatchedChallengeError unless challenge raise ClientDataTypeError unless response.client_data.registration? # Validate public key U2F.public_key_pem(response.public_key_raw) raise AttestationSignatureError unless response.verify(app_id) Registration.new( response.key_handle, response.public_key, response.certificate ) end
ruby
def register!(challenges, response) challenges = [challenges] unless challenges.is_a? Array challenge = challenges.detect do |chg| chg == response.client_data.challenge end raise UnmatchedChallengeError unless challenge raise ClientDataTypeError unless response.client_data.registration? # Validate public key U2F.public_key_pem(response.public_key_raw) raise AttestationSignatureError unless response.verify(app_id) Registration.new( response.key_handle, response.public_key, response.certificate ) end
[ "def", "register!", "(", "challenges", ",", "response", ")", "challenges", "=", "[", "challenges", "]", "unless", "challenges", ".", "is_a?", "Array", "challenge", "=", "challenges", ".", "detect", "do", "|", "chg", "|", "chg", "==", "response", ".", "client_data", ".", "challenge", "end", "raise", "UnmatchedChallengeError", "unless", "challenge", "raise", "ClientDataTypeError", "unless", "response", ".", "client_data", ".", "registration?", "# Validate public key", "U2F", ".", "public_key_pem", "(", "response", ".", "public_key_raw", ")", "raise", "AttestationSignatureError", "unless", "response", ".", "verify", "(", "app_id", ")", "Registration", ".", "new", "(", "response", ".", "key_handle", ",", "response", ".", "public_key", ",", "response", ".", "certificate", ")", "end" ]
Authenticate the response from the U2F device when registering * *Args*: - +challenges+:: +Array+ of challenge strings - +response+:: Response of the U2F device as a +RegisterResponse+ object * *Returns*: - A +Registration+ object * *Raises*: - +UnmatchedChallengeError+:: if the challenge in the response doesn't match any of the provided ones - +ClientDataTypeError+:: if the response is of the wrong type - +AttestationSignatureError+:: if the registration failed
[ "Authenticate", "the", "response", "from", "the", "U2F", "device", "when", "registering" ]
1daa303669b589fced6f91c1b5d60cfa5dc14524
https://github.com/castle/ruby-u2f/blob/1daa303669b589fced6f91c1b5d60cfa5dc14524/lib/u2f/u2f.rb#L103-L123
16,487
castle/ruby-u2f
lib/u2f/sign_response.rb
U2F.SignResponse.verify
def verify(app_id, public_key_pem) data = [ ::U2F::DIGEST.digest(app_id), signature_data.byteslice(0, 5), ::U2F::DIGEST.digest(client_data_json) ].join public_key = OpenSSL::PKey.read(public_key_pem) begin public_key.verify(::U2F::DIGEST.new, signature, data) rescue OpenSSL::PKey::PKeyError false end end
ruby
def verify(app_id, public_key_pem) data = [ ::U2F::DIGEST.digest(app_id), signature_data.byteslice(0, 5), ::U2F::DIGEST.digest(client_data_json) ].join public_key = OpenSSL::PKey.read(public_key_pem) begin public_key.verify(::U2F::DIGEST.new, signature, data) rescue OpenSSL::PKey::PKeyError false end end
[ "def", "verify", "(", "app_id", ",", "public_key_pem", ")", "data", "=", "[", "::", "U2F", "::", "DIGEST", ".", "digest", "(", "app_id", ")", ",", "signature_data", ".", "byteslice", "(", "0", ",", "5", ")", ",", "::", "U2F", "::", "DIGEST", ".", "digest", "(", "client_data_json", ")", "]", ".", "join", "public_key", "=", "OpenSSL", "::", "PKey", ".", "read", "(", "public_key_pem", ")", "begin", "public_key", ".", "verify", "(", "::", "U2F", "::", "DIGEST", ".", "new", ",", "signature", ",", "data", ")", "rescue", "OpenSSL", "::", "PKey", "::", "PKeyError", "false", "end", "end" ]
Verifies the response against an app id and the public key of the registered device
[ "Verifies", "the", "response", "against", "an", "app", "id", "and", "the", "public", "key", "of", "the", "registered", "device" ]
1daa303669b589fced6f91c1b5d60cfa5dc14524
https://github.com/castle/ruby-u2f/blob/1daa303669b589fced6f91c1b5d60cfa5dc14524/lib/u2f/sign_response.rb#L53-L67
16,488
castle/ruby-u2f
lib/u2f/register_response.rb
U2F.RegisterResponse.verify
def verify(app_id) # Chapter 4.3 in # http://fidoalliance.org/specs/fido-u2f-raw-message-formats-v1.0-rd-20141008.pdf data = [ "\x00", ::U2F::DIGEST.digest(app_id), ::U2F::DIGEST.digest(client_data_json), key_handle_raw, public_key_raw ].join begin parsed_certificate.public_key.verify(::U2F::DIGEST.new, signature, data) rescue OpenSSL::PKey::PKeyError false end end
ruby
def verify(app_id) # Chapter 4.3 in # http://fidoalliance.org/specs/fido-u2f-raw-message-formats-v1.0-rd-20141008.pdf data = [ "\x00", ::U2F::DIGEST.digest(app_id), ::U2F::DIGEST.digest(client_data_json), key_handle_raw, public_key_raw ].join begin parsed_certificate.public_key.verify(::U2F::DIGEST.new, signature, data) rescue OpenSSL::PKey::PKeyError false end end
[ "def", "verify", "(", "app_id", ")", "# Chapter 4.3 in", "# http://fidoalliance.org/specs/fido-u2f-raw-message-formats-v1.0-rd-20141008.pdf", "data", "=", "[", "\"\\x00\"", ",", "::", "U2F", "::", "DIGEST", ".", "digest", "(", "app_id", ")", ",", "::", "U2F", "::", "DIGEST", ".", "digest", "(", "client_data_json", ")", ",", "key_handle_raw", ",", "public_key_raw", "]", ".", "join", "begin", "parsed_certificate", ".", "public_key", ".", "verify", "(", "::", "U2F", "::", "DIGEST", ".", "new", ",", "signature", ",", "data", ")", "rescue", "OpenSSL", "::", "PKey", "::", "PKeyError", "false", "end", "end" ]
Verifies the registration data against the app id
[ "Verifies", "the", "registration", "data", "against", "the", "app", "id" ]
1daa303669b589fced6f91c1b5d60cfa5dc14524
https://github.com/castle/ruby-u2f/blob/1daa303669b589fced6f91c1b5d60cfa5dc14524/lib/u2f/register_response.rb#L92-L108
16,489
castle/ruby-u2f
lib/u2f/fake_u2f.rb
U2F.FakeU2F.register_response
def register_response(challenge, error = false) if error JSON.dump(errorCode: 4) else client_data_json = client_data(::U2F::ClientData::REGISTRATION_TYP, challenge) JSON.dump( registrationData: reg_registration_data(client_data_json), clientData: ::U2F.urlsafe_encode64(client_data_json) ) end end
ruby
def register_response(challenge, error = false) if error JSON.dump(errorCode: 4) else client_data_json = client_data(::U2F::ClientData::REGISTRATION_TYP, challenge) JSON.dump( registrationData: reg_registration_data(client_data_json), clientData: ::U2F.urlsafe_encode64(client_data_json) ) end end
[ "def", "register_response", "(", "challenge", ",", "error", "=", "false", ")", "if", "error", "JSON", ".", "dump", "(", "errorCode", ":", "4", ")", "else", "client_data_json", "=", "client_data", "(", "::", "U2F", "::", "ClientData", "::", "REGISTRATION_TYP", ",", "challenge", ")", "JSON", ".", "dump", "(", "registrationData", ":", "reg_registration_data", "(", "client_data_json", ")", ",", "clientData", ":", "::", "U2F", ".", "urlsafe_encode64", "(", "client_data_json", ")", ")", "end", "end" ]
Initialize a new FakeU2F device for use in tests. app_id - The appId/origin this is being tested against. options - A Hash of optional parameters (optional). :counter - The initial counter for this device. :key_handle - The raw key-handle this device should use. :cert_subject - The subject field for the certificate generated for this device. Returns nothing. A registerResponse hash as returned by the u2f.register JavaScript API. challenge - The challenge to sign. error - Boolean. Whether to return an error response (optional). Returns a JSON encoded Hash String.
[ "Initialize", "a", "new", "FakeU2F", "device", "for", "use", "in", "tests", "." ]
1daa303669b589fced6f91c1b5d60cfa5dc14524
https://github.com/castle/ruby-u2f/blob/1daa303669b589fced6f91c1b5d60cfa5dc14524/lib/u2f/fake_u2f.rb#L33-L43
16,490
castle/ruby-u2f
lib/u2f/fake_u2f.rb
U2F.FakeU2F.sign_response
def sign_response(challenge) client_data_json = client_data(::U2F::ClientData::AUTHENTICATION_TYP, challenge) JSON.dump( clientData: ::U2F.urlsafe_encode64(client_data_json), keyHandle: ::U2F.urlsafe_encode64(key_handle_raw), signatureData: auth_signature_data(client_data_json) ) end
ruby
def sign_response(challenge) client_data_json = client_data(::U2F::ClientData::AUTHENTICATION_TYP, challenge) JSON.dump( clientData: ::U2F.urlsafe_encode64(client_data_json), keyHandle: ::U2F.urlsafe_encode64(key_handle_raw), signatureData: auth_signature_data(client_data_json) ) end
[ "def", "sign_response", "(", "challenge", ")", "client_data_json", "=", "client_data", "(", "::", "U2F", "::", "ClientData", "::", "AUTHENTICATION_TYP", ",", "challenge", ")", "JSON", ".", "dump", "(", "clientData", ":", "::", "U2F", ".", "urlsafe_encode64", "(", "client_data_json", ")", ",", "keyHandle", ":", "::", "U2F", ".", "urlsafe_encode64", "(", "key_handle_raw", ")", ",", "signatureData", ":", "auth_signature_data", "(", "client_data_json", ")", ")", "end" ]
A SignResponse hash as returned by the u2f.sign JavaScript API. challenge - The challenge to sign. Returns a JSON encoded Hash String.
[ "A", "SignResponse", "hash", "as", "returned", "by", "the", "u2f", ".", "sign", "JavaScript", "API", "." ]
1daa303669b589fced6f91c1b5d60cfa5dc14524
https://github.com/castle/ruby-u2f/blob/1daa303669b589fced6f91c1b5d60cfa5dc14524/lib/u2f/fake_u2f.rb#L50-L57
16,491
castle/ruby-u2f
lib/u2f/fake_u2f.rb
U2F.FakeU2F.reg_registration_data
def reg_registration_data(client_data_json) ::U2F.urlsafe_encode64( [ 5, origin_public_key_raw, key_handle_raw.bytesize, key_handle_raw, cert_raw, reg_signature(client_data_json) ].pack("CA65CA#{key_handle_raw.bytesize}A#{cert_raw.bytesize}A*") ) end
ruby
def reg_registration_data(client_data_json) ::U2F.urlsafe_encode64( [ 5, origin_public_key_raw, key_handle_raw.bytesize, key_handle_raw, cert_raw, reg_signature(client_data_json) ].pack("CA65CA#{key_handle_raw.bytesize}A#{cert_raw.bytesize}A*") ) end
[ "def", "reg_registration_data", "(", "client_data_json", ")", "::", "U2F", ".", "urlsafe_encode64", "(", "[", "5", ",", "origin_public_key_raw", ",", "key_handle_raw", ".", "bytesize", ",", "key_handle_raw", ",", "cert_raw", ",", "reg_signature", "(", "client_data_json", ")", "]", ".", "pack", "(", "\"CA65CA#{key_handle_raw.bytesize}A#{cert_raw.bytesize}A*\"", ")", ")", "end" ]
The registrationData field returns in a RegisterResponse Hash. client_data_json - The JSON encoded clientData String. Returns a url-safe base64 encoded binary String.
[ "The", "registrationData", "field", "returns", "in", "a", "RegisterResponse", "Hash", "." ]
1daa303669b589fced6f91c1b5d60cfa5dc14524
https://github.com/castle/ruby-u2f/blob/1daa303669b589fced6f91c1b5d60cfa5dc14524/lib/u2f/fake_u2f.rb#L82-L93
16,492
castle/ruby-u2f
lib/u2f/fake_u2f.rb
U2F.FakeU2F.reg_signature
def reg_signature(client_data_json) payload = [ "\x00", ::U2F::DIGEST.digest(app_id), ::U2F::DIGEST.digest(client_data_json), key_handle_raw, origin_public_key_raw ].join cert_key.sign(::U2F::DIGEST.new, payload) end
ruby
def reg_signature(client_data_json) payload = [ "\x00", ::U2F::DIGEST.digest(app_id), ::U2F::DIGEST.digest(client_data_json), key_handle_raw, origin_public_key_raw ].join cert_key.sign(::U2F::DIGEST.new, payload) end
[ "def", "reg_signature", "(", "client_data_json", ")", "payload", "=", "[", "\"\\x00\"", ",", "::", "U2F", "::", "DIGEST", ".", "digest", "(", "app_id", ")", ",", "::", "U2F", "::", "DIGEST", ".", "digest", "(", "client_data_json", ")", ",", "key_handle_raw", ",", "origin_public_key_raw", "]", ".", "join", "cert_key", ".", "sign", "(", "::", "U2F", "::", "DIGEST", ".", "new", ",", "payload", ")", "end" ]
The signature field of a registrationData field of a RegisterResponse. client_data_json - The JSON encoded clientData String. Returns an ECDSA signature String.
[ "The", "signature", "field", "of", "a", "registrationData", "field", "of", "a", "RegisterResponse", "." ]
1daa303669b589fced6f91c1b5d60cfa5dc14524
https://github.com/castle/ruby-u2f/blob/1daa303669b589fced6f91c1b5d60cfa5dc14524/lib/u2f/fake_u2f.rb#L100-L109
16,493
castle/ruby-u2f
lib/u2f/fake_u2f.rb
U2F.FakeU2F.auth_signature
def auth_signature(client_data_json) data = [ ::U2F::DIGEST.digest(app_id), 1, # User present counter, ::U2F::DIGEST.digest(client_data_json) ].pack('A32CNA32') origin_key.sign(::U2F::DIGEST.new, data) end
ruby
def auth_signature(client_data_json) data = [ ::U2F::DIGEST.digest(app_id), 1, # User present counter, ::U2F::DIGEST.digest(client_data_json) ].pack('A32CNA32') origin_key.sign(::U2F::DIGEST.new, data) end
[ "def", "auth_signature", "(", "client_data_json", ")", "data", "=", "[", "::", "U2F", "::", "DIGEST", ".", "digest", "(", "app_id", ")", ",", "1", ",", "# User present", "counter", ",", "::", "U2F", "::", "DIGEST", ".", "digest", "(", "client_data_json", ")", "]", ".", "pack", "(", "'A32CNA32'", ")", "origin_key", ".", "sign", "(", "::", "U2F", "::", "DIGEST", ".", "new", ",", "data", ")", "end" ]
The signature field of a signatureData field of a SignResponse Hash. client_data_json - The JSON encoded clientData String. Returns an ECDSA signature String.
[ "The", "signature", "field", "of", "a", "signatureData", "field", "of", "a", "SignResponse", "Hash", "." ]
1daa303669b589fced6f91c1b5d60cfa5dc14524
https://github.com/castle/ruby-u2f/blob/1daa303669b589fced6f91c1b5d60cfa5dc14524/lib/u2f/fake_u2f.rb#L131-L140
16,494
castle/ruby-u2f
lib/u2f/fake_u2f.rb
U2F.FakeU2F.client_data
def client_data(typ, challenge) JSON.dump( challenge: challenge, origin: app_id, typ: typ ) end
ruby
def client_data(typ, challenge) JSON.dump( challenge: challenge, origin: app_id, typ: typ ) end
[ "def", "client_data", "(", "typ", ",", "challenge", ")", "JSON", ".", "dump", "(", "challenge", ":", "challenge", ",", "origin", ":", "app_id", ",", "typ", ":", "typ", ")", "end" ]
The clientData hash as returned by registration and authentication responses. typ - The String value for the 'typ' field. challenge - The String url-safe base64 encoded challenge parameter. Returns a JSON encoded Hash String.
[ "The", "clientData", "hash", "as", "returned", "by", "registration", "and", "authentication", "responses", "." ]
1daa303669b589fced6f91c1b5d60cfa5dc14524
https://github.com/castle/ruby-u2f/blob/1daa303669b589fced6f91c1b5d60cfa5dc14524/lib/u2f/fake_u2f.rb#L149-L155
16,495
castle/ruby-u2f
lib/u2f/fake_u2f.rb
U2F.FakeU2F.cert
def cert @cert ||= OpenSSL::X509::Certificate.new.tap do |c| c.subject = c.issuer = OpenSSL::X509::Name.parse(cert_subject) c.not_before = Time.now c.not_after = Time.now + 365 * 24 * 60 * 60 c.public_key = cert_key c.serial = 0x1 c.version = 0x0 c.sign cert_key, ::U2F::DIGEST.new end end
ruby
def cert @cert ||= OpenSSL::X509::Certificate.new.tap do |c| c.subject = c.issuer = OpenSSL::X509::Name.parse(cert_subject) c.not_before = Time.now c.not_after = Time.now + 365 * 24 * 60 * 60 c.public_key = cert_key c.serial = 0x1 c.version = 0x0 c.sign cert_key, ::U2F::DIGEST.new end end
[ "def", "cert", "@cert", "||=", "OpenSSL", "::", "X509", "::", "Certificate", ".", "new", ".", "tap", "do", "|", "c", "|", "c", ".", "subject", "=", "c", ".", "issuer", "=", "OpenSSL", "::", "X509", "::", "Name", ".", "parse", "(", "cert_subject", ")", "c", ".", "not_before", "=", "Time", ".", "now", "c", ".", "not_after", "=", "Time", ".", "now", "+", "365", "*", "24", "*", "60", "*", "60", "c", ".", "public_key", "=", "cert_key", "c", ".", "serial", "=", "0x1", "c", ".", "version", "=", "0x0", "c", ".", "sign", "cert_key", ",", "::", "U2F", "::", "DIGEST", ".", "new", "end", "end" ]
The self-signed device attestation certificate. Returns a OpenSSL::X509::Certificate instance.
[ "The", "self", "-", "signed", "device", "attestation", "certificate", "." ]
1daa303669b589fced6f91c1b5d60cfa5dc14524
https://github.com/castle/ruby-u2f/blob/1daa303669b589fced6f91c1b5d60cfa5dc14524/lib/u2f/fake_u2f.rb#L167-L177
16,496
jonatas/fast
lib/fast.rb
Fast.Rewriter.replace_on
def replace_on(*types) types.map do |type| self.class.send :define_method, "on_#{type}" do |node| if captures = match?(node) # rubocop:disable Lint/AssignmentInCondition @match_index += 1 execute_replacement(node, captures) end super(node) end end end
ruby
def replace_on(*types) types.map do |type| self.class.send :define_method, "on_#{type}" do |node| if captures = match?(node) # rubocop:disable Lint/AssignmentInCondition @match_index += 1 execute_replacement(node, captures) end super(node) end end end
[ "def", "replace_on", "(", "*", "types", ")", "types", ".", "map", "do", "|", "type", "|", "self", ".", "class", ".", "send", ":define_method", ",", "\"on_#{type}\"", "do", "|", "node", "|", "if", "captures", "=", "match?", "(", "node", ")", "# rubocop:disable Lint/AssignmentInCondition", "@match_index", "+=", "1", "execute_replacement", "(", "node", ",", "captures", ")", "end", "super", "(", "node", ")", "end", "end", "end" ]
Generate methods for all affected types. @see Fast.replace
[ "Generate", "methods", "for", "all", "affected", "types", "." ]
5d918a5c19327847fbadab6c56035f936458ba70
https://github.com/jonatas/fast/blob/5d918a5c19327847fbadab6c56035f936458ba70/lib/fast.rb#L268-L278
16,497
jonatas/fast
lib/fast.rb
Fast.Matcher.captures?
def captures?(fast = @fast) case fast when Capture then true when Array then fast.any?(&method(:captures?)) when Find then captures?(fast.token) end end
ruby
def captures?(fast = @fast) case fast when Capture then true when Array then fast.any?(&method(:captures?)) when Find then captures?(fast.token) end end
[ "def", "captures?", "(", "fast", "=", "@fast", ")", "case", "fast", "when", "Capture", "then", "true", "when", "Array", "then", "fast", ".", "any?", "(", "method", "(", ":captures?", ")", ")", "when", "Find", "then", "captures?", "(", "fast", ".", "token", ")", "end", "end" ]
Look recursively into @param fast to check if the expression is have captures. @return [true] if any sub expression have captures.
[ "Look", "recursively", "into" ]
5d918a5c19327847fbadab6c56035f936458ba70
https://github.com/jonatas/fast/blob/5d918a5c19327847fbadab6c56035f936458ba70/lib/fast.rb#L686-L692
16,498
jonatas/fast
lib/fast.rb
Fast.Matcher.find_captures
def find_captures(fast = @fast) return true if fast == @fast && !captures?(fast) case fast when Capture then fast.captures when Array then fast.flat_map(&method(:find_captures)).compact when Find then find_captures(fast.token) end end
ruby
def find_captures(fast = @fast) return true if fast == @fast && !captures?(fast) case fast when Capture then fast.captures when Array then fast.flat_map(&method(:find_captures)).compact when Find then find_captures(fast.token) end end
[ "def", "find_captures", "(", "fast", "=", "@fast", ")", "return", "true", "if", "fast", "==", "@fast", "&&", "!", "captures?", "(", "fast", ")", "case", "fast", "when", "Capture", "then", "fast", ".", "captures", "when", "Array", "then", "fast", ".", "flat_map", "(", "method", "(", ":find_captures", ")", ")", ".", "compact", "when", "Find", "then", "find_captures", "(", "fast", ".", "token", ")", "end", "end" ]
Find search captures recursively. @return [Array<Object>] of captures from the expression @return [true] in case of no captures in the expression @see Fast::Capture @see Fast::FindFromArgument
[ "Find", "search", "captures", "recursively", "." ]
5d918a5c19327847fbadab6c56035f936458ba70
https://github.com/jonatas/fast/blob/5d918a5c19327847fbadab6c56035f936458ba70/lib/fast.rb#L700-L708
16,499
jonatas/fast
lib/fast.rb
Fast.Matcher.prepare_arguments
def prepare_arguments(expression, arguments) case expression when Array expression.each do |item| prepare_arguments(item, arguments) end when Fast::FindFromArgument expression.arguments = arguments when Fast::Find prepare_arguments expression.token, arguments end end
ruby
def prepare_arguments(expression, arguments) case expression when Array expression.each do |item| prepare_arguments(item, arguments) end when Fast::FindFromArgument expression.arguments = arguments when Fast::Find prepare_arguments expression.token, arguments end end
[ "def", "prepare_arguments", "(", "expression", ",", "arguments", ")", "case", "expression", "when", "Array", "expression", ".", "each", "do", "|", "item", "|", "prepare_arguments", "(", "item", ",", "arguments", ")", "end", "when", "Fast", "::", "FindFromArgument", "expression", ".", "arguments", "=", "arguments", "when", "Fast", "::", "Find", "prepare_arguments", "expression", ".", "token", ",", "arguments", "end", "end" ]
Prepare arguments case the expression needs to bind extra arguments. @return [void]
[ "Prepare", "arguments", "case", "the", "expression", "needs", "to", "bind", "extra", "arguments", "." ]
5d918a5c19327847fbadab6c56035f936458ba70
https://github.com/jonatas/fast/blob/5d918a5c19327847fbadab6c56035f936458ba70/lib/fast.rb#L714-L725