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,100
gdelugre/origami
lib/origami/page.rb
Origami.PageTreeNode.each_page
def each_page(browsed_nodes: [], &block) return enum_for(__method__) { self.Count.to_i } unless block_given? if browsed_nodes.any?{|node| node.equal?(self)} raise InvalidPageTreeError, "Cyclic tree graph detected" end unless self.Kids.is_a?(Array) raise InvalidPageTreeError, "Kids must be an Array" end browsed_nodes.push(self) unless self.Count.nil? [ self.Count.value, self.Kids.length ].min.times do |n| node = self.Kids[n].solve case node when PageTreeNode then node.each_page(browsed_nodes: browsed_nodes, &block) when Page then yield(node) else raise InvalidPageTreeError, "not a Page or PageTreeNode" end end end self end
ruby
def each_page(browsed_nodes: [], &block) return enum_for(__method__) { self.Count.to_i } unless block_given? if browsed_nodes.any?{|node| node.equal?(self)} raise InvalidPageTreeError, "Cyclic tree graph detected" end unless self.Kids.is_a?(Array) raise InvalidPageTreeError, "Kids must be an Array" end browsed_nodes.push(self) unless self.Count.nil? [ self.Count.value, self.Kids.length ].min.times do |n| node = self.Kids[n].solve case node when PageTreeNode then node.each_page(browsed_nodes: browsed_nodes, &block) when Page then yield(node) else raise InvalidPageTreeError, "not a Page or PageTreeNode" end end end self end
[ "def", "each_page", "(", "browsed_nodes", ":", "[", "]", ",", "&", "block", ")", "return", "enum_for", "(", "__method__", ")", "{", "self", ".", "Count", ".", "to_i", "}", "unless", "block_given?", "if", "browsed_nodes", ".", "any?", "{", "|", "node", "|", "node", ".", "equal?", "(", "self", ")", "}", "raise", "InvalidPageTreeError", ",", "\"Cyclic tree graph detected\"", "end", "unless", "self", ".", "Kids", ".", "is_a?", "(", "Array", ")", "raise", "InvalidPageTreeError", ",", "\"Kids must be an Array\"", "end", "browsed_nodes", ".", "push", "(", "self", ")", "unless", "self", ".", "Count", ".", "nil?", "[", "self", ".", "Count", ".", "value", ",", "self", ".", "Kids", ".", "length", "]", ".", "min", ".", "times", "do", "|", "n", "|", "node", "=", "self", ".", "Kids", "[", "n", "]", ".", "solve", "case", "node", "when", "PageTreeNode", "then", "node", ".", "each_page", "(", "browsed_nodes", ":", "browsed_nodes", ",", "block", ")", "when", "Page", "then", "yield", "(", "node", ")", "else", "raise", "InvalidPageTreeError", ",", "\"not a Page or PageTreeNode\"", "end", "end", "end", "self", "end" ]
Iterate through each page of that node.
[ "Iterate", "through", "each", "page", "of", "that", "node", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/page.rb#L345-L372
16,101
gdelugre/origami
lib/origami/page.rb
Origami.PageTreeNode.get_page
def get_page(n) raise IndexError, "Page numbers are referenced starting from 1" if n < 1 raise IndexError, "Page not found" if n > self.Count.to_i self.each_page.lazy.drop(n - 1).first or raise IndexError, "Page not found" end
ruby
def get_page(n) raise IndexError, "Page numbers are referenced starting from 1" if n < 1 raise IndexError, "Page not found" if n > self.Count.to_i self.each_page.lazy.drop(n - 1).first or raise IndexError, "Page not found" end
[ "def", "get_page", "(", "n", ")", "raise", "IndexError", ",", "\"Page numbers are referenced starting from 1\"", "if", "n", "<", "1", "raise", "IndexError", ",", "\"Page not found\"", "if", "n", ">", "self", ".", "Count", ".", "to_i", "self", ".", "each_page", ".", "lazy", ".", "drop", "(", "n", "-", "1", ")", ".", "first", "or", "raise", "IndexError", ",", "\"Page not found\"", "end" ]
Get the n-th Page object in this node, starting from 1.
[ "Get", "the", "n", "-", "th", "Page", "object", "in", "this", "node", "starting", "from", "1", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/page.rb#L377-L382
16,102
gdelugre/origami
lib/origami/page.rb
Origami.Page.each_content_stream
def each_content_stream contents = self.Contents return enum_for(__method__) do case contents when Array then contents.length when Stream then 1 else 0 end end unless block_given? case contents when Stream then yield(contents) when Array then contents.each { |stm| yield(stm.solve) } end end
ruby
def each_content_stream contents = self.Contents return enum_for(__method__) do case contents when Array then contents.length when Stream then 1 else 0 end end unless block_given? case contents when Stream then yield(contents) when Array then contents.each { |stm| yield(stm.solve) } end end
[ "def", "each_content_stream", "contents", "=", "self", ".", "Contents", "return", "enum_for", "(", "__method__", ")", "do", "case", "contents", "when", "Array", "then", "contents", ".", "length", "when", "Stream", "then", "1", "else", "0", "end", "end", "unless", "block_given?", "case", "contents", "when", "Stream", "then", "yield", "(", "contents", ")", "when", "Array", "then", "contents", ".", "each", "{", "|", "stm", "|", "yield", "(", "stm", ".", "solve", ")", "}", "end", "end" ]
Iterates over all the ContentStreams of the Page.
[ "Iterates", "over", "all", "the", "ContentStreams", "of", "the", "Page", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/page.rb#L560-L576
16,103
gdelugre/origami
lib/origami/page.rb
Origami.Page.add_annotation
def add_annotation(*annotations) self.Annots ||= [] annotations.each do |annot| annot.solve[:P] = self if self.indirect? self.Annots << annot end end
ruby
def add_annotation(*annotations) self.Annots ||= [] annotations.each do |annot| annot.solve[:P] = self if self.indirect? self.Annots << annot end end
[ "def", "add_annotation", "(", "*", "annotations", ")", "self", ".", "Annots", "||=", "[", "]", "annotations", ".", "each", "do", "|", "annot", "|", "annot", ".", "solve", "[", ":P", "]", "=", "self", "if", "self", ".", "indirect?", "self", ".", "Annots", "<<", "annot", "end", "end" ]
Add an Annotation to the Page.
[ "Add", "an", "Annotation", "to", "the", "Page", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/page.rb#L588-L595
16,104
gdelugre/origami
lib/origami/page.rb
Origami.Page.each_annotation
def each_annotation annots = self.Annots return enum_for(__method__) { annots.is_a?(Array) ? annots.length : 0 } unless block_given? return unless annots.is_a?(Array) annots.each do |annot| yield(annot.solve) end end
ruby
def each_annotation annots = self.Annots return enum_for(__method__) { annots.is_a?(Array) ? annots.length : 0 } unless block_given? return unless annots.is_a?(Array) annots.each do |annot| yield(annot.solve) end end
[ "def", "each_annotation", "annots", "=", "self", ".", "Annots", "return", "enum_for", "(", "__method__", ")", "{", "annots", ".", "is_a?", "(", "Array", ")", "?", "annots", ".", "length", ":", "0", "}", "unless", "block_given?", "return", "unless", "annots", ".", "is_a?", "(", "Array", ")", "annots", ".", "each", "do", "|", "annot", "|", "yield", "(", "annot", ".", "solve", ")", "end", "end" ]
Iterate through each Annotation of the Page.
[ "Iterate", "through", "each", "Annotation", "of", "the", "Page", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/page.rb#L600-L609
16,105
gdelugre/origami
lib/origami/page.rb
Origami.Page.add_flash_application
def add_flash_application(swfspec, params = {}) options = { windowed: false, transparent: false, navigation_pane: false, toolbar: false, pass_context_click: false, activation: Annotation::RichMedia::Activation::PAGE_OPEN, deactivation: Annotation::RichMedia::Deactivation::PAGE_CLOSE, flash_vars: nil } options.update(params) annot = create_richmedia(:Flash, swfspec, options) add_annotation(annot) annot end
ruby
def add_flash_application(swfspec, params = {}) options = { windowed: false, transparent: false, navigation_pane: false, toolbar: false, pass_context_click: false, activation: Annotation::RichMedia::Activation::PAGE_OPEN, deactivation: Annotation::RichMedia::Deactivation::PAGE_CLOSE, flash_vars: nil } options.update(params) annot = create_richmedia(:Flash, swfspec, options) add_annotation(annot) annot end
[ "def", "add_flash_application", "(", "swfspec", ",", "params", "=", "{", "}", ")", "options", "=", "{", "windowed", ":", "false", ",", "transparent", ":", "false", ",", "navigation_pane", ":", "false", ",", "toolbar", ":", "false", ",", "pass_context_click", ":", "false", ",", "activation", ":", "Annotation", "::", "RichMedia", "::", "Activation", "::", "PAGE_OPEN", ",", "deactivation", ":", "Annotation", "::", "RichMedia", "::", "Deactivation", "::", "PAGE_CLOSE", ",", "flash_vars", ":", "nil", "}", "options", ".", "update", "(", "params", ")", "annot", "=", "create_richmedia", "(", ":Flash", ",", "swfspec", ",", "options", ")", "add_annotation", "(", "annot", ")", "annot", "end" ]
Embed a SWF Flash application in the page.
[ "Embed", "a", "SWF", "Flash", "application", "in", "the", "page", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/page.rb#L621-L639
16,106
gdelugre/origami
lib/origami/metadata.rb
Origami.PDF.metadata
def metadata metadata_stm = self.Catalog.Metadata if metadata_stm.is_a?(Stream) doc = REXML::Document.new(metadata_stm.data) info = {} doc.elements.each('*/*/rdf:Description') do |description| description.attributes.each_attribute do |attr| case attr.prefix when 'pdf','xap' info[attr.name] = attr.value end end description.elements.each('*') do |element| value = (element.elements['.//rdf:li'] || element).text info[element.name] = value.to_s end end info end end
ruby
def metadata metadata_stm = self.Catalog.Metadata if metadata_stm.is_a?(Stream) doc = REXML::Document.new(metadata_stm.data) info = {} doc.elements.each('*/*/rdf:Description') do |description| description.attributes.each_attribute do |attr| case attr.prefix when 'pdf','xap' info[attr.name] = attr.value end end description.elements.each('*') do |element| value = (element.elements['.//rdf:li'] || element).text info[element.name] = value.to_s end end info end end
[ "def", "metadata", "metadata_stm", "=", "self", ".", "Catalog", ".", "Metadata", "if", "metadata_stm", ".", "is_a?", "(", "Stream", ")", "doc", "=", "REXML", "::", "Document", ".", "new", "(", "metadata_stm", ".", "data", ")", "info", "=", "{", "}", "doc", ".", "elements", ".", "each", "(", "'*/*/rdf:Description'", ")", "do", "|", "description", "|", "description", ".", "attributes", ".", "each_attribute", "do", "|", "attr", "|", "case", "attr", ".", "prefix", "when", "'pdf'", ",", "'xap'", "info", "[", "attr", ".", "name", "]", "=", "attr", ".", "value", "end", "end", "description", ".", "elements", ".", "each", "(", "'*'", ")", "do", "|", "element", "|", "value", "=", "(", "element", ".", "elements", "[", "'.//rdf:li'", "]", "||", "element", ")", ".", "text", "info", "[", "element", ".", "name", "]", "=", "value", ".", "to_s", "end", "end", "info", "end", "end" ]
Returns a Hash of the information found in the metadata stream
[ "Returns", "a", "Hash", "of", "the", "information", "found", "in", "the", "metadata", "stream" ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/metadata.rb#L59-L83
16,107
gdelugre/origami
lib/origami/metadata.rb
Origami.PDF.create_metadata
def create_metadata(info = {}) skeleton = <<-XMP <?packet begin="\xef\xbb\xbf" id="W5M0MpCehiHzreSzNTczkc9d"?> <x:xmpmeta xmlns:x="adobe:ns:meta/"> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> <rdf:Description rdf:about="" xmlns:pdf="http://ns.adobe.com/pdf/1.3/"> </rdf:Description> </rdf:RDF> </x:xmpmeta> <?xpacket end="w"?> XMP xml = if self.Catalog.Metadata.is_a?(Stream) self.Catalog.Metadata.data else skeleton end doc = REXML::Document.new(xml) desc = doc.elements['*/*/rdf:Description'] info.each do |name, value| elt = REXML::Element.new "pdf:#{name}" elt.text = value desc.elements << elt end xml = ""; doc.write(xml, 4) if self.Catalog.Metadata.is_a?(Stream) self.Catalog.Metadata.data = xml else self.Catalog.Metadata = Stream.new(xml) end self.Catalog.Metadata end
ruby
def create_metadata(info = {}) skeleton = <<-XMP <?packet begin="\xef\xbb\xbf" id="W5M0MpCehiHzreSzNTczkc9d"?> <x:xmpmeta xmlns:x="adobe:ns:meta/"> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> <rdf:Description rdf:about="" xmlns:pdf="http://ns.adobe.com/pdf/1.3/"> </rdf:Description> </rdf:RDF> </x:xmpmeta> <?xpacket end="w"?> XMP xml = if self.Catalog.Metadata.is_a?(Stream) self.Catalog.Metadata.data else skeleton end doc = REXML::Document.new(xml) desc = doc.elements['*/*/rdf:Description'] info.each do |name, value| elt = REXML::Element.new "pdf:#{name}" elt.text = value desc.elements << elt end xml = ""; doc.write(xml, 4) if self.Catalog.Metadata.is_a?(Stream) self.Catalog.Metadata.data = xml else self.Catalog.Metadata = Stream.new(xml) end self.Catalog.Metadata end
[ "def", "create_metadata", "(", "info", "=", "{", "}", ")", "skeleton", "=", "<<-XMP", "\\xef", "\\xbb", "\\xbf", "XMP", "xml", "=", "if", "self", ".", "Catalog", ".", "Metadata", ".", "is_a?", "(", "Stream", ")", "self", ".", "Catalog", ".", "Metadata", ".", "data", "else", "skeleton", "end", "doc", "=", "REXML", "::", "Document", ".", "new", "(", "xml", ")", "desc", "=", "doc", ".", "elements", "[", "'*/*/rdf:Description'", "]", "info", ".", "each", "do", "|", "name", ",", "value", "|", "elt", "=", "REXML", "::", "Element", ".", "new", "\"pdf:#{name}\"", "elt", ".", "text", "=", "value", "desc", ".", "elements", "<<", "elt", "end", "xml", "=", "\"\"", ";", "doc", ".", "write", "(", "xml", ",", "4", ")", "if", "self", ".", "Catalog", ".", "Metadata", ".", "is_a?", "(", "Stream", ")", "self", ".", "Catalog", ".", "Metadata", ".", "data", "=", "xml", "else", "self", ".", "Catalog", ".", "Metadata", "=", "Stream", ".", "new", "(", "xml", ")", "end", "self", ".", "Catalog", ".", "Metadata", "end" ]
Modifies or creates a metadata stream.
[ "Modifies", "or", "creates", "a", "metadata", "stream", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/metadata.rb#L88-L126
16,108
gdelugre/origami
lib/origami/trailer.rb
Origami.PDF.trailer
def trailer # # First look for a standard trailer dictionary # if @revisions.last.trailer.dictionary? trl = @revisions.last.trailer # # Otherwise look for a xref stream. # else trl = @revisions.last.xrefstm end raise InvalidPDFError, "No trailer found" if trl.nil? trl end
ruby
def trailer # # First look for a standard trailer dictionary # if @revisions.last.trailer.dictionary? trl = @revisions.last.trailer # # Otherwise look for a xref stream. # else trl = @revisions.last.xrefstm end raise InvalidPDFError, "No trailer found" if trl.nil? trl end
[ "def", "trailer", "#", "# First look for a standard trailer dictionary", "#", "if", "@revisions", ".", "last", ".", "trailer", ".", "dictionary?", "trl", "=", "@revisions", ".", "last", ".", "trailer", "#", "# Otherwise look for a xref stream.", "#", "else", "trl", "=", "@revisions", ".", "last", ".", "xrefstm", "end", "raise", "InvalidPDFError", ",", "\"No trailer found\"", "if", "trl", ".", "nil?", "trl", "end" ]
Returns the current trailer. This might be either a Trailer or XRefStream.
[ "Returns", "the", "current", "trailer", ".", "This", "might", "be", "either", "a", "Trailer", "or", "XRefStream", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/trailer.rb#L29-L46
16,109
gdelugre/origami
lib/origami/extensions/ppklite.rb
Origami.PPKLite.add_certificate
def add_certificate(certfile, attributes, viewable: false, editable: false) if certfile.is_a?(OpenSSL::X509::Certificate) x509 = certfile else x509 = OpenSSL::X509::Certificate.new(certfile) end address_book = get_address_book cert = Certificate.new cert.Cert = x509.to_der cert.ID = address_book.NextID address_book.NextID += 1 cert.Trust = attributes cert.Viewable = viewable cert.Editable = editable address_book.Entries.push(self << cert) end
ruby
def add_certificate(certfile, attributes, viewable: false, editable: false) if certfile.is_a?(OpenSSL::X509::Certificate) x509 = certfile else x509 = OpenSSL::X509::Certificate.new(certfile) end address_book = get_address_book cert = Certificate.new cert.Cert = x509.to_der cert.ID = address_book.NextID address_book.NextID += 1 cert.Trust = attributes cert.Viewable = viewable cert.Editable = editable address_book.Entries.push(self << cert) end
[ "def", "add_certificate", "(", "certfile", ",", "attributes", ",", "viewable", ":", "false", ",", "editable", ":", "false", ")", "if", "certfile", ".", "is_a?", "(", "OpenSSL", "::", "X509", "::", "Certificate", ")", "x509", "=", "certfile", "else", "x509", "=", "OpenSSL", "::", "X509", "::", "Certificate", ".", "new", "(", "certfile", ")", "end", "address_book", "=", "get_address_book", "cert", "=", "Certificate", ".", "new", "cert", ".", "Cert", "=", "x509", ".", "to_der", "cert", ".", "ID", "=", "address_book", ".", "NextID", "address_book", ".", "NextID", "+=", "1", "cert", ".", "Trust", "=", "attributes", "cert", ".", "Viewable", "=", "viewable", "cert", ".", "Editable", "=", "editable", "address_book", ".", "Entries", ".", "push", "(", "self", "<<", "cert", ")", "end" ]
Add a certificate into the address book
[ "Add", "a", "certificate", "into", "the", "address", "book" ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/extensions/ppklite.rb#L346-L365
16,110
gdelugre/origami
lib/origami/stream.rb
Origami.Stream.each_filter
def each_filter filters = self.Filter return enum_for(__method__) do case filters when NilClass then 0 when Array then filters.length else 1 end end unless block_given? return if filters.nil? if filters.is_a?(Array) filters.each do |filter| yield(filter) end else yield(filters) end self end
ruby
def each_filter filters = self.Filter return enum_for(__method__) do case filters when NilClass then 0 when Array then filters.length else 1 end end unless block_given? return if filters.nil? if filters.is_a?(Array) filters.each do |filter| yield(filter) end else yield(filters) end self end
[ "def", "each_filter", "filters", "=", "self", ".", "Filter", "return", "enum_for", "(", "__method__", ")", "do", "case", "filters", "when", "NilClass", "then", "0", "when", "Array", "then", "filters", ".", "length", "else", "1", "end", "end", "unless", "block_given?", "return", "if", "filters", ".", "nil?", "if", "filters", ".", "is_a?", "(", "Array", ")", "filters", ".", "each", "do", "|", "filter", "|", "yield", "(", "filter", ")", "end", "else", "yield", "(", "filters", ")", "end", "self", "end" ]
Iterates over each Filter in the Stream.
[ "Iterates", "over", "each", "Filter", "in", "the", "Stream", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/stream.rb#L166-L187
16,111
gdelugre/origami
lib/origami/stream.rb
Origami.Stream.set_predictor
def set_predictor(predictor, colors: 1, bitspercomponent: 8, columns: 1) filters = self.filters layer = filters.index(:FlateDecode) or filters.index(:LZWDecode) if layer.nil? raise InvalidStreamObjectError, 'Predictor functions can only be used with Flate or LZW filters' end params = Filter::LZW::DecodeParms.new params[:Predictor] = predictor params[:Colors] = colors if colors != 1 params[:BitsPerComponent] = bitspercomponent if bitspercomponent != 8 params[:Columns] = columns if columns != 1 set_decode_params(layer, params) self end
ruby
def set_predictor(predictor, colors: 1, bitspercomponent: 8, columns: 1) filters = self.filters layer = filters.index(:FlateDecode) or filters.index(:LZWDecode) if layer.nil? raise InvalidStreamObjectError, 'Predictor functions can only be used with Flate or LZW filters' end params = Filter::LZW::DecodeParms.new params[:Predictor] = predictor params[:Colors] = colors if colors != 1 params[:BitsPerComponent] = bitspercomponent if bitspercomponent != 8 params[:Columns] = columns if columns != 1 set_decode_params(layer, params) self end
[ "def", "set_predictor", "(", "predictor", ",", "colors", ":", "1", ",", "bitspercomponent", ":", "8", ",", "columns", ":", "1", ")", "filters", "=", "self", ".", "filters", "layer", "=", "filters", ".", "index", "(", ":FlateDecode", ")", "or", "filters", ".", "index", "(", ":LZWDecode", ")", "if", "layer", ".", "nil?", "raise", "InvalidStreamObjectError", ",", "'Predictor functions can only be used with Flate or LZW filters'", "end", "params", "=", "Filter", "::", "LZW", "::", "DecodeParms", ".", "new", "params", "[", ":Predictor", "]", "=", "predictor", "params", "[", ":Colors", "]", "=", "colors", "if", "colors", "!=", "1", "params", "[", ":BitsPerComponent", "]", "=", "bitspercomponent", "if", "bitspercomponent", "!=", "8", "params", "[", ":Columns", "]", "=", "columns", "if", "columns", "!=", "1", "set_decode_params", "(", "layer", ",", "params", ")", "self", "end" ]
Set predictor type for the current Stream. Applies only for LZW and FlateDecode filters.
[ "Set", "predictor", "type", "for", "the", "current", "Stream", ".", "Applies", "only", "for", "LZW", "and", "FlateDecode", "filters", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/stream.rb#L200-L217
16,112
gdelugre/origami
lib/origami/stream.rb
Origami.Stream.decode!
def decode! self.decrypt! if self.is_a?(Encryption::EncryptedStream) return if decoded? filters = self.filters dparams = decode_params @data = @encoded_data.dup @data.freeze filters.each_with_index do |filter, layer| params = dparams[layer].is_a?(Dictionary) ? dparams[layer] : {} # Handle Crypt filters. if filter == :Crypt raise Filter::Error, "Crypt filter must be the first filter" unless layer.zero? # Skip the Crypt filter. next end begin @data = decode_data(@data, filter, params) rescue Filter::Error => error @data = error.decoded_data raise end end self end
ruby
def decode! self.decrypt! if self.is_a?(Encryption::EncryptedStream) return if decoded? filters = self.filters dparams = decode_params @data = @encoded_data.dup @data.freeze filters.each_with_index do |filter, layer| params = dparams[layer].is_a?(Dictionary) ? dparams[layer] : {} # Handle Crypt filters. if filter == :Crypt raise Filter::Error, "Crypt filter must be the first filter" unless layer.zero? # Skip the Crypt filter. next end begin @data = decode_data(@data, filter, params) rescue Filter::Error => error @data = error.decoded_data raise end end self end
[ "def", "decode!", "self", ".", "decrypt!", "if", "self", ".", "is_a?", "(", "Encryption", "::", "EncryptedStream", ")", "return", "if", "decoded?", "filters", "=", "self", ".", "filters", "dparams", "=", "decode_params", "@data", "=", "@encoded_data", ".", "dup", "@data", ".", "freeze", "filters", ".", "each_with_index", "do", "|", "filter", ",", "layer", "|", "params", "=", "dparams", "[", "layer", "]", ".", "is_a?", "(", "Dictionary", ")", "?", "dparams", "[", "layer", "]", ":", "{", "}", "# Handle Crypt filters.", "if", "filter", "==", ":Crypt", "raise", "Filter", "::", "Error", ",", "\"Crypt filter must be the first filter\"", "unless", "layer", ".", "zero?", "# Skip the Crypt filter.", "next", "end", "begin", "@data", "=", "decode_data", "(", "@data", ",", "filter", ",", "params", ")", "rescue", "Filter", "::", "Error", "=>", "error", "@data", "=", "error", ".", "decoded_data", "raise", "end", "end", "self", "end" ]
Uncompress the stream data.
[ "Uncompress", "the", "stream", "data", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/stream.rb#L274-L304
16,113
gdelugre/origami
lib/origami/stream.rb
Origami.Stream.encode!
def encode! return if encoded? filters = self.filters dparams = decode_params @encoded_data = @data.dup (filters.length - 1).downto(0) do |layer| params = dparams[layer].is_a?(Dictionary) ? dparams[layer] : {} filter = filters[layer] # Handle Crypt filters. if filter == :Crypt raise Filter::Error, "Crypt filter must be the first filter" unless layer.zero? # Skip the Crypt filter. next end @encoded_data = encode_data(@encoded_data, filter, params) end self.Length = @encoded_data.length self end
ruby
def encode! return if encoded? filters = self.filters dparams = decode_params @encoded_data = @data.dup (filters.length - 1).downto(0) do |layer| params = dparams[layer].is_a?(Dictionary) ? dparams[layer] : {} filter = filters[layer] # Handle Crypt filters. if filter == :Crypt raise Filter::Error, "Crypt filter must be the first filter" unless layer.zero? # Skip the Crypt filter. next end @encoded_data = encode_data(@encoded_data, filter, params) end self.Length = @encoded_data.length self end
[ "def", "encode!", "return", "if", "encoded?", "filters", "=", "self", ".", "filters", "dparams", "=", "decode_params", "@encoded_data", "=", "@data", ".", "dup", "(", "filters", ".", "length", "-", "1", ")", ".", "downto", "(", "0", ")", "do", "|", "layer", "|", "params", "=", "dparams", "[", "layer", "]", ".", "is_a?", "(", "Dictionary", ")", "?", "dparams", "[", "layer", "]", ":", "{", "}", "filter", "=", "filters", "[", "layer", "]", "# Handle Crypt filters.", "if", "filter", "==", ":Crypt", "raise", "Filter", "::", "Error", ",", "\"Crypt filter must be the first filter\"", "unless", "layer", ".", "zero?", "# Skip the Crypt filter.", "next", "end", "@encoded_data", "=", "encode_data", "(", "@encoded_data", ",", "filter", ",", "params", ")", "end", "self", ".", "Length", "=", "@encoded_data", ".", "length", "self", "end" ]
Compress the stream data.
[ "Compress", "the", "stream", "data", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/stream.rb#L309-L334
16,114
gdelugre/origami
lib/origami/stream.rb
Origami.ObjectStream.import_object_from_document
def import_object_from_document(object) obj_doc = object.document # Remove the previous instance if the object is indirect to avoid duplicates. if obj_doc.equal?(@document) @document.delete_object(object.reference) if object.indirect? # Otherwise, create a exported version of the object. else object = object.export end object end
ruby
def import_object_from_document(object) obj_doc = object.document # Remove the previous instance if the object is indirect to avoid duplicates. if obj_doc.equal?(@document) @document.delete_object(object.reference) if object.indirect? # Otherwise, create a exported version of the object. else object = object.export end object end
[ "def", "import_object_from_document", "(", "object", ")", "obj_doc", "=", "object", ".", "document", "# Remove the previous instance if the object is indirect to avoid duplicates.", "if", "obj_doc", ".", "equal?", "(", "@document", ")", "@document", ".", "delete_object", "(", "object", ".", "reference", ")", "if", "object", ".", "indirect?", "# Otherwise, create a exported version of the object.", "else", "object", "=", "object", ".", "export", "end", "object", "end" ]
Preprocess the object in case it already belongs to a document. If the document is the same as the current object stream, remove the duplicate object from our document. If the object comes from another document, use the export method to create a version without references.
[ "Preprocess", "the", "object", "in", "case", "it", "already", "belongs", "to", "a", "document", ".", "If", "the", "document", "is", "the", "same", "as", "the", "current", "object", "stream", "remove", "the", "duplicate", "object", "from", "our", "document", ".", "If", "the", "object", "comes", "from", "another", "document", "use", "the", "export", "method", "to", "create", "a", "version", "without", "references", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/stream.rb#L638-L651
16,115
gdelugre/origami
lib/origami/string.rb
Origami.String.to_utf8
def to_utf8 detect_encoding utf16 = self.encoding.to_utf16be(self.value) utf16.slice!(0, Encoding::UTF16BE::BOM.size) utf16.encode("utf-8", "utf-16be") end
ruby
def to_utf8 detect_encoding utf16 = self.encoding.to_utf16be(self.value) utf16.slice!(0, Encoding::UTF16BE::BOM.size) utf16.encode("utf-8", "utf-16be") end
[ "def", "to_utf8", "detect_encoding", "utf16", "=", "self", ".", "encoding", ".", "to_utf16be", "(", "self", ".", "value", ")", "utf16", ".", "slice!", "(", "0", ",", "Encoding", "::", "UTF16BE", "::", "BOM", ".", "size", ")", "utf16", ".", "encode", "(", "\"utf-8\"", ",", "\"utf-16be\"", ")", "end" ]
Convert String object to an UTF8 encoded Ruby string.
[ "Convert", "String", "object", "to", "an", "UTF8", "encoded", "Ruby", "string", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/string.rb#L121-L128
16,116
gdelugre/origami
lib/origami/graphics/xobject.rb
Origami.ContentStream.draw_polygon
def draw_polygon(coords = [], attr = {}) load! stroke_color = attr.fetch(:stroke_color, DEFAULT_STROKE_COLOR) fill_color = attr.fetch(:fill_color, DEFAULT_FILL_COLOR) line_cap = attr.fetch(:line_cap, DEFAULT_LINECAP) line_join = attr.fetch(:line_join, DEFAULT_LINEJOIN) line_width = attr.fetch(:line_width, DEFAULT_LINEWIDTH) dash_pattern = attr.fetch(:dash, DEFAULT_DASHPATTERN) stroke = attr[:stroke].nil? ? true : attr[:stroke] fill = attr[:fill].nil? ? false : attr[:fill] stroke = true if fill == false and stroke == false set_fill_color(fill_color) if fill set_stroke_color(stroke_color) if stroke set_line_width(line_width) set_line_cap(line_cap) set_line_join(line_join) set_dash_pattern(dash_pattern) if @canvas.gs.text_state.is_in_text_object? @instructions << PDF::Instruction.new('ET').render(@canvas) end unless coords.size < 1 x,y = coords.slice!(0) @instructions << PDF::Instruction.new('m',x,y).render(@canvas) coords.each do |px,py| @instructions << PDF::Instruction.new('l',px,py).render(@canvas) end @instructions << (i = if stroke and not fill PDF::Instruction.new('s') elsif fill and not stroke PDF::Instruction.new('f') elsif fill and stroke PDF::Instruction.new('b') end ) i.render(@canvas) end self end
ruby
def draw_polygon(coords = [], attr = {}) load! stroke_color = attr.fetch(:stroke_color, DEFAULT_STROKE_COLOR) fill_color = attr.fetch(:fill_color, DEFAULT_FILL_COLOR) line_cap = attr.fetch(:line_cap, DEFAULT_LINECAP) line_join = attr.fetch(:line_join, DEFAULT_LINEJOIN) line_width = attr.fetch(:line_width, DEFAULT_LINEWIDTH) dash_pattern = attr.fetch(:dash, DEFAULT_DASHPATTERN) stroke = attr[:stroke].nil? ? true : attr[:stroke] fill = attr[:fill].nil? ? false : attr[:fill] stroke = true if fill == false and stroke == false set_fill_color(fill_color) if fill set_stroke_color(stroke_color) if stroke set_line_width(line_width) set_line_cap(line_cap) set_line_join(line_join) set_dash_pattern(dash_pattern) if @canvas.gs.text_state.is_in_text_object? @instructions << PDF::Instruction.new('ET').render(@canvas) end unless coords.size < 1 x,y = coords.slice!(0) @instructions << PDF::Instruction.new('m',x,y).render(@canvas) coords.each do |px,py| @instructions << PDF::Instruction.new('l',px,py).render(@canvas) end @instructions << (i = if stroke and not fill PDF::Instruction.new('s') elsif fill and not stroke PDF::Instruction.new('f') elsif fill and stroke PDF::Instruction.new('b') end ) i.render(@canvas) end self end
[ "def", "draw_polygon", "(", "coords", "=", "[", "]", ",", "attr", "=", "{", "}", ")", "load!", "stroke_color", "=", "attr", ".", "fetch", "(", ":stroke_color", ",", "DEFAULT_STROKE_COLOR", ")", "fill_color", "=", "attr", ".", "fetch", "(", ":fill_color", ",", "DEFAULT_FILL_COLOR", ")", "line_cap", "=", "attr", ".", "fetch", "(", ":line_cap", ",", "DEFAULT_LINECAP", ")", "line_join", "=", "attr", ".", "fetch", "(", ":line_join", ",", "DEFAULT_LINEJOIN", ")", "line_width", "=", "attr", ".", "fetch", "(", ":line_width", ",", "DEFAULT_LINEWIDTH", ")", "dash_pattern", "=", "attr", ".", "fetch", "(", ":dash", ",", "DEFAULT_DASHPATTERN", ")", "stroke", "=", "attr", "[", ":stroke", "]", ".", "nil?", "?", "true", ":", "attr", "[", ":stroke", "]", "fill", "=", "attr", "[", ":fill", "]", ".", "nil?", "?", "false", ":", "attr", "[", ":fill", "]", "stroke", "=", "true", "if", "fill", "==", "false", "and", "stroke", "==", "false", "set_fill_color", "(", "fill_color", ")", "if", "fill", "set_stroke_color", "(", "stroke_color", ")", "if", "stroke", "set_line_width", "(", "line_width", ")", "set_line_cap", "(", "line_cap", ")", "set_line_join", "(", "line_join", ")", "set_dash_pattern", "(", "dash_pattern", ")", "if", "@canvas", ".", "gs", ".", "text_state", ".", "is_in_text_object?", "@instructions", "<<", "PDF", "::", "Instruction", ".", "new", "(", "'ET'", ")", ".", "render", "(", "@canvas", ")", "end", "unless", "coords", ".", "size", "<", "1", "x", ",", "y", "=", "coords", ".", "slice!", "(", "0", ")", "@instructions", "<<", "PDF", "::", "Instruction", ".", "new", "(", "'m'", ",", "x", ",", "y", ")", ".", "render", "(", "@canvas", ")", "coords", ".", "each", "do", "|", "px", ",", "py", "|", "@instructions", "<<", "PDF", "::", "Instruction", ".", "new", "(", "'l'", ",", "px", ",", "py", ")", ".", "render", "(", "@canvas", ")", "end", "@instructions", "<<", "(", "i", "=", "if", "stroke", "and", "not", "fill", "PDF", "::", "Instruction", ".", "new", "(", "'s'", ")", "elsif", "fill", "and", "not", "stroke", "PDF", "::", "Instruction", ".", "new", "(", "'f'", ")", "elsif", "fill", "and", "stroke", "PDF", "::", "Instruction", ".", "new", "(", "'b'", ")", "end", ")", "i", ".", "render", "(", "@canvas", ")", "end", "self", "end" ]
Draw a polygon from a array of coordinates.
[ "Draw", "a", "polygon", "from", "a", "array", "of", "coordinates", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/graphics/xobject.rb#L96-L144
16,117
gdelugre/origami
lib/origami/object.rb
Origami.StandardObject.version_required
def version_required #:nodoc: max = [ "1.0", 0 ] self.each_key do |field| attributes = self.class.fields[field.value] if attributes.nil? STDERR.puts "Warning: object #{self.class} has undocumented field #{field.value}" next end version = attributes[:Version] || '1.0' level = attributes[:ExtensionLevel] || 0 current = [ version, level ] max = [ max, current, self[field.value].version_required ].max end max end
ruby
def version_required #:nodoc: max = [ "1.0", 0 ] self.each_key do |field| attributes = self.class.fields[field.value] if attributes.nil? STDERR.puts "Warning: object #{self.class} has undocumented field #{field.value}" next end version = attributes[:Version] || '1.0' level = attributes[:ExtensionLevel] || 0 current = [ version, level ] max = [ max, current, self[field.value].version_required ].max end max end
[ "def", "version_required", "#:nodoc:", "max", "=", "[", "\"1.0\"", ",", "0", "]", "self", ".", "each_key", "do", "|", "field", "|", "attributes", "=", "self", ".", "class", ".", "fields", "[", "field", ".", "value", "]", "if", "attributes", ".", "nil?", "STDERR", ".", "puts", "\"Warning: object #{self.class} has undocumented field #{field.value}\"", "next", "end", "version", "=", "attributes", "[", ":Version", "]", "||", "'1.0'", "level", "=", "attributes", "[", ":ExtensionLevel", "]", "||", "0", "current", "=", "[", "version", ",", "level", "]", "max", "=", "[", "max", ",", "current", ",", "self", "[", "field", ".", "value", "]", ".", "version_required", "]", ".", "max", "end", "max", "end" ]
Returns the version and level required by the current Object.
[ "Returns", "the", "version", "and", "level", "required", "by", "the", "current", "Object", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/object.rb#L263-L281
16,118
gdelugre/origami
lib/origami/object.rb
Origami.Object.set_indirect
def set_indirect(bool) unless bool == true or bool == false raise TypeError, "The argument must be boolean" end if bool == false @no = @generation = 0 @document = nil @file_offset = nil end @indirect = bool self end
ruby
def set_indirect(bool) unless bool == true or bool == false raise TypeError, "The argument must be boolean" end if bool == false @no = @generation = 0 @document = nil @file_offset = nil end @indirect = bool self end
[ "def", "set_indirect", "(", "bool", ")", "unless", "bool", "==", "true", "or", "bool", "==", "false", "raise", "TypeError", ",", "\"The argument must be boolean\"", "end", "if", "bool", "==", "false", "@no", "=", "@generation", "=", "0", "@document", "=", "nil", "@file_offset", "=", "nil", "end", "@indirect", "=", "bool", "self", "end" ]
Creates a new PDF Object. Sets whether the object is indirect or not. Indirect objects are allocated numbers at build time.
[ "Creates", "a", "new", "PDF", "Object", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/object.rb#L409-L422
16,119
gdelugre/origami
lib/origami/object.rb
Origami.Object.copy
def copy saved_doc = @document saved_parent = @parent @document = @parent = nil # do not process parent object and document in the copy # Perform the recursive copy (quite dirty). copyobj = Marshal.load(Marshal.dump(self)) # restore saved values @document = saved_doc @parent = saved_parent copyobj.set_document(saved_doc) if copyobj.indirect? copyobj.parent = parent copyobj end
ruby
def copy saved_doc = @document saved_parent = @parent @document = @parent = nil # do not process parent object and document in the copy # Perform the recursive copy (quite dirty). copyobj = Marshal.load(Marshal.dump(self)) # restore saved values @document = saved_doc @parent = saved_parent copyobj.set_document(saved_doc) if copyobj.indirect? copyobj.parent = parent copyobj end
[ "def", "copy", "saved_doc", "=", "@document", "saved_parent", "=", "@parent", "@document", "=", "@parent", "=", "nil", "# do not process parent object and document in the copy", "# Perform the recursive copy (quite dirty).", "copyobj", "=", "Marshal", ".", "load", "(", "Marshal", ".", "dump", "(", "self", ")", ")", "# restore saved values", "@document", "=", "saved_doc", "@parent", "=", "saved_parent", "copyobj", ".", "set_document", "(", "saved_doc", ")", "if", "copyobj", ".", "indirect?", "copyobj", ".", "parent", "=", "parent", "copyobj", "end" ]
Deep copy of an object.
[ "Deep", "copy", "of", "an", "object", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/object.rb#L457-L474
16,120
gdelugre/origami
lib/origami/object.rb
Origami.Object.cast_to
def cast_to(type, parser = nil) assert_cast_type(type) cast = type.new(self.copy, parser) cast.file_offset = @file_offset transfer_attributes(cast) end
ruby
def cast_to(type, parser = nil) assert_cast_type(type) cast = type.new(self.copy, parser) cast.file_offset = @file_offset transfer_attributes(cast) end
[ "def", "cast_to", "(", "type", ",", "parser", "=", "nil", ")", "assert_cast_type", "(", "type", ")", "cast", "=", "type", ".", "new", "(", "self", ".", "copy", ",", "parser", ")", "cast", ".", "file_offset", "=", "@file_offset", "transfer_attributes", "(", "cast", ")", "end" ]
Casts an object to a new type.
[ "Casts", "an", "object", "to", "a", "new", "type", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/object.rb#L479-L486
16,121
gdelugre/origami
lib/origami/object.rb
Origami.Object.reference
def reference raise InvalidObjectError, "Cannot reference a direct object" unless self.indirect? ref = Reference.new(@no, @generation) ref.parent = self ref end
ruby
def reference raise InvalidObjectError, "Cannot reference a direct object" unless self.indirect? ref = Reference.new(@no, @generation) ref.parent = self ref end
[ "def", "reference", "raise", "InvalidObjectError", ",", "\"Cannot reference a direct object\"", "unless", "self", ".", "indirect?", "ref", "=", "Reference", ".", "new", "(", "@no", ",", "@generation", ")", "ref", ".", "parent", "=", "self", "ref", "end" ]
Returns an indirect reference to this object.
[ "Returns", "an", "indirect", "reference", "to", "this", "object", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/object.rb#L491-L498
16,122
gdelugre/origami
lib/origami/object.rb
Origami.Object.xrefs
def xrefs raise InvalidObjectError, "Cannot find xrefs to a direct object" unless self.indirect? raise InvalidObjectError, "Not attached to any document" if self.document.nil? @document.each_object(compressed: true) .flat_map { |object| case object when Stream object.dictionary.xref_cache[self.reference] when ObjectCache object.xref_cache[self.reference] end } .compact! end
ruby
def xrefs raise InvalidObjectError, "Cannot find xrefs to a direct object" unless self.indirect? raise InvalidObjectError, "Not attached to any document" if self.document.nil? @document.each_object(compressed: true) .flat_map { |object| case object when Stream object.dictionary.xref_cache[self.reference] when ObjectCache object.xref_cache[self.reference] end } .compact! end
[ "def", "xrefs", "raise", "InvalidObjectError", ",", "\"Cannot find xrefs to a direct object\"", "unless", "self", ".", "indirect?", "raise", "InvalidObjectError", ",", "\"Not attached to any document\"", "if", "self", ".", "document", ".", "nil?", "@document", ".", "each_object", "(", "compressed", ":", "true", ")", ".", "flat_map", "{", "|", "object", "|", "case", "object", "when", "Stream", "object", ".", "dictionary", ".", "xref_cache", "[", "self", ".", "reference", "]", "when", "ObjectCache", "object", ".", "xref_cache", "[", "self", ".", "reference", "]", "end", "}", ".", "compact!", "end" ]
Returns an array of references pointing to the current object.
[ "Returns", "an", "array", "of", "references", "pointing", "to", "the", "current", "object", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/object.rb#L503-L517
16,123
gdelugre/origami
lib/origami/object.rb
Origami.Object.export
def export exported_obj = self.logicalize exported_obj.no = exported_obj.generation = 0 exported_obj.set_document(nil) if exported_obj.indirect? exported_obj.parent = nil exported_obj.xref_cache.clear exported_obj end
ruby
def export exported_obj = self.logicalize exported_obj.no = exported_obj.generation = 0 exported_obj.set_document(nil) if exported_obj.indirect? exported_obj.parent = nil exported_obj.xref_cache.clear exported_obj end
[ "def", "export", "exported_obj", "=", "self", ".", "logicalize", "exported_obj", ".", "no", "=", "exported_obj", ".", "generation", "=", "0", "exported_obj", ".", "set_document", "(", "nil", ")", "if", "exported_obj", ".", "indirect?", "exported_obj", ".", "parent", "=", "nil", "exported_obj", ".", "xref_cache", ".", "clear", "exported_obj", "end" ]
Creates an exportable version of current object. The exportable version is a copy of _self_ with solved references, no owning PDF and no parent. References to Catalog or PageTreeNode objects have been destroyed. When exported, an object can be moved into another document without hassle.
[ "Creates", "an", "exportable", "version", "of", "current", "object", ".", "The", "exportable", "version", "is", "a", "copy", "of", "_self_", "with", "solved", "references", "no", "owning", "PDF", "and", "no", "parent", ".", "References", "to", "Catalog", "or", "PageTreeNode", "objects", "have", "been", "destroyed", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/object.rb#L526-L534
16,124
gdelugre/origami
lib/origami/object.rb
Origami.Object.type
def type name = (self.class.name or self.class.superclass.name or self.native_type.name) name.split("::").last.to_sym end
ruby
def type name = (self.class.name or self.class.superclass.name or self.native_type.name) name.split("::").last.to_sym end
[ "def", "type", "name", "=", "(", "self", ".", "class", ".", "name", "or", "self", ".", "class", ".", "superclass", ".", "name", "or", "self", ".", "native_type", ".", "name", ")", "name", ".", "split", "(", "\"::\"", ")", ".", "last", ".", "to_sym", "end" ]
Returns the symbol type of this Object.
[ "Returns", "the", "symbol", "type", "of", "this", "Object", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/object.rb#L681-L685
16,125
gdelugre/origami
lib/origami/object.rb
Origami.Object.transfer_attributes
def transfer_attributes(target) target.no, target.generation = @no, @generation target.parent = @parent if self.indirect? target.set_indirect(true) target.set_document(@document) end target end
ruby
def transfer_attributes(target) target.no, target.generation = @no, @generation target.parent = @parent if self.indirect? target.set_indirect(true) target.set_document(@document) end target end
[ "def", "transfer_attributes", "(", "target", ")", "target", ".", "no", ",", "target", ".", "generation", "=", "@no", ",", "@generation", "target", ".", "parent", "=", "@parent", "if", "self", ".", "indirect?", "target", ".", "set_indirect", "(", "true", ")", "target", ".", "set_document", "(", "@document", ")", "end", "target", "end" ]
Copy the attributes of the current object to another object. Copied attributes do not include the file offset.
[ "Copy", "the", "attributes", "of", "the", "current", "object", "to", "another", "object", ".", "Copied", "attributes", "do", "not", "include", "the", "file", "offset", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/object.rb#L716-L725
16,126
gdelugre/origami
lib/origami/object.rb
Origami.Object.resolve_all_references
def resolve_all_references(obj, browsed: [], cache: {}) return obj if browsed.include?(obj) browsed.push(obj) if obj.is_a?(ObjectStream) obj.each do |subobj| resolve_all_references(subobj, browsed: browsed, cache: cache) end end if obj.is_a?(Stream) resolve_all_references(obj.dictionary, browsed: browsed, cache: cache) end if obj.is_a?(CompoundObject) obj.update_values! do |subobj| if subobj.is_a?(Reference) subobj = (cache[subobj] ||= subobj.solve.copy) subobj.no = subobj.generation = 0 subobj.parent = obj end resolve_all_references(subobj, browsed: browsed, cache: cache) end end obj end
ruby
def resolve_all_references(obj, browsed: [], cache: {}) return obj if browsed.include?(obj) browsed.push(obj) if obj.is_a?(ObjectStream) obj.each do |subobj| resolve_all_references(subobj, browsed: browsed, cache: cache) end end if obj.is_a?(Stream) resolve_all_references(obj.dictionary, browsed: browsed, cache: cache) end if obj.is_a?(CompoundObject) obj.update_values! do |subobj| if subobj.is_a?(Reference) subobj = (cache[subobj] ||= subobj.solve.copy) subobj.no = subobj.generation = 0 subobj.parent = obj end resolve_all_references(subobj, browsed: browsed, cache: cache) end end obj end
[ "def", "resolve_all_references", "(", "obj", ",", "browsed", ":", "[", "]", ",", "cache", ":", "{", "}", ")", "return", "obj", "if", "browsed", ".", "include?", "(", "obj", ")", "browsed", ".", "push", "(", "obj", ")", "if", "obj", ".", "is_a?", "(", "ObjectStream", ")", "obj", ".", "each", "do", "|", "subobj", "|", "resolve_all_references", "(", "subobj", ",", "browsed", ":", "browsed", ",", "cache", ":", "cache", ")", "end", "end", "if", "obj", ".", "is_a?", "(", "Stream", ")", "resolve_all_references", "(", "obj", ".", "dictionary", ",", "browsed", ":", "browsed", ",", "cache", ":", "cache", ")", "end", "if", "obj", ".", "is_a?", "(", "CompoundObject", ")", "obj", ".", "update_values!", "do", "|", "subobj", "|", "if", "subobj", ".", "is_a?", "(", "Reference", ")", "subobj", "=", "(", "cache", "[", "subobj", "]", "||=", "subobj", ".", "solve", ".", "copy", ")", "subobj", ".", "no", "=", "subobj", ".", "generation", "=", "0", "subobj", ".", "parent", "=", "obj", "end", "resolve_all_references", "(", "subobj", ",", "browsed", ":", "browsed", ",", "cache", ":", "cache", ")", "end", "end", "obj", "end" ]
Replace all references of an object by their actual object value.
[ "Replace", "all", "references", "of", "an", "object", "by", "their", "actual", "object", "value", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/object.rb#L730-L757
16,127
gdelugre/origami
lib/origami/parser.rb
Origami.Parser.try_object_promotion
def try_object_promotion(obj) return obj unless Origami::OPTIONS[:enable_type_propagation] and @deferred_casts.key?(obj.reference) types = @deferred_casts[obj.reference] types = [ types ] unless types.is_a?(::Array) # Promote object if a compatible type is found. cast_type = types.find {|type| type < obj.class } if cast_type obj = obj.cast_to(cast_type, self) else obj end end
ruby
def try_object_promotion(obj) return obj unless Origami::OPTIONS[:enable_type_propagation] and @deferred_casts.key?(obj.reference) types = @deferred_casts[obj.reference] types = [ types ] unless types.is_a?(::Array) # Promote object if a compatible type is found. cast_type = types.find {|type| type < obj.class } if cast_type obj = obj.cast_to(cast_type, self) else obj end end
[ "def", "try_object_promotion", "(", "obj", ")", "return", "obj", "unless", "Origami", "::", "OPTIONS", "[", ":enable_type_propagation", "]", "and", "@deferred_casts", ".", "key?", "(", "obj", ".", "reference", ")", "types", "=", "@deferred_casts", "[", "obj", ".", "reference", "]", "types", "=", "[", "types", "]", "unless", "types", ".", "is_a?", "(", "::", "Array", ")", "# Promote object if a compatible type is found.", "cast_type", "=", "types", ".", "find", "{", "|", "type", "|", "type", "<", "obj", ".", "class", "}", "if", "cast_type", "obj", "=", "obj", ".", "cast_to", "(", "cast_type", ",", "self", ")", "else", "obj", "end", "end" ]
Attempt to promote an object using the deferred casts.
[ "Attempt", "to", "promote", "an", "object", "using", "the", "deferred", "casts", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/parser.rb#L226-L239
16,128
gdelugre/origami
lib/origami/signature.rb
Origami.PDF.signed?
def signed? begin self.Catalog.AcroForm.is_a?(Dictionary) and self.Catalog.AcroForm.SigFlags.is_a?(Integer) and (self.Catalog.AcroForm.SigFlags & InteractiveForm::SigFlags::SIGNATURES_EXIST != 0) rescue InvalidReferenceError false end end
ruby
def signed? begin self.Catalog.AcroForm.is_a?(Dictionary) and self.Catalog.AcroForm.SigFlags.is_a?(Integer) and (self.Catalog.AcroForm.SigFlags & InteractiveForm::SigFlags::SIGNATURES_EXIST != 0) rescue InvalidReferenceError false end end
[ "def", "signed?", "begin", "self", ".", "Catalog", ".", "AcroForm", ".", "is_a?", "(", "Dictionary", ")", "and", "self", ".", "Catalog", ".", "AcroForm", ".", "SigFlags", ".", "is_a?", "(", "Integer", ")", "and", "(", "self", ".", "Catalog", ".", "AcroForm", ".", "SigFlags", "&", "InteractiveForm", "::", "SigFlags", "::", "SIGNATURES_EXIST", "!=", "0", ")", "rescue", "InvalidReferenceError", "false", "end", "end" ]
Returns whether the document contains a digital signature.
[ "Returns", "whether", "the", "document", "contains", "a", "digital", "signature", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/signature.rb#L194-L202
16,129
gdelugre/origami
lib/origami/signature.rb
Origami.PDF.extract_signed_data
def extract_signed_data(digsig) # Computes the boundaries of the Contents field. start_sig = digsig[:Contents].file_offset stream = StringScanner.new(self.original_data) stream.pos = digsig[:Contents].file_offset Object.typeof(stream).parse(stream) end_sig = stream.pos stream.terminate r1, r2 = digsig.ranges if r1.begin != 0 or r2.end != self.original_data.size or r1.end != start_sig or r2.begin != end_sig raise SignatureError, "Invalid signature byte range" end self.original_data[r1] + self.original_data[r2] end
ruby
def extract_signed_data(digsig) # Computes the boundaries of the Contents field. start_sig = digsig[:Contents].file_offset stream = StringScanner.new(self.original_data) stream.pos = digsig[:Contents].file_offset Object.typeof(stream).parse(stream) end_sig = stream.pos stream.terminate r1, r2 = digsig.ranges if r1.begin != 0 or r2.end != self.original_data.size or r1.end != start_sig or r2.begin != end_sig raise SignatureError, "Invalid signature byte range" end self.original_data[r1] + self.original_data[r2] end
[ "def", "extract_signed_data", "(", "digsig", ")", "# Computes the boundaries of the Contents field.", "start_sig", "=", "digsig", "[", ":Contents", "]", ".", "file_offset", "stream", "=", "StringScanner", ".", "new", "(", "self", ".", "original_data", ")", "stream", ".", "pos", "=", "digsig", "[", ":Contents", "]", ".", "file_offset", "Object", ".", "typeof", "(", "stream", ")", ".", "parse", "(", "stream", ")", "end_sig", "=", "stream", ".", "pos", "stream", ".", "terminate", "r1", ",", "r2", "=", "digsig", ".", "ranges", "if", "r1", ".", "begin", "!=", "0", "or", "r2", ".", "end", "!=", "self", ".", "original_data", ".", "size", "or", "r1", ".", "end", "!=", "start_sig", "or", "r2", ".", "begin", "!=", "end_sig", "raise", "SignatureError", ",", "\"Invalid signature byte range\"", "end", "self", ".", "original_data", "[", "r1", "]", "+", "self", ".", "original_data", "[", "r2", "]", "end" ]
Verifies the ByteRange field of a digital signature and returned the signed data.
[ "Verifies", "the", "ByteRange", "field", "of", "a", "digital", "signature", "and", "returned", "the", "signed", "data", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/signature.rb#L314-L334
16,130
gdelugre/origami
lib/origami/compound.rb
Origami.CompoundObject.update_values
def update_values(&b) return enum_for(__method__) unless block_given? return self.class.new self.transform_values(&b) if self.respond_to?(:transform_values) return self.class.new self.map(&b) if self.respond_to?(:map) raise NotImplementedError, "This object does not implement this method" end
ruby
def update_values(&b) return enum_for(__method__) unless block_given? return self.class.new self.transform_values(&b) if self.respond_to?(:transform_values) return self.class.new self.map(&b) if self.respond_to?(:map) raise NotImplementedError, "This object does not implement this method" end
[ "def", "update_values", "(", "&", "b", ")", "return", "enum_for", "(", "__method__", ")", "unless", "block_given?", "return", "self", ".", "class", ".", "new", "self", ".", "transform_values", "(", "b", ")", "if", "self", ".", "respond_to?", "(", ":transform_values", ")", "return", "self", ".", "class", ".", "new", "self", ".", "map", "(", "b", ")", "if", "self", ".", "respond_to?", "(", ":map", ")", "raise", "NotImplementedError", ",", "\"This object does not implement this method\"", "end" ]
Returns a new compound object with updated values based on the provided block.
[ "Returns", "a", "new", "compound", "object", "with", "updated", "values", "based", "on", "the", "provided", "block", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/compound.rb#L127-L133
16,131
gdelugre/origami
lib/origami/compound.rb
Origami.CompoundObject.update_values!
def update_values!(&b) return enum_for(__method__) unless block_given? return self.transform_values!(&b) if self.respond_to?(:transform_values!) return self.map!(&b) if self.respond_to?(:map!) raise NotImplementedError, "This object does not implement this method" end
ruby
def update_values!(&b) return enum_for(__method__) unless block_given? return self.transform_values!(&b) if self.respond_to?(:transform_values!) return self.map!(&b) if self.respond_to?(:map!) raise NotImplementedError, "This object does not implement this method" end
[ "def", "update_values!", "(", "&", "b", ")", "return", "enum_for", "(", "__method__", ")", "unless", "block_given?", "return", "self", ".", "transform_values!", "(", "b", ")", "if", "self", ".", "respond_to?", "(", ":transform_values!", ")", "return", "self", ".", "map!", "(", "b", ")", "if", "self", ".", "respond_to?", "(", ":map!", ")", "raise", "NotImplementedError", ",", "\"This object does not implement this method\"", "end" ]
Modifies the compound object's values based on the provided block.
[ "Modifies", "the", "compound", "object", "s", "values", "based", "on", "the", "provided", "block", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/compound.rb#L138-L144
16,132
gdelugre/origami
lib/origami/linearization.rb
Origami.PDF.linearized?
def linearized? begin first_obj = @revisions.first.objects.min_by{|obj| obj.file_offset} rescue return false end @revisions.size > 1 and first_obj.is_a?(Dictionary) and first_obj.has_key? :Linearized end
ruby
def linearized? begin first_obj = @revisions.first.objects.min_by{|obj| obj.file_offset} rescue return false end @revisions.size > 1 and first_obj.is_a?(Dictionary) and first_obj.has_key? :Linearized end
[ "def", "linearized?", "begin", "first_obj", "=", "@revisions", ".", "first", ".", "objects", ".", "min_by", "{", "|", "obj", "|", "obj", ".", "file_offset", "}", "rescue", "return", "false", "end", "@revisions", ".", "size", ">", "1", "and", "first_obj", ".", "is_a?", "(", "Dictionary", ")", "and", "first_obj", ".", "has_key?", ":Linearized", "end" ]
Returns whether the current document is linearized.
[ "Returns", "whether", "the", "current", "document", "is", "linearized", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/linearization.rb#L31-L39
16,133
gdelugre/origami
lib/origami/linearization.rb
Origami.PDF.delinearize!
def delinearize! raise LinearizationError, 'Not a linearized document' unless self.linearized? # # Saves the first trailer. # prev_trailer = @revisions.first.trailer linear_dict = @revisions.first.objects.min_by{|obj| obj.file_offset} # # Removes hint streams used by linearization. # delete_hint_streams(linear_dict) # # Update the trailer. # last_trailer = (@revisions.last.trailer ||= Trailer.new) last_trailer.dictionary ||= Dictionary.new if prev_trailer.dictionary? last_trailer.dictionary = last_trailer.dictionary.merge(prev_trailer.dictionary) else xrefstm = @revisions.last.xrefstm raise LinearizationError, 'Cannot find trailer info while delinearizing document' unless xrefstm.is_a?(XRefStream) last_trailer.dictionary[:Root] = xrefstm[:Root] last_trailer.dictionary[:Encrypt] = xrefstm[:Encrypt] last_trailer.dictionary[:Info] = xrefstm[:Info] last_trailer.dictionary[:ID] = xrefstm[:ID] end # # Remove all xrefs. # Fix: Should be merged instead. # remove_xrefs # # Remove the linearization revision. # @revisions.first.body.delete(linear_dict.reference) @revisions.last.body.merge! @revisions.first.body remove_revision(0) self end
ruby
def delinearize! raise LinearizationError, 'Not a linearized document' unless self.linearized? # # Saves the first trailer. # prev_trailer = @revisions.first.trailer linear_dict = @revisions.first.objects.min_by{|obj| obj.file_offset} # # Removes hint streams used by linearization. # delete_hint_streams(linear_dict) # # Update the trailer. # last_trailer = (@revisions.last.trailer ||= Trailer.new) last_trailer.dictionary ||= Dictionary.new if prev_trailer.dictionary? last_trailer.dictionary = last_trailer.dictionary.merge(prev_trailer.dictionary) else xrefstm = @revisions.last.xrefstm raise LinearizationError, 'Cannot find trailer info while delinearizing document' unless xrefstm.is_a?(XRefStream) last_trailer.dictionary[:Root] = xrefstm[:Root] last_trailer.dictionary[:Encrypt] = xrefstm[:Encrypt] last_trailer.dictionary[:Info] = xrefstm[:Info] last_trailer.dictionary[:ID] = xrefstm[:ID] end # # Remove all xrefs. # Fix: Should be merged instead. # remove_xrefs # # Remove the linearization revision. # @revisions.first.body.delete(linear_dict.reference) @revisions.last.body.merge! @revisions.first.body remove_revision(0) self end
[ "def", "delinearize!", "raise", "LinearizationError", ",", "'Not a linearized document'", "unless", "self", ".", "linearized?", "#", "# Saves the first trailer.", "#", "prev_trailer", "=", "@revisions", ".", "first", ".", "trailer", "linear_dict", "=", "@revisions", ".", "first", ".", "objects", ".", "min_by", "{", "|", "obj", "|", "obj", ".", "file_offset", "}", "#", "# Removes hint streams used by linearization.", "#", "delete_hint_streams", "(", "linear_dict", ")", "#", "# Update the trailer.", "#", "last_trailer", "=", "(", "@revisions", ".", "last", ".", "trailer", "||=", "Trailer", ".", "new", ")", "last_trailer", ".", "dictionary", "||=", "Dictionary", ".", "new", "if", "prev_trailer", ".", "dictionary?", "last_trailer", ".", "dictionary", "=", "last_trailer", ".", "dictionary", ".", "merge", "(", "prev_trailer", ".", "dictionary", ")", "else", "xrefstm", "=", "@revisions", ".", "last", ".", "xrefstm", "raise", "LinearizationError", ",", "'Cannot find trailer info while delinearizing document'", "unless", "xrefstm", ".", "is_a?", "(", "XRefStream", ")", "last_trailer", ".", "dictionary", "[", ":Root", "]", "=", "xrefstm", "[", ":Root", "]", "last_trailer", ".", "dictionary", "[", ":Encrypt", "]", "=", "xrefstm", "[", ":Encrypt", "]", "last_trailer", ".", "dictionary", "[", ":Info", "]", "=", "xrefstm", "[", ":Info", "]", "last_trailer", ".", "dictionary", "[", ":ID", "]", "=", "xrefstm", "[", ":ID", "]", "end", "#", "# Remove all xrefs.", "# Fix: Should be merged instead.", "#", "remove_xrefs", "#", "# Remove the linearization revision.", "#", "@revisions", ".", "first", ".", "body", ".", "delete", "(", "linear_dict", ".", "reference", ")", "@revisions", ".", "last", ".", "body", ".", "merge!", "@revisions", ".", "first", ".", "body", "remove_revision", "(", "0", ")", "self", "end" ]
Tries to delinearize the document if it has been linearized. This operation is xrefs destructive, should be fixed in the future to merge tables.
[ "Tries", "to", "delinearize", "the", "document", "if", "it", "has", "been", "linearized", ".", "This", "operation", "is", "xrefs", "destructive", "should", "be", "fixed", "in", "the", "future", "to", "merge", "tables", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/linearization.rb#L45-L95
16,134
gdelugre/origami
lib/origami/linearization.rb
Origami.PDF.delete_hint_streams
def delete_hint_streams(linearization_dict) hints = linearization_dict[:H] return unless hints.is_a?(Array) hints.each_slice(2) do |offset, _length| next unless offset.is_a?(Integer) stream = get_object_by_offset(offset) delete_object(stream.reference) if stream.is_a?(Stream) end end
ruby
def delete_hint_streams(linearization_dict) hints = linearization_dict[:H] return unless hints.is_a?(Array) hints.each_slice(2) do |offset, _length| next unless offset.is_a?(Integer) stream = get_object_by_offset(offset) delete_object(stream.reference) if stream.is_a?(Stream) end end
[ "def", "delete_hint_streams", "(", "linearization_dict", ")", "hints", "=", "linearization_dict", "[", ":H", "]", "return", "unless", "hints", ".", "is_a?", "(", "Array", ")", "hints", ".", "each_slice", "(", "2", ")", "do", "|", "offset", ",", "_length", "|", "next", "unless", "offset", ".", "is_a?", "(", "Integer", ")", "stream", "=", "get_object_by_offset", "(", "offset", ")", "delete_object", "(", "stream", ".", "reference", ")", "if", "stream", ".", "is_a?", "(", "Stream", ")", "end", "end" ]
Strip the document from Hint streams given a linearization dictionary.
[ "Strip", "the", "document", "from", "Hint", "streams", "given", "a", "linearization", "dictionary", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/linearization.rb#L102-L112
16,135
gdelugre/origami
lib/origami/reference.rb
Origami.Reference.follow
def follow doc = self.document if doc.nil? raise InvalidReferenceError, "Not attached to any document" end target = doc.get_object(self) if target.nil? and not Origami::OPTIONS[:ignore_bad_references] raise InvalidReferenceError, "Cannot resolve reference : #{self}" end target or Null.new end
ruby
def follow doc = self.document if doc.nil? raise InvalidReferenceError, "Not attached to any document" end target = doc.get_object(self) if target.nil? and not Origami::OPTIONS[:ignore_bad_references] raise InvalidReferenceError, "Cannot resolve reference : #{self}" end target or Null.new end
[ "def", "follow", "doc", "=", "self", ".", "document", "if", "doc", ".", "nil?", "raise", "InvalidReferenceError", ",", "\"Not attached to any document\"", "end", "target", "=", "doc", ".", "get_object", "(", "self", ")", "if", "target", ".", "nil?", "and", "not", "Origami", "::", "OPTIONS", "[", ":ignore_bad_references", "]", "raise", "InvalidReferenceError", ",", "\"Cannot resolve reference : #{self}\"", "end", "target", "or", "Null", ".", "new", "end" ]
Returns the object pointed to by the reference. The reference must be part of a document. Raises an InvalidReferenceError if the object cannot be found.
[ "Returns", "the", "object", "pointed", "to", "by", "the", "reference", ".", "The", "reference", "must", "be", "part", "of", "a", "document", ".", "Raises", "an", "InvalidReferenceError", "if", "the", "object", "cannot", "be", "found", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/reference.rb#L68-L82
16,136
gdelugre/origami
lib/origami/acroform.rb
Origami.PDF.create_form
def create_form(*fields) acroform = self.Catalog.AcroForm ||= InteractiveForm.new.set_indirect(true) self.add_fields(*fields) acroform end
ruby
def create_form(*fields) acroform = self.Catalog.AcroForm ||= InteractiveForm.new.set_indirect(true) self.add_fields(*fields) acroform end
[ "def", "create_form", "(", "*", "fields", ")", "acroform", "=", "self", ".", "Catalog", ".", "AcroForm", "||=", "InteractiveForm", ".", "new", ".", "set_indirect", "(", "true", ")", "self", ".", "add_fields", "(", "fields", ")", "acroform", "end" ]
Creates a new AcroForm with specified fields.
[ "Creates", "a", "new", "AcroForm", "with", "specified", "fields", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/acroform.rb#L35-L40
16,137
gdelugre/origami
lib/origami/acroform.rb
Origami.PDF.each_field
def each_field return enum_for(__method__) do if self.form? and self.Catalog.AcroForm.Fields.is_a?(Array) self.Catalog.AcroForm.Fields.length else 0 end end unless block_given? if self.form? and self.Catalog.AcroForm.Fields.is_a?(Array) self.Catalog.AcroForm.Fields.each do |field| yield(field.solve) end end end
ruby
def each_field return enum_for(__method__) do if self.form? and self.Catalog.AcroForm.Fields.is_a?(Array) self.Catalog.AcroForm.Fields.length else 0 end end unless block_given? if self.form? and self.Catalog.AcroForm.Fields.is_a?(Array) self.Catalog.AcroForm.Fields.each do |field| yield(field.solve) end end end
[ "def", "each_field", "return", "enum_for", "(", "__method__", ")", "do", "if", "self", ".", "form?", "and", "self", ".", "Catalog", ".", "AcroForm", ".", "Fields", ".", "is_a?", "(", "Array", ")", "self", ".", "Catalog", ".", "AcroForm", ".", "Fields", ".", "length", "else", "0", "end", "end", "unless", "block_given?", "if", "self", ".", "form?", "and", "self", ".", "Catalog", ".", "AcroForm", ".", "Fields", ".", "is_a?", "(", "Array", ")", "self", ".", "Catalog", ".", "AcroForm", ".", "Fields", ".", "each", "do", "|", "field", "|", "yield", "(", "field", ".", "solve", ")", "end", "end", "end" ]
Iterates over each Acroform Field.
[ "Iterates", "over", "each", "Acroform", "Field", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/acroform.rb#L68-L82
16,138
gdelugre/origami
lib/origami/encryption.rb
Origami.PDF.create_security_handler
def create_security_handler(version, revision, params) # Ensure the document has an ID. doc_id = (trailer_key(:ID) || generate_id).first # Create the standard encryption dictionary. handler = Encryption::Standard::Dictionary.new handler.Filter = :Standard handler.V = version handler.R = revision handler.Length = params[:key_size] handler.P = -1 # params[:Permissions] # Build the crypt filter dictionary. if revision >= 4 handler.EncryptMetadata = params[:encrypt_metadata] handler.CF = Dictionary.new crypt_filter = Encryption::CryptFilterDictionary.new crypt_filter.AuthEvent = :DocOpen if revision == 4 crypt_filter.CFM = :AESV2 else crypt_filter.CFM = :AESV3 end crypt_filter.Length = params[:key_size] >> 3 handler.CF[:StdCF] = crypt_filter handler.StmF = handler.StrF = :StdCF end user_passwd, owner_passwd = params[:user_passwd], params[:owner_passwd] # Setup keys. handler.set_passwords(owner_passwd, user_passwd, doc_id) encryption_key = handler.compute_user_encryption_key(user_passwd, doc_id) # Install the encryption dictionary to the document. self.trailer.Encrypt = self << handler [ handler, encryption_key ] end
ruby
def create_security_handler(version, revision, params) # Ensure the document has an ID. doc_id = (trailer_key(:ID) || generate_id).first # Create the standard encryption dictionary. handler = Encryption::Standard::Dictionary.new handler.Filter = :Standard handler.V = version handler.R = revision handler.Length = params[:key_size] handler.P = -1 # params[:Permissions] # Build the crypt filter dictionary. if revision >= 4 handler.EncryptMetadata = params[:encrypt_metadata] handler.CF = Dictionary.new crypt_filter = Encryption::CryptFilterDictionary.new crypt_filter.AuthEvent = :DocOpen if revision == 4 crypt_filter.CFM = :AESV2 else crypt_filter.CFM = :AESV3 end crypt_filter.Length = params[:key_size] >> 3 handler.CF[:StdCF] = crypt_filter handler.StmF = handler.StrF = :StdCF end user_passwd, owner_passwd = params[:user_passwd], params[:owner_passwd] # Setup keys. handler.set_passwords(owner_passwd, user_passwd, doc_id) encryption_key = handler.compute_user_encryption_key(user_passwd, doc_id) # Install the encryption dictionary to the document. self.trailer.Encrypt = self << handler [ handler, encryption_key ] end
[ "def", "create_security_handler", "(", "version", ",", "revision", ",", "params", ")", "# Ensure the document has an ID.", "doc_id", "=", "(", "trailer_key", "(", ":ID", ")", "||", "generate_id", ")", ".", "first", "# Create the standard encryption dictionary.", "handler", "=", "Encryption", "::", "Standard", "::", "Dictionary", ".", "new", "handler", ".", "Filter", "=", ":Standard", "handler", ".", "V", "=", "version", "handler", ".", "R", "=", "revision", "handler", ".", "Length", "=", "params", "[", ":key_size", "]", "handler", ".", "P", "=", "-", "1", "# params[:Permissions]", "# Build the crypt filter dictionary.", "if", "revision", ">=", "4", "handler", ".", "EncryptMetadata", "=", "params", "[", ":encrypt_metadata", "]", "handler", ".", "CF", "=", "Dictionary", ".", "new", "crypt_filter", "=", "Encryption", "::", "CryptFilterDictionary", ".", "new", "crypt_filter", ".", "AuthEvent", "=", ":DocOpen", "if", "revision", "==", "4", "crypt_filter", ".", "CFM", "=", ":AESV2", "else", "crypt_filter", ".", "CFM", "=", ":AESV3", "end", "crypt_filter", ".", "Length", "=", "params", "[", ":key_size", "]", ">>", "3", "handler", ".", "CF", "[", ":StdCF", "]", "=", "crypt_filter", "handler", ".", "StmF", "=", "handler", ".", "StrF", "=", ":StdCF", "end", "user_passwd", ",", "owner_passwd", "=", "params", "[", ":user_passwd", "]", ",", "params", "[", ":owner_passwd", "]", "# Setup keys.", "handler", ".", "set_passwords", "(", "owner_passwd", ",", "user_passwd", ",", "doc_id", ")", "encryption_key", "=", "handler", ".", "compute_user_encryption_key", "(", "user_passwd", ",", "doc_id", ")", "# Install the encryption dictionary to the document.", "self", ".", "trailer", ".", "Encrypt", "=", "self", "<<", "handler", "[", "handler", ",", "encryption_key", "]", "end" ]
Installs the standard security dictionary, marking the document as being encrypted. Returns the handler and the encryption key used for protecting contents.
[ "Installs", "the", "standard", "security", "dictionary", "marking", "the", "document", "as", "being", "encrypted", ".", "Returns", "the", "handler", "and", "the", "encryption", "key", "used", "for", "protecting", "contents", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/encryption.rb#L123-L165
16,139
gdelugre/origami
lib/origami/pdf.rb
Origami.PDF.<<
def <<(object) owner = object.document # # Does object belongs to another PDF ? # if owner and not owner.equal?(self) import object else add_to_revision(object, @revisions.last) end end
ruby
def <<(object) owner = object.document # # Does object belongs to another PDF ? # if owner and not owner.equal?(self) import object else add_to_revision(object, @revisions.last) end end
[ "def", "<<", "(", "object", ")", "owner", "=", "object", ".", "document", "#", "# Does object belongs to another PDF ?", "#", "if", "owner", "and", "not", "owner", ".", "equal?", "(", "self", ")", "import", "object", "else", "add_to_revision", "(", "object", ",", "@revisions", ".", "last", ")", "end", "end" ]
Adds a new object to the PDF file. If this object has no version number, then a new one will be automatically computed and assignated to him. It returns a Reference to this Object. _object_:: The object to add.
[ "Adds", "a", "new", "object", "to", "the", "PDF", "file", ".", "If", "this", "object", "has", "no", "version", "number", "then", "a", "new", "one", "will", "be", "automatically", "computed", "and", "assignated", "to", "him", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/pdf.rb#L317-L328
16,140
gdelugre/origami
lib/origami/pdf.rb
Origami.PDF.add_to_revision
def add_to_revision(object, revision) object.set_indirect(true) object.set_document(self) object.no, object.generation = allocate_new_object_number if object.no == 0 revision.body[object.reference] = object object.reference end
ruby
def add_to_revision(object, revision) object.set_indirect(true) object.set_document(self) object.no, object.generation = allocate_new_object_number if object.no == 0 revision.body[object.reference] = object object.reference end
[ "def", "add_to_revision", "(", "object", ",", "revision", ")", "object", ".", "set_indirect", "(", "true", ")", "object", ".", "set_document", "(", "self", ")", "object", ".", "no", ",", "object", ".", "generation", "=", "allocate_new_object_number", "if", "object", ".", "no", "==", "0", "revision", ".", "body", "[", "object", ".", "reference", "]", "=", "object", "object", ".", "reference", "end" ]
Adds a new object to a specific revision. If this object has no version number, then a new one will be automatically computed and assignated to him. It returns a Reference to this Object. _object_:: The object to add. _revision_:: The revision to add the object to.
[ "Adds", "a", "new", "object", "to", "a", "specific", "revision", ".", "If", "this", "object", "has", "no", "version", "number", "then", "a", "new", "one", "will", "be", "automatically", "computed", "and", "assignated", "to", "him", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/pdf.rb#L350-L359
16,141
gdelugre/origami
lib/origami/pdf.rb
Origami.PDF.add_new_revision
def add_new_revision root = @revisions.last.trailer[:Root] unless @revisions.empty? @revisions << Revision.new(self) @revisions.last.trailer = Trailer.new @revisions.last.trailer.Root = root self end
ruby
def add_new_revision root = @revisions.last.trailer[:Root] unless @revisions.empty? @revisions << Revision.new(self) @revisions.last.trailer = Trailer.new @revisions.last.trailer.Root = root self end
[ "def", "add_new_revision", "root", "=", "@revisions", ".", "last", ".", "trailer", "[", ":Root", "]", "unless", "@revisions", ".", "empty?", "@revisions", "<<", "Revision", ".", "new", "(", "self", ")", "@revisions", ".", "last", ".", "trailer", "=", "Trailer", ".", "new", "@revisions", ".", "last", ".", "trailer", ".", "Root", "=", "root", "self", "end" ]
Ends the current Revision, and starts a new one.
[ "Ends", "the", "current", "Revision", "and", "starts", "a", "new", "one", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/pdf.rb#L364-L372
16,142
gdelugre/origami
lib/origami/pdf.rb
Origami.PDF.delete_object
def delete_object(no, generation = 0) case no when Reference target = no when ::Integer target = Reference.new(no, generation) else raise TypeError, "Invalid parameter type : #{no.class}" end @revisions.each do |rev| rev.body.delete(target) end end
ruby
def delete_object(no, generation = 0) case no when Reference target = no when ::Integer target = Reference.new(no, generation) else raise TypeError, "Invalid parameter type : #{no.class}" end @revisions.each do |rev| rev.body.delete(target) end end
[ "def", "delete_object", "(", "no", ",", "generation", "=", "0", ")", "case", "no", "when", "Reference", "target", "=", "no", "when", "::", "Integer", "target", "=", "Reference", ".", "new", "(", "no", ",", "generation", ")", "else", "raise", "TypeError", ",", "\"Invalid parameter type : #{no.class}\"", "end", "@revisions", ".", "each", "do", "|", "rev", "|", "rev", ".", "body", ".", "delete", "(", "target", ")", "end", "end" ]
Remove an object.
[ "Remove", "an", "object", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/pdf.rb#L401-L414
16,143
gdelugre/origami
lib/origami/pdf.rb
Origami.PDF.cast_object
def cast_object(reference, type) #:nodoc: @revisions.each do |rev| if rev.body.include?(reference) object = rev.body[reference] return object if object.is_a?(type) if type < rev.body[reference].class rev.body[reference] = object.cast_to(type, @parser) return rev.body[reference] end end end nil end
ruby
def cast_object(reference, type) #:nodoc: @revisions.each do |rev| if rev.body.include?(reference) object = rev.body[reference] return object if object.is_a?(type) if type < rev.body[reference].class rev.body[reference] = object.cast_to(type, @parser) return rev.body[reference] end end end nil end
[ "def", "cast_object", "(", "reference", ",", "type", ")", "#:nodoc:", "@revisions", ".", "each", "do", "|", "rev", "|", "if", "rev", ".", "body", ".", "include?", "(", "reference", ")", "object", "=", "rev", ".", "body", "[", "reference", "]", "return", "object", "if", "object", ".", "is_a?", "(", "type", ")", "if", "type", "<", "rev", ".", "body", "[", "reference", "]", ".", "class", "rev", ".", "body", "[", "reference", "]", "=", "object", ".", "cast_to", "(", "type", ",", "@parser", ")", "return", "rev", ".", "body", "[", "reference", "]", "end", "end", "end", "nil", "end" ]
Casts a PDF object into another object type. The target type must be a subtype of the original type.
[ "Casts", "a", "PDF", "object", "into", "another", "object", "type", ".", "The", "target", "type", "must", "be", "a", "subtype", "of", "the", "original", "type", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/pdf.rb#L499-L514
16,144
gdelugre/origami
lib/origami/pdf.rb
Origami.PDF.search_object
def search_object(object, pattern, streams: true, object_streams: true) result = [] case object when Stream result.concat object.dictionary.strings_cache.select{|str| str.match(pattern) } result.concat object.dictionary.names_cache.select{|name| name.value.match(pattern) } begin result.push object if streams and object.data.match(pattern) rescue Filter::Error return result # Skip object if a decoding error occured. end return result unless object.is_a?(ObjectStream) and object_streams object.each do |child| result.concat search_object(child, pattern, streams: streams, object_streams: object_streams) end when Name, String result.push object if object.value.match(pattern) when ObjectCache result.concat object.strings_cache.select{|str| str.match(pattern) } result.concat object.names_cache.select{|name| name.value.match(pattern) } end result end
ruby
def search_object(object, pattern, streams: true, object_streams: true) result = [] case object when Stream result.concat object.dictionary.strings_cache.select{|str| str.match(pattern) } result.concat object.dictionary.names_cache.select{|name| name.value.match(pattern) } begin result.push object if streams and object.data.match(pattern) rescue Filter::Error return result # Skip object if a decoding error occured. end return result unless object.is_a?(ObjectStream) and object_streams object.each do |child| result.concat search_object(child, pattern, streams: streams, object_streams: object_streams) end when Name, String result.push object if object.value.match(pattern) when ObjectCache result.concat object.strings_cache.select{|str| str.match(pattern) } result.concat object.names_cache.select{|name| name.value.match(pattern) } end result end
[ "def", "search_object", "(", "object", ",", "pattern", ",", "streams", ":", "true", ",", "object_streams", ":", "true", ")", "result", "=", "[", "]", "case", "object", "when", "Stream", "result", ".", "concat", "object", ".", "dictionary", ".", "strings_cache", ".", "select", "{", "|", "str", "|", "str", ".", "match", "(", "pattern", ")", "}", "result", ".", "concat", "object", ".", "dictionary", ".", "names_cache", ".", "select", "{", "|", "name", "|", "name", ".", "value", ".", "match", "(", "pattern", ")", "}", "begin", "result", ".", "push", "object", "if", "streams", "and", "object", ".", "data", ".", "match", "(", "pattern", ")", "rescue", "Filter", "::", "Error", "return", "result", "# Skip object if a decoding error occured.", "end", "return", "result", "unless", "object", ".", "is_a?", "(", "ObjectStream", ")", "and", "object_streams", "object", ".", "each", "do", "|", "child", "|", "result", ".", "concat", "search_object", "(", "child", ",", "pattern", ",", "streams", ":", "streams", ",", "object_streams", ":", "object_streams", ")", "end", "when", "Name", ",", "String", "result", ".", "push", "object", "if", "object", ".", "value", ".", "match", "(", "pattern", ")", "when", "ObjectCache", "result", ".", "concat", "object", ".", "strings_cache", ".", "select", "{", "|", "str", "|", "str", ".", "match", "(", "pattern", ")", "}", "result", ".", "concat", "object", ".", "names_cache", ".", "select", "{", "|", "name", "|", "name", ".", "value", ".", "match", "(", "pattern", ")", "}", "end", "result", "end" ]
Searches through an object, possibly going into object streams. Returns an array of matching strings, names and streams.
[ "Searches", "through", "an", "object", "possibly", "going", "into", "object", "streams", ".", "Returns", "an", "array", "of", "matching", "strings", "names", "and", "streams", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/pdf.rb#L576-L606
16,145
gdelugre/origami
lib/origami/pdf.rb
Origami.PDF.load_object_at_offset
def load_object_at_offset(revision, offset) return nil if loaded? or @parser.nil? pos = @parser.pos begin object = @parser.parse_object(offset) return nil if object.nil? if self.is_a?(Encryption::EncryptedDocument) make_encrypted_object(object) end add_to_revision(object, revision) ensure @parser.pos = pos end object end
ruby
def load_object_at_offset(revision, offset) return nil if loaded? or @parser.nil? pos = @parser.pos begin object = @parser.parse_object(offset) return nil if object.nil? if self.is_a?(Encryption::EncryptedDocument) make_encrypted_object(object) end add_to_revision(object, revision) ensure @parser.pos = pos end object end
[ "def", "load_object_at_offset", "(", "revision", ",", "offset", ")", "return", "nil", "if", "loaded?", "or", "@parser", ".", "nil?", "pos", "=", "@parser", ".", "pos", "begin", "object", "=", "@parser", ".", "parse_object", "(", "offset", ")", "return", "nil", "if", "object", ".", "nil?", "if", "self", ".", "is_a?", "(", "Encryption", "::", "EncryptedDocument", ")", "make_encrypted_object", "(", "object", ")", "end", "add_to_revision", "(", "object", ",", "revision", ")", "ensure", "@parser", ".", "pos", "=", "pos", "end", "object", "end" ]
Load an object from its given file offset. The document must have an associated Parser.
[ "Load", "an", "object", "from", "its", "given", "file", "offset", ".", "The", "document", "must", "have", "an", "associated", "Parser", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/pdf.rb#L612-L630
16,146
gdelugre/origami
lib/origami/pdf.rb
Origami.PDF.make_encrypted_object
def make_encrypted_object(object) case object when String object.extend(Encryption::EncryptedString) when Stream object.extend(Encryption::EncryptedStream) when ObjectCache object.strings_cache.each do |string| string.extend(Encryption::EncryptedString) end end end
ruby
def make_encrypted_object(object) case object when String object.extend(Encryption::EncryptedString) when Stream object.extend(Encryption::EncryptedStream) when ObjectCache object.strings_cache.each do |string| string.extend(Encryption::EncryptedString) end end end
[ "def", "make_encrypted_object", "(", "object", ")", "case", "object", "when", "String", "object", ".", "extend", "(", "Encryption", "::", "EncryptedString", ")", "when", "Stream", "object", ".", "extend", "(", "Encryption", "::", "EncryptedStream", ")", "when", "ObjectCache", "object", ".", "strings_cache", ".", "each", "do", "|", "string", "|", "string", ".", "extend", "(", "Encryption", "::", "EncryptedString", ")", "end", "end", "end" ]
Method called on encrypted objects loaded into the document.
[ "Method", "called", "on", "encrypted", "objects", "loaded", "into", "the", "document", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/pdf.rb#L635-L646
16,147
gdelugre/origami
lib/origami/pdf.rb
Origami.PDF.load_all_objects
def load_all_objects return if loaded? or @parser.nil? @revisions.each do |revision| if revision.xreftable? xrefs = revision.xreftable elsif revision.xrefstm? xrefs = revision.xrefstm else next end xrefs.each_with_number do |xref, no| self.get_object(no) unless xref.free? end end loaded! end
ruby
def load_all_objects return if loaded? or @parser.nil? @revisions.each do |revision| if revision.xreftable? xrefs = revision.xreftable elsif revision.xrefstm? xrefs = revision.xrefstm else next end xrefs.each_with_number do |xref, no| self.get_object(no) unless xref.free? end end loaded! end
[ "def", "load_all_objects", "return", "if", "loaded?", "or", "@parser", ".", "nil?", "@revisions", ".", "each", "do", "|", "revision", "|", "if", "revision", ".", "xreftable?", "xrefs", "=", "revision", ".", "xreftable", "elsif", "revision", ".", "xrefstm?", "xrefs", "=", "revision", ".", "xrefstm", "else", "next", "end", "xrefs", ".", "each_with_number", "do", "|", "xref", ",", "no", "|", "self", ".", "get_object", "(", "no", ")", "unless", "xref", ".", "free?", "end", "end", "loaded!", "end" ]
Force the loading of all objects in the document.
[ "Force", "the", "loading", "of", "all", "objects", "in", "the", "document", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/pdf.rb#L651-L669
16,148
gdelugre/origami
lib/origami/pdf.rb
Origami.PDF.physicalize
def physicalize(options = {}) @revisions.each do |revision| # Do not use each_object here as build_object may modify the iterator. revision.objects.each do |obj| build_object(obj, revision, options) end end self end
ruby
def physicalize(options = {}) @revisions.each do |revision| # Do not use each_object here as build_object may modify the iterator. revision.objects.each do |obj| build_object(obj, revision, options) end end self end
[ "def", "physicalize", "(", "options", "=", "{", "}", ")", "@revisions", ".", "each", "do", "|", "revision", "|", "# Do not use each_object here as build_object may modify the iterator.", "revision", ".", "objects", ".", "each", "do", "|", "obj", "|", "build_object", "(", "obj", ",", "revision", ",", "options", ")", "end", "end", "self", "end" ]
Converts a logical PDF view into a physical view ready for writing.
[ "Converts", "a", "logical", "PDF", "view", "into", "a", "physical", "view", "ready", "for", "writing", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/pdf.rb#L731-L741
16,149
gdelugre/origami
lib/origami/pdf.rb
Origami.PDF.init
def init catalog = (self.Catalog = (trailer_key(:Root) || Catalog.new)) @revisions.last.trailer.Root = catalog.reference loaded! self end
ruby
def init catalog = (self.Catalog = (trailer_key(:Root) || Catalog.new)) @revisions.last.trailer.Root = catalog.reference loaded! self end
[ "def", "init", "catalog", "=", "(", "self", ".", "Catalog", "=", "(", "trailer_key", "(", ":Root", ")", "||", "Catalog", ".", "new", ")", ")", "@revisions", ".", "last", ".", "trailer", ".", "Root", "=", "catalog", ".", "reference", "loaded!", "self", "end" ]
Instanciates basic structures required for a valid PDF file.
[ "Instanciates", "basic", "structures", "required", "for", "a", "valid", "PDF", "file", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/pdf.rb#L988-L995
16,150
gdelugre/origami
lib/origami/pdf.rb
Origami.PDF.build_xrefs
def build_xrefs(objects) #:nodoc: lastno = 0 brange = 0 xrefs = [ XRef.new(0, XRef::FIRSTFREE, XRef::FREE) ] xrefsection = XRef::Section.new objects.sort_by {|object| object.reference} .each do |object| if (object.no - lastno).abs > 1 xrefsection << XRef::Subsection.new(brange, xrefs) brange = object.no xrefs.clear end xrefs << XRef.new(get_object_offset(object.no, object.generation), object.generation, XRef::USED) lastno = object.no end xrefsection << XRef::Subsection.new(brange, xrefs) xrefsection end
ruby
def build_xrefs(objects) #:nodoc: lastno = 0 brange = 0 xrefs = [ XRef.new(0, XRef::FIRSTFREE, XRef::FREE) ] xrefsection = XRef::Section.new objects.sort_by {|object| object.reference} .each do |object| if (object.no - lastno).abs > 1 xrefsection << XRef::Subsection.new(brange, xrefs) brange = object.no xrefs.clear end xrefs << XRef.new(get_object_offset(object.no, object.generation), object.generation, XRef::USED) lastno = object.no end xrefsection << XRef::Subsection.new(brange, xrefs) xrefsection end
[ "def", "build_xrefs", "(", "objects", ")", "#:nodoc:", "lastno", "=", "0", "brange", "=", "0", "xrefs", "=", "[", "XRef", ".", "new", "(", "0", ",", "XRef", "::", "FIRSTFREE", ",", "XRef", "::", "FREE", ")", "]", "xrefsection", "=", "XRef", "::", "Section", ".", "new", "objects", ".", "sort_by", "{", "|", "object", "|", "object", ".", "reference", "}", ".", "each", "do", "|", "object", "|", "if", "(", "object", ".", "no", "-", "lastno", ")", ".", "abs", ">", "1", "xrefsection", "<<", "XRef", "::", "Subsection", ".", "new", "(", "brange", ",", "xrefs", ")", "brange", "=", "object", ".", "no", "xrefs", ".", "clear", "end", "xrefs", "<<", "XRef", ".", "new", "(", "get_object_offset", "(", "object", ".", "no", ",", "object", ".", "generation", ")", ",", "object", ".", "generation", ",", "XRef", "::", "USED", ")", "lastno", "=", "object", ".", "no", "end", "xrefsection", "<<", "XRef", "::", "Subsection", ".", "new", "(", "brange", ",", "xrefs", ")", "xrefsection", "end" ]
Build a xref section from a set of objects.
[ "Build", "a", "xref", "section", "from", "a", "set", "of", "objects", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/pdf.rb#L1060-L1085
16,151
gdelugre/origami
lib/origami/dictionary.rb
Origami.Dictionary.transform_values
def transform_values(&b) self.class.new self.map { |k, v| [ k.to_sym, b.call(v) ] }.to_h end
ruby
def transform_values(&b) self.class.new self.map { |k, v| [ k.to_sym, b.call(v) ] }.to_h end
[ "def", "transform_values", "(", "&", "b", ")", "self", ".", "class", ".", "new", "self", ".", "map", "{", "|", "k", ",", "v", "|", "[", "k", ".", "to_sym", ",", "b", ".", "call", "(", "v", ")", "]", "}", ".", "to_h", "end" ]
Returns a new Dictionary object with values modified by given block.
[ "Returns", "a", "new", "Dictionary", "object", "with", "values", "modified", "by", "given", "block", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/dictionary.rb#L131-L135
16,152
gdelugre/origami
lib/origami/dictionary.rb
Origami.Dictionary.transform_values!
def transform_values!(&b) self.each_pair do |k, v| self[k] = b.call(unlink_object(v)) end end
ruby
def transform_values!(&b) self.each_pair do |k, v| self[k] = b.call(unlink_object(v)) end end
[ "def", "transform_values!", "(", "&", "b", ")", "self", ".", "each_pair", "do", "|", "k", ",", "v", "|", "self", "[", "k", "]", "=", "b", ".", "call", "(", "unlink_object", "(", "v", ")", ")", "end", "end" ]
Modifies the values of the Dictionary, leaving keys unchanged.
[ "Modifies", "the", "values", "of", "the", "Dictionary", "leaving", "keys", "unchanged", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/dictionary.rb#L140-L144
16,153
gdelugre/origami
lib/origami/xreftable.rb
Origami.PDF.remove_xrefs
def remove_xrefs @revisions.reverse_each do |rev| if rev.xrefstm? delete_object(rev.xrefstm.reference) end if rev.trailer.XRefStm.is_a?(Integer) xrefstm = get_object_by_offset(rev.trailer.XRefStm) delete_object(xrefstm.reference) if xrefstm.is_a?(XRefStream) end rev.xrefstm = rev.xreftable = nil end end
ruby
def remove_xrefs @revisions.reverse_each do |rev| if rev.xrefstm? delete_object(rev.xrefstm.reference) end if rev.trailer.XRefStm.is_a?(Integer) xrefstm = get_object_by_offset(rev.trailer.XRefStm) delete_object(xrefstm.reference) if xrefstm.is_a?(XRefStream) end rev.xrefstm = rev.xreftable = nil end end
[ "def", "remove_xrefs", "@revisions", ".", "reverse_each", "do", "|", "rev", "|", "if", "rev", ".", "xrefstm?", "delete_object", "(", "rev", ".", "xrefstm", ".", "reference", ")", "end", "if", "rev", ".", "trailer", ".", "XRefStm", ".", "is_a?", "(", "Integer", ")", "xrefstm", "=", "get_object_by_offset", "(", "rev", ".", "trailer", ".", "XRefStm", ")", "delete_object", "(", "xrefstm", ".", "reference", ")", "if", "xrefstm", ".", "is_a?", "(", "XRefStream", ")", "end", "rev", ".", "xrefstm", "=", "rev", ".", "xreftable", "=", "nil", "end", "end" ]
Tries to strip any xrefs information off the document.
[ "Tries", "to", "strip", "any", "xrefs", "information", "off", "the", "document", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/xreftable.rb#L27-L41
16,154
gdelugre/origami
lib/origami/xreftable.rb
Origami.XRefStream.each_with_number
def each_with_number return enum_for(__method__) unless block_given? load! if @xrefs.nil? ranges = object_ranges xrefs = @xrefs.to_enum ranges.each do |range| range.each do |no| begin yield(xrefs.next, no) rescue StopIteration raise InvalidXRefStreamObjectError, "Range is bigger than number of entries" end end end end
ruby
def each_with_number return enum_for(__method__) unless block_given? load! if @xrefs.nil? ranges = object_ranges xrefs = @xrefs.to_enum ranges.each do |range| range.each do |no| begin yield(xrefs.next, no) rescue StopIteration raise InvalidXRefStreamObjectError, "Range is bigger than number of entries" end end end end
[ "def", "each_with_number", "return", "enum_for", "(", "__method__", ")", "unless", "block_given?", "load!", "if", "@xrefs", ".", "nil?", "ranges", "=", "object_ranges", "xrefs", "=", "@xrefs", ".", "to_enum", "ranges", ".", "each", "do", "|", "range", "|", "range", ".", "each", "do", "|", "no", "|", "begin", "yield", "(", "xrefs", ".", "next", ",", "no", ")", "rescue", "StopIteration", "raise", "InvalidXRefStreamObjectError", ",", "\"Range is bigger than number of entries\"", "end", "end", "end", "end" ]
Iterates over each XRef present in the stream, passing the XRef and its object number.
[ "Iterates", "over", "each", "XRef", "present", "in", "the", "stream", "passing", "the", "XRef", "and", "its", "object", "number", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/xreftable.rb#L447-L464
16,155
gdelugre/origami
lib/origami/xreftable.rb
Origami.XRefStream.find
def find(no) load! if @xrefs.nil? ranges = object_ranges index = 0 ranges.each do |range| return @xrefs[index + no - range.begin] if range.cover?(no) index += range.size end nil end
ruby
def find(no) load! if @xrefs.nil? ranges = object_ranges index = 0 ranges.each do |range| return @xrefs[index + no - range.begin] if range.cover?(no) index += range.size end nil end
[ "def", "find", "(", "no", ")", "load!", "if", "@xrefs", ".", "nil?", "ranges", "=", "object_ranges", "index", "=", "0", "ranges", ".", "each", "do", "|", "range", "|", "return", "@xrefs", "[", "index", "+", "no", "-", "range", ".", "begin", "]", "if", "range", ".", "cover?", "(", "no", ")", "index", "+=", "range", ".", "size", "end", "nil", "end" ]
Returns an XRef matching this object number.
[ "Returns", "an", "XRef", "matching", "this", "object", "number", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/xreftable.rb#L469-L482
16,156
gdelugre/origami
lib/origami/xreftable.rb
Origami.XRefStream.field_widths
def field_widths widths = self.W unless widths.is_a?(Array) and widths.length == 3 and widths.all? {|w| w.is_a?(Integer) and w >= 0 } raise InvalidXRefStreamObjectError, "Invalid W field: #{widths}" end widths end
ruby
def field_widths widths = self.W unless widths.is_a?(Array) and widths.length == 3 and widths.all? {|w| w.is_a?(Integer) and w >= 0 } raise InvalidXRefStreamObjectError, "Invalid W field: #{widths}" end widths end
[ "def", "field_widths", "widths", "=", "self", ".", "W", "unless", "widths", ".", "is_a?", "(", "Array", ")", "and", "widths", ".", "length", "==", "3", "and", "widths", ".", "all?", "{", "|", "w", "|", "w", ".", "is_a?", "(", "Integer", ")", "and", "w", ">=", "0", "}", "raise", "InvalidXRefStreamObjectError", ",", "\"Invalid W field: #{widths}\"", "end", "widths", "end" ]
Check and return the internal field widths.
[ "Check", "and", "return", "the", "internal", "field", "widths", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/xreftable.rb#L546-L554
16,157
igorkasyanchuk/rails_db
app/helpers/rails_db/application_helper.rb
RailsDb.ApplicationHelper.guess_name
def guess_name(sections) if sections.size > 1 sections[-1] = 'rails_db' variable = sections.join("_") result = eval(variable) end rescue NameError sections.delete_at(-2) guess_name(sections) end
ruby
def guess_name(sections) if sections.size > 1 sections[-1] = 'rails_db' variable = sections.join("_") result = eval(variable) end rescue NameError sections.delete_at(-2) guess_name(sections) end
[ "def", "guess_name", "(", "sections", ")", "if", "sections", ".", "size", ">", "1", "sections", "[", "-", "1", "]", "=", "'rails_db'", "variable", "=", "sections", ".", "join", "(", "\"_\"", ")", "result", "=", "eval", "(", "variable", ")", "end", "rescue", "NameError", "sections", ".", "delete_at", "(", "-", "2", ")", "guess_name", "(", "sections", ")", "end" ]
in case engine was added in namespace
[ "in", "case", "engine", "was", "added", "in", "namespace" ]
ecc664670242f032ca4387d9c1ba80c02591b923
https://github.com/igorkasyanchuk/rails_db/blob/ecc664670242f032ca4387d9c1ba80c02591b923/app/helpers/rails_db/application_helper.rb#L11-L20
16,158
orta/cocoapods-keys
lib/preinstaller.rb
CocoaPodsKeys.PreInstaller.setup
def setup require 'key_master' require 'keyring_liberator' require 'pod/command/keys/set' require 'cocoapods/user_interface' require 'dotenv' ui = Pod::UserInterface options = @user_options || {} current_dir = Pathname.pwd Dotenv.load project = options.fetch('project') { CocoaPodsKeys::NameWhisperer.get_project_name } keyring = KeyringLiberator.get_current_keyring(project, current_dir) unless keyring check_for_multiple_keyrings(project, current_dir) end existing_keyring = !keyring.nil? keyring = CocoaPodsKeys::Keyring.new(project, current_dir, []) unless keyring has_shown_intro = false keys = options.fetch('keys', []) # Remove keys from the keyring that no longer exist original_keyring_keys = keyring.keys.clone original_keyring_keys.each do |key| keyring.keychain_has_key?(key) end # Add keys to the keyring that have been added, # and prompt for their value if needed. keys.each do |key| unless keyring.keychain_has_key?(key) if ci? raise Pod::Informative, "CocoaPods-Keys could not find a key named: #{key}" end unless has_shown_intro ui.puts "\n CocoaPods-Keys has detected a keys mismatch for your setup." has_shown_intro = true end ui.puts ' What is the key for ' + key.green answer = '' loop do ui.print ' > ' answer = ui.gets.strip break unless answer.empty? end ui.puts args = CLAide::ARGV.new([key, answer, keyring.name]) setter = Pod::Command::Keys::Set.new(args) setter.run end end existing_keyring || !keys.empty? end
ruby
def setup require 'key_master' require 'keyring_liberator' require 'pod/command/keys/set' require 'cocoapods/user_interface' require 'dotenv' ui = Pod::UserInterface options = @user_options || {} current_dir = Pathname.pwd Dotenv.load project = options.fetch('project') { CocoaPodsKeys::NameWhisperer.get_project_name } keyring = KeyringLiberator.get_current_keyring(project, current_dir) unless keyring check_for_multiple_keyrings(project, current_dir) end existing_keyring = !keyring.nil? keyring = CocoaPodsKeys::Keyring.new(project, current_dir, []) unless keyring has_shown_intro = false keys = options.fetch('keys', []) # Remove keys from the keyring that no longer exist original_keyring_keys = keyring.keys.clone original_keyring_keys.each do |key| keyring.keychain_has_key?(key) end # Add keys to the keyring that have been added, # and prompt for their value if needed. keys.each do |key| unless keyring.keychain_has_key?(key) if ci? raise Pod::Informative, "CocoaPods-Keys could not find a key named: #{key}" end unless has_shown_intro ui.puts "\n CocoaPods-Keys has detected a keys mismatch for your setup." has_shown_intro = true end ui.puts ' What is the key for ' + key.green answer = '' loop do ui.print ' > ' answer = ui.gets.strip break unless answer.empty? end ui.puts args = CLAide::ARGV.new([key, answer, keyring.name]) setter = Pod::Command::Keys::Set.new(args) setter.run end end existing_keyring || !keys.empty? end
[ "def", "setup", "require", "'key_master'", "require", "'keyring_liberator'", "require", "'pod/command/keys/set'", "require", "'cocoapods/user_interface'", "require", "'dotenv'", "ui", "=", "Pod", "::", "UserInterface", "options", "=", "@user_options", "||", "{", "}", "current_dir", "=", "Pathname", ".", "pwd", "Dotenv", ".", "load", "project", "=", "options", ".", "fetch", "(", "'project'", ")", "{", "CocoaPodsKeys", "::", "NameWhisperer", ".", "get_project_name", "}", "keyring", "=", "KeyringLiberator", ".", "get_current_keyring", "(", "project", ",", "current_dir", ")", "unless", "keyring", "check_for_multiple_keyrings", "(", "project", ",", "current_dir", ")", "end", "existing_keyring", "=", "!", "keyring", ".", "nil?", "keyring", "=", "CocoaPodsKeys", "::", "Keyring", ".", "new", "(", "project", ",", "current_dir", ",", "[", "]", ")", "unless", "keyring", "has_shown_intro", "=", "false", "keys", "=", "options", ".", "fetch", "(", "'keys'", ",", "[", "]", ")", "# Remove keys from the keyring that no longer exist", "original_keyring_keys", "=", "keyring", ".", "keys", ".", "clone", "original_keyring_keys", ".", "each", "do", "|", "key", "|", "keyring", ".", "keychain_has_key?", "(", "key", ")", "end", "# Add keys to the keyring that have been added,", "# and prompt for their value if needed.", "keys", ".", "each", "do", "|", "key", "|", "unless", "keyring", ".", "keychain_has_key?", "(", "key", ")", "if", "ci?", "raise", "Pod", "::", "Informative", ",", "\"CocoaPods-Keys could not find a key named: #{key}\"", "end", "unless", "has_shown_intro", "ui", ".", "puts", "\"\\n CocoaPods-Keys has detected a keys mismatch for your setup.\"", "has_shown_intro", "=", "true", "end", "ui", ".", "puts", "' What is the key for '", "+", "key", ".", "green", "answer", "=", "''", "loop", "do", "ui", ".", "print", "' > '", "answer", "=", "ui", ".", "gets", ".", "strip", "break", "unless", "answer", ".", "empty?", "end", "ui", ".", "puts", "args", "=", "CLAide", "::", "ARGV", ".", "new", "(", "[", "key", ",", "answer", ",", "keyring", ".", "name", "]", ")", "setter", "=", "Pod", "::", "Command", "::", "Keys", "::", "Set", ".", "new", "(", "args", ")", "setter", ".", "run", "end", "end", "existing_keyring", "||", "!", "keys", ".", "empty?", "end" ]
Returns `true` if all keys specified by the user are satisfied by either an existing keyring or environment variables.
[ "Returns", "true", "if", "all", "keys", "specified", "by", "the", "user", "are", "satisfied", "by", "either", "an", "existing", "keyring", "or", "environment", "variables", "." ]
bfdaa7be34457539a4cbcd74f907befd179fd4e7
https://github.com/orta/cocoapods-keys/blob/bfdaa7be34457539a4cbcd74f907befd179fd4e7/lib/preinstaller.rb#L9-L70
16,159
justinfrench/formtastic
lib/formtastic/namespaced_class_finder.rb
Formtastic.NamespacedClassFinder.find_with_const_defined
def find_with_const_defined(class_name) @namespaces.find do |namespace| if namespace.const_defined?(class_name) break namespace.const_get(class_name) end end end
ruby
def find_with_const_defined(class_name) @namespaces.find do |namespace| if namespace.const_defined?(class_name) break namespace.const_get(class_name) end end end
[ "def", "find_with_const_defined", "(", "class_name", ")", "@namespaces", ".", "find", "do", "|", "namespace", "|", "if", "namespace", ".", "const_defined?", "(", "class_name", ")", "break", "namespace", ".", "const_get", "(", "class_name", ")", "end", "end", "end" ]
Looks up the given class name in the configured namespaces in order, returning the first one that has the class name constant defined.
[ "Looks", "up", "the", "given", "class", "name", "in", "the", "configured", "namespaces", "in", "order", "returning", "the", "first", "one", "that", "has", "the", "class", "name", "constant", "defined", "." ]
f1ddec6efbcf49b88e212249829344c450784195
https://github.com/justinfrench/formtastic/blob/f1ddec6efbcf49b88e212249829344c450784195/lib/formtastic/namespaced_class_finder.rb#L81-L87
16,160
ruby-grape/grape-swagger
lib/grape-swagger/endpoint.rb
Grape.Endpoint.swagger_object
def swagger_object(target_class, request, options) object = { info: info_object(options[:info].merge(version: options[:doc_version])), swagger: '2.0', produces: content_types_for(target_class), authorizations: options[:authorizations], securityDefinitions: options[:security_definitions], security: options[:security], host: GrapeSwagger::DocMethods::OptionalObject.build(:host, options, request), basePath: GrapeSwagger::DocMethods::OptionalObject.build(:base_path, options, request), schemes: options[:schemes].is_a?(String) ? [options[:schemes]] : options[:schemes] } GrapeSwagger::DocMethods::Extensions.add_extensions_to_root(options, object) object.delete_if { |_, value| value.blank? } end
ruby
def swagger_object(target_class, request, options) object = { info: info_object(options[:info].merge(version: options[:doc_version])), swagger: '2.0', produces: content_types_for(target_class), authorizations: options[:authorizations], securityDefinitions: options[:security_definitions], security: options[:security], host: GrapeSwagger::DocMethods::OptionalObject.build(:host, options, request), basePath: GrapeSwagger::DocMethods::OptionalObject.build(:base_path, options, request), schemes: options[:schemes].is_a?(String) ? [options[:schemes]] : options[:schemes] } GrapeSwagger::DocMethods::Extensions.add_extensions_to_root(options, object) object.delete_if { |_, value| value.blank? } end
[ "def", "swagger_object", "(", "target_class", ",", "request", ",", "options", ")", "object", "=", "{", "info", ":", "info_object", "(", "options", "[", ":info", "]", ".", "merge", "(", "version", ":", "options", "[", ":doc_version", "]", ")", ")", ",", "swagger", ":", "'2.0'", ",", "produces", ":", "content_types_for", "(", "target_class", ")", ",", "authorizations", ":", "options", "[", ":authorizations", "]", ",", "securityDefinitions", ":", "options", "[", ":security_definitions", "]", ",", "security", ":", "options", "[", ":security", "]", ",", "host", ":", "GrapeSwagger", "::", "DocMethods", "::", "OptionalObject", ".", "build", "(", ":host", ",", "options", ",", "request", ")", ",", "basePath", ":", "GrapeSwagger", "::", "DocMethods", "::", "OptionalObject", ".", "build", "(", ":base_path", ",", "options", ",", "request", ")", ",", "schemes", ":", "options", "[", ":schemes", "]", ".", "is_a?", "(", "String", ")", "?", "[", "options", "[", ":schemes", "]", "]", ":", "options", "[", ":schemes", "]", "}", "GrapeSwagger", "::", "DocMethods", "::", "Extensions", ".", "add_extensions_to_root", "(", "options", ",", "object", ")", "object", ".", "delete_if", "{", "|", "_", ",", "value", "|", "value", ".", "blank?", "}", "end" ]
swagger spec2.0 related parts required keys for SwaggerObject
[ "swagger", "spec2", ".", "0", "related", "parts" ]
542511d9ef08f25b587914a4976009fbc95f7dc0
https://github.com/ruby-grape/grape-swagger/blob/542511d9ef08f25b587914a4976009fbc95f7dc0/lib/grape-swagger/endpoint.rb#L26-L41
16,161
ruby-grape/grape-swagger
lib/grape-swagger/endpoint.rb
Grape.Endpoint.info_object
def info_object(infos) result = { title: infos[:title] || 'API title', description: infos[:description], termsOfService: infos[:terms_of_service_url], contact: contact_object(infos), license: license_object(infos), version: infos[:version] } GrapeSwagger::DocMethods::Extensions.add_extensions_to_info(infos, result) result.delete_if { |_, value| value.blank? } end
ruby
def info_object(infos) result = { title: infos[:title] || 'API title', description: infos[:description], termsOfService: infos[:terms_of_service_url], contact: contact_object(infos), license: license_object(infos), version: infos[:version] } GrapeSwagger::DocMethods::Extensions.add_extensions_to_info(infos, result) result.delete_if { |_, value| value.blank? } end
[ "def", "info_object", "(", "infos", ")", "result", "=", "{", "title", ":", "infos", "[", ":title", "]", "||", "'API title'", ",", "description", ":", "infos", "[", ":description", "]", ",", "termsOfService", ":", "infos", "[", ":terms_of_service_url", "]", ",", "contact", ":", "contact_object", "(", "infos", ")", ",", "license", ":", "license_object", "(", "infos", ")", ",", "version", ":", "infos", "[", ":version", "]", "}", "GrapeSwagger", "::", "DocMethods", "::", "Extensions", ".", "add_extensions_to_info", "(", "infos", ",", "result", ")", "result", ".", "delete_if", "{", "|", "_", ",", "value", "|", "value", ".", "blank?", "}", "end" ]
building info object
[ "building", "info", "object" ]
542511d9ef08f25b587914a4976009fbc95f7dc0
https://github.com/ruby-grape/grape-swagger/blob/542511d9ef08f25b587914a4976009fbc95f7dc0/lib/grape-swagger/endpoint.rb#L44-L57
16,162
ruby-grape/grape-swagger
lib/grape-swagger/endpoint.rb
Grape.Endpoint.license_object
def license_object(infos) { name: infos.delete(:license), url: infos.delete(:license_url) }.delete_if { |_, value| value.blank? } end
ruby
def license_object(infos) { name: infos.delete(:license), url: infos.delete(:license_url) }.delete_if { |_, value| value.blank? } end
[ "def", "license_object", "(", "infos", ")", "{", "name", ":", "infos", ".", "delete", "(", ":license", ")", ",", "url", ":", "infos", ".", "delete", "(", ":license_url", ")", "}", ".", "delete_if", "{", "|", "_", ",", "value", "|", "value", ".", "blank?", "}", "end" ]
sub-objects of info object license
[ "sub", "-", "objects", "of", "info", "object", "license" ]
542511d9ef08f25b587914a4976009fbc95f7dc0
https://github.com/ruby-grape/grape-swagger/blob/542511d9ef08f25b587914a4976009fbc95f7dc0/lib/grape-swagger/endpoint.rb#L61-L66
16,163
ruby-grape/grape-swagger
lib/grape-swagger/endpoint.rb
Grape.Endpoint.path_and_definition_objects
def path_and_definition_objects(namespace_routes, options) @paths = {} @definitions = {} namespace_routes.each_key do |key| routes = namespace_routes[key] path_item(routes, options) end add_definitions_from options[:models] [@paths, @definitions] end
ruby
def path_and_definition_objects(namespace_routes, options) @paths = {} @definitions = {} namespace_routes.each_key do |key| routes = namespace_routes[key] path_item(routes, options) end add_definitions_from options[:models] [@paths, @definitions] end
[ "def", "path_and_definition_objects", "(", "namespace_routes", ",", "options", ")", "@paths", "=", "{", "}", "@definitions", "=", "{", "}", "namespace_routes", ".", "each_key", "do", "|", "key", "|", "routes", "=", "namespace_routes", "[", "key", "]", "path_item", "(", "routes", ",", "options", ")", "end", "add_definitions_from", "options", "[", ":models", "]", "[", "@paths", ",", "@definitions", "]", "end" ]
building path and definitions objects
[ "building", "path", "and", "definitions", "objects" ]
542511d9ef08f25b587914a4976009fbc95f7dc0
https://github.com/ruby-grape/grape-swagger/blob/542511d9ef08f25b587914a4976009fbc95f7dc0/lib/grape-swagger/endpoint.rb#L78-L88
16,164
piotrmurach/tty-tree
lib/tty/tree.rb
TTY.Tree.node
def node(name, type = Node, &block) parent = @nodes_stack.empty? ? Node::ROOT : @nodes_stack.last level = [0, @nodes_stack.size - 1].max prefix = ':pipe' * level if parent.class == LeafNode prefix = ':space' * level end node = type.new(name, parent.full_path, prefix, @nodes_stack.size) @nodes << node return unless block_given? @nodes_stack << node if block.arity.zero? instance_eval(&block) else instance_eval(&(->(*_args) { block[node] })) end @nodes_stack.pop end
ruby
def node(name, type = Node, &block) parent = @nodes_stack.empty? ? Node::ROOT : @nodes_stack.last level = [0, @nodes_stack.size - 1].max prefix = ':pipe' * level if parent.class == LeafNode prefix = ':space' * level end node = type.new(name, parent.full_path, prefix, @nodes_stack.size) @nodes << node return unless block_given? @nodes_stack << node if block.arity.zero? instance_eval(&block) else instance_eval(&(->(*_args) { block[node] })) end @nodes_stack.pop end
[ "def", "node", "(", "name", ",", "type", "=", "Node", ",", "&", "block", ")", "parent", "=", "@nodes_stack", ".", "empty?", "?", "Node", "::", "ROOT", ":", "@nodes_stack", ".", "last", "level", "=", "[", "0", ",", "@nodes_stack", ".", "size", "-", "1", "]", ".", "max", "prefix", "=", "':pipe'", "*", "level", "if", "parent", ".", "class", "==", "LeafNode", "prefix", "=", "':space'", "*", "level", "end", "node", "=", "type", ".", "new", "(", "name", ",", "parent", ".", "full_path", ",", "prefix", ",", "@nodes_stack", ".", "size", ")", "@nodes", "<<", "node", "return", "unless", "block_given?", "@nodes_stack", "<<", "node", "if", "block", ".", "arity", ".", "zero?", "instance_eval", "(", "block", ")", "else", "instance_eval", "(", "(", "->", "(", "*", "_args", ")", "{", "block", "[", "node", "]", "}", ")", ")", "end", "@nodes_stack", ".", "pop", "end" ]
Create a Tree @param [String,Dir,Hash] data @api public Add node to this tree. @param [Symbol,String] name the name for the node @param [Node, LeafNode] type the type of node to add @example TTY::Tree.new do node '...' do node '...' end end @api public
[ "Create", "a", "Tree" ]
8e7e3bfc84a3bf3a2d325eae2fb5bfca2f7a5a8c
https://github.com/piotrmurach/tty-tree/blob/8e7e3bfc84a3bf3a2d325eae2fb5bfca2f7a5a8c/lib/tty/tree.rb#L58-L77
16,165
yosiat/panko_serializer
lib/panko/serialization_descriptor.rb
Panko.SerializationDescriptor.apply_filters
def apply_filters(options) return unless options.key?(:only) || options.key?(:except) attributes_only_filters, associations_only_filters = resolve_filters(options, :only) attributes_except_filters, associations_except_filters = resolve_filters(options, :except) self.attributes = apply_attribute_filters( attributes, attributes_only_filters, attributes_except_filters ) self.method_fields = apply_attribute_filters( method_fields, attributes_only_filters, attributes_except_filters ) unless has_many_associations.empty? self.has_many_associations = apply_association_filters( has_many_associations, { attributes: attributes_only_filters, associations: associations_only_filters }, attributes: attributes_except_filters, associations: associations_except_filters ) end unless has_one_associations.empty? self.has_one_associations = apply_association_filters( has_one_associations, { attributes: attributes_only_filters, associations: associations_only_filters }, attributes: attributes_except_filters, associations: associations_except_filters ) end end
ruby
def apply_filters(options) return unless options.key?(:only) || options.key?(:except) attributes_only_filters, associations_only_filters = resolve_filters(options, :only) attributes_except_filters, associations_except_filters = resolve_filters(options, :except) self.attributes = apply_attribute_filters( attributes, attributes_only_filters, attributes_except_filters ) self.method_fields = apply_attribute_filters( method_fields, attributes_only_filters, attributes_except_filters ) unless has_many_associations.empty? self.has_many_associations = apply_association_filters( has_many_associations, { attributes: attributes_only_filters, associations: associations_only_filters }, attributes: attributes_except_filters, associations: associations_except_filters ) end unless has_one_associations.empty? self.has_one_associations = apply_association_filters( has_one_associations, { attributes: attributes_only_filters, associations: associations_only_filters }, attributes: attributes_except_filters, associations: associations_except_filters ) end end
[ "def", "apply_filters", "(", "options", ")", "return", "unless", "options", ".", "key?", "(", ":only", ")", "||", "options", ".", "key?", "(", ":except", ")", "attributes_only_filters", ",", "associations_only_filters", "=", "resolve_filters", "(", "options", ",", ":only", ")", "attributes_except_filters", ",", "associations_except_filters", "=", "resolve_filters", "(", "options", ",", ":except", ")", "self", ".", "attributes", "=", "apply_attribute_filters", "(", "attributes", ",", "attributes_only_filters", ",", "attributes_except_filters", ")", "self", ".", "method_fields", "=", "apply_attribute_filters", "(", "method_fields", ",", "attributes_only_filters", ",", "attributes_except_filters", ")", "unless", "has_many_associations", ".", "empty?", "self", ".", "has_many_associations", "=", "apply_association_filters", "(", "has_many_associations", ",", "{", "attributes", ":", "attributes_only_filters", ",", "associations", ":", "associations_only_filters", "}", ",", "attributes", ":", "attributes_except_filters", ",", "associations", ":", "associations_except_filters", ")", "end", "unless", "has_one_associations", ".", "empty?", "self", ".", "has_one_associations", "=", "apply_association_filters", "(", "has_one_associations", ",", "{", "attributes", ":", "attributes_only_filters", ",", "associations", ":", "associations_only_filters", "}", ",", "attributes", ":", "attributes_except_filters", ",", "associations", ":", "associations_except_filters", ")", "end", "end" ]
Applies attributes and association filters
[ "Applies", "attributes", "and", "association", "filters" ]
bbd23293b33cd8c25efc7609382139716b1b9ec7
https://github.com/yosiat/panko_serializer/blob/bbd23293b33cd8c25efc7609382139716b1b9ec7/lib/panko/serialization_descriptor.rb#L56-L89
16,166
FooBarWidget/default_value_for
lib/default_value_for.rb
DefaultValueFor.ClassMethods.default_value_for
def default_value_for(attribute, options = {}, &block) value = options allows_nil = true if options.is_a?(Hash) opts = options.stringify_keys value = opts.fetch('value', options) allows_nil = opts.fetch('allows_nil', true) end if !method_defined?(:set_default_values) include(InstanceMethods) after_initialize :set_default_values class_attribute :_default_attribute_values class_attribute :_default_attribute_values_not_allowing_nil extend(DelayedClassMethods) init_hash = true else init_hash = !singleton_methods(false).include?(:_default_attribute_values) end if init_hash self._default_attribute_values = {} self._default_attribute_values_not_allowing_nil = [] end if block_given? container = BlockValueContainer.new(block) else container = NormalValueContainer.new(value) end _default_attribute_values[attribute.to_s] = container _default_attribute_values_not_allowing_nil << attribute.to_s unless allows_nil end
ruby
def default_value_for(attribute, options = {}, &block) value = options allows_nil = true if options.is_a?(Hash) opts = options.stringify_keys value = opts.fetch('value', options) allows_nil = opts.fetch('allows_nil', true) end if !method_defined?(:set_default_values) include(InstanceMethods) after_initialize :set_default_values class_attribute :_default_attribute_values class_attribute :_default_attribute_values_not_allowing_nil extend(DelayedClassMethods) init_hash = true else init_hash = !singleton_methods(false).include?(:_default_attribute_values) end if init_hash self._default_attribute_values = {} self._default_attribute_values_not_allowing_nil = [] end if block_given? container = BlockValueContainer.new(block) else container = NormalValueContainer.new(value) end _default_attribute_values[attribute.to_s] = container _default_attribute_values_not_allowing_nil << attribute.to_s unless allows_nil end
[ "def", "default_value_for", "(", "attribute", ",", "options", "=", "{", "}", ",", "&", "block", ")", "value", "=", "options", "allows_nil", "=", "true", "if", "options", ".", "is_a?", "(", "Hash", ")", "opts", "=", "options", ".", "stringify_keys", "value", "=", "opts", ".", "fetch", "(", "'value'", ",", "options", ")", "allows_nil", "=", "opts", ".", "fetch", "(", "'allows_nil'", ",", "true", ")", "end", "if", "!", "method_defined?", "(", ":set_default_values", ")", "include", "(", "InstanceMethods", ")", "after_initialize", ":set_default_values", "class_attribute", ":_default_attribute_values", "class_attribute", ":_default_attribute_values_not_allowing_nil", "extend", "(", "DelayedClassMethods", ")", "init_hash", "=", "true", "else", "init_hash", "=", "!", "singleton_methods", "(", "false", ")", ".", "include?", "(", ":_default_attribute_values", ")", "end", "if", "init_hash", "self", ".", "_default_attribute_values", "=", "{", "}", "self", ".", "_default_attribute_values_not_allowing_nil", "=", "[", "]", "end", "if", "block_given?", "container", "=", "BlockValueContainer", ".", "new", "(", "block", ")", "else", "container", "=", "NormalValueContainer", ".", "new", "(", "value", ")", "end", "_default_attribute_values", "[", "attribute", ".", "to_s", "]", "=", "container", "_default_attribute_values_not_allowing_nil", "<<", "attribute", ".", "to_s", "unless", "allows_nil", "end" ]
Declares a default value for the given attribute. Sets the default value to the given options parameter unless the given options equal { :value => ... } The <tt>options</tt> can be used to specify the following things: * <tt>value</tt> - Sets the default value. * <tt>allows_nil (default: true)</tt> - Sets explicitly passed nil values if option is set to true.
[ "Declares", "a", "default", "value", "for", "the", "given", "attribute", "." ]
d5fe8f13aed6e63df5e5128c7625ccf46f66eea8
https://github.com/FooBarWidget/default_value_for/blob/d5fe8f13aed6e63df5e5128c7625ccf46f66eea8/lib/default_value_for.rb#L58-L94
16,167
zendesk/zendesk_apps_support
lib/zendesk_apps_support/package.rb
ZendeskAppsSupport.Package.compile
def compile(options) begin app_id = options.fetch(:app_id) asset_url_prefix = options.fetch(:assets_dir) name = options.fetch(:app_name) rescue KeyError => e raise ArgumentError, e.message end locale = options.fetch(:locale, 'en') source = manifest.iframe_only? ? nil : app_js app_class_name = "app-#{app_id}" # if no_template is an array, we still need the templates templates = manifest.no_template == true ? {} : compiled_templates(app_id, asset_url_prefix) SRC_TEMPLATE.result( name: name, version: manifest.version, source: source, app_class_properties: manifest.app_class_properties, asset_url_prefix: asset_url_prefix, logo_asset_hash: generate_logo_hash(manifest.products), location_icons: location_icons, app_class_name: app_class_name, author: manifest.author, translations: manifest.iframe_only? ? nil : runtime_translations(translations_for(locale)), framework_version: manifest.framework_version, templates: templates, modules: commonjs_modules, iframe_only: manifest.iframe_only? ) end
ruby
def compile(options) begin app_id = options.fetch(:app_id) asset_url_prefix = options.fetch(:assets_dir) name = options.fetch(:app_name) rescue KeyError => e raise ArgumentError, e.message end locale = options.fetch(:locale, 'en') source = manifest.iframe_only? ? nil : app_js app_class_name = "app-#{app_id}" # if no_template is an array, we still need the templates templates = manifest.no_template == true ? {} : compiled_templates(app_id, asset_url_prefix) SRC_TEMPLATE.result( name: name, version: manifest.version, source: source, app_class_properties: manifest.app_class_properties, asset_url_prefix: asset_url_prefix, logo_asset_hash: generate_logo_hash(manifest.products), location_icons: location_icons, app_class_name: app_class_name, author: manifest.author, translations: manifest.iframe_only? ? nil : runtime_translations(translations_for(locale)), framework_version: manifest.framework_version, templates: templates, modules: commonjs_modules, iframe_only: manifest.iframe_only? ) end
[ "def", "compile", "(", "options", ")", "begin", "app_id", "=", "options", ".", "fetch", "(", ":app_id", ")", "asset_url_prefix", "=", "options", ".", "fetch", "(", ":assets_dir", ")", "name", "=", "options", ".", "fetch", "(", ":app_name", ")", "rescue", "KeyError", "=>", "e", "raise", "ArgumentError", ",", "e", ".", "message", "end", "locale", "=", "options", ".", "fetch", "(", ":locale", ",", "'en'", ")", "source", "=", "manifest", ".", "iframe_only?", "?", "nil", ":", "app_js", "app_class_name", "=", "\"app-#{app_id}\"", "# if no_template is an array, we still need the templates", "templates", "=", "manifest", ".", "no_template", "==", "true", "?", "{", "}", ":", "compiled_templates", "(", "app_id", ",", "asset_url_prefix", ")", "SRC_TEMPLATE", ".", "result", "(", "name", ":", "name", ",", "version", ":", "manifest", ".", "version", ",", "source", ":", "source", ",", "app_class_properties", ":", "manifest", ".", "app_class_properties", ",", "asset_url_prefix", ":", "asset_url_prefix", ",", "logo_asset_hash", ":", "generate_logo_hash", "(", "manifest", ".", "products", ")", ",", "location_icons", ":", "location_icons", ",", "app_class_name", ":", "app_class_name", ",", "author", ":", "manifest", ".", "author", ",", "translations", ":", "manifest", ".", "iframe_only?", "?", "nil", ":", "runtime_translations", "(", "translations_for", "(", "locale", ")", ")", ",", "framework_version", ":", "manifest", ".", "framework_version", ",", "templates", ":", "templates", ",", "modules", ":", "commonjs_modules", ",", "iframe_only", ":", "manifest", ".", "iframe_only?", ")", "end" ]
this is not really compile_js, it compiles the whole app including scss for v1 apps
[ "this", "is", "not", "really", "compile_js", "it", "compiles", "the", "whole", "app", "including", "scss", "for", "v1", "apps" ]
d744af677c8d05706a63a25c2aee0203d2a3f102
https://github.com/zendesk/zendesk_apps_support/blob/d744af677c8d05706a63a25c2aee0203d2a3f102/lib/zendesk_apps_support/package.rb#L108-L140
16,168
cldwalker/hirb
lib/hirb/helpers/table.rb
Hirb.Helpers::Table.default_field_lengths
def default_field_lengths field_lengths = @headers ? @headers.inject({}) {|h,(k,v)| h[k] = String.size(v); h} : @fields.inject({}) {|h,e| h[e] = 1; h } @rows.each do |row| @fields.each do |field| len = String.size(row[field]) field_lengths[field] = len if len > field_lengths[field].to_i end end field_lengths end
ruby
def default_field_lengths field_lengths = @headers ? @headers.inject({}) {|h,(k,v)| h[k] = String.size(v); h} : @fields.inject({}) {|h,e| h[e] = 1; h } @rows.each do |row| @fields.each do |field| len = String.size(row[field]) field_lengths[field] = len if len > field_lengths[field].to_i end end field_lengths end
[ "def", "default_field_lengths", "field_lengths", "=", "@headers", "?", "@headers", ".", "inject", "(", "{", "}", ")", "{", "|", "h", ",", "(", "k", ",", "v", ")", "|", "h", "[", "k", "]", "=", "String", ".", "size", "(", "v", ")", ";", "h", "}", ":", "@fields", ".", "inject", "(", "{", "}", ")", "{", "|", "h", ",", "e", "|", "h", "[", "e", "]", "=", "1", ";", "h", "}", "@rows", ".", "each", "do", "|", "row", "|", "@fields", ".", "each", "do", "|", "field", "|", "len", "=", "String", ".", "size", "(", "row", "[", "field", "]", ")", "field_lengths", "[", "field", "]", "=", "len", "if", "len", ">", "field_lengths", "[", "field", "]", ".", "to_i", "end", "end", "field_lengths", "end" ]
find max length for each field; start with the headers
[ "find", "max", "length", "for", "each", "field", ";", "start", "with", "the", "headers" ]
264f72c7c0f0966001e802414a5b0641036c7860
https://github.com/cldwalker/hirb/blob/264f72c7c0f0966001e802414a5b0641036c7860/lib/hirb/helpers/table.rb#L322-L332
16,169
cldwalker/hirb
lib/hirb/helpers/table.rb
Hirb.Helpers::Table.array_to_indices_hash
def array_to_indices_hash(array) array.inject({}) {|hash,e| hash[hash.size] = e; hash } end
ruby
def array_to_indices_hash(array) array.inject({}) {|hash,e| hash[hash.size] = e; hash } end
[ "def", "array_to_indices_hash", "(", "array", ")", "array", ".", "inject", "(", "{", "}", ")", "{", "|", "hash", ",", "e", "|", "hash", "[", "hash", ".", "size", "]", "=", "e", ";", "hash", "}", "end" ]
Converts an array to a hash mapping a numerical index to its array value.
[ "Converts", "an", "array", "to", "a", "hash", "mapping", "a", "numerical", "index", "to", "its", "array", "value", "." ]
264f72c7c0f0966001e802414a5b0641036c7860
https://github.com/cldwalker/hirb/blob/264f72c7c0f0966001e802414a5b0641036c7860/lib/hirb/helpers/table.rb#L371-L373
16,170
cldwalker/hirb
lib/hirb/formatter.rb
Hirb.Formatter.format_output
def format_output(output, options={}, &block) output_class = determine_output_class(output) options = parse_console_options(options) if options.delete(:console) options = Util.recursive_hash_merge(klass_config(output_class), options) _format_output(output, options, &block) end
ruby
def format_output(output, options={}, &block) output_class = determine_output_class(output) options = parse_console_options(options) if options.delete(:console) options = Util.recursive_hash_merge(klass_config(output_class), options) _format_output(output, options, &block) end
[ "def", "format_output", "(", "output", ",", "options", "=", "{", "}", ",", "&", "block", ")", "output_class", "=", "determine_output_class", "(", "output", ")", "options", "=", "parse_console_options", "(", "options", ")", "if", "options", ".", "delete", "(", ":console", ")", "options", "=", "Util", ".", "recursive_hash_merge", "(", "klass_config", "(", "output_class", ")", ",", "options", ")", "_format_output", "(", "output", ",", "options", ",", "block", ")", "end" ]
This method looks for an output object's view in Formatter.config and then Formatter.dynamic_config. If a view is found, a stringified view is returned based on the object. If no view is found, nil is returned. The options this class takes are a view hash as described in Formatter.config. These options will be merged with any existing helper config hash an output class has in Formatter.config. Any block given is passed along to a helper class.
[ "This", "method", "looks", "for", "an", "output", "object", "s", "view", "in", "Formatter", ".", "config", "and", "then", "Formatter", ".", "dynamic_config", ".", "If", "a", "view", "is", "found", "a", "stringified", "view", "is", "returned", "based", "on", "the", "object", ".", "If", "no", "view", "is", "found", "nil", "is", "returned", ".", "The", "options", "this", "class", "takes", "are", "a", "view", "hash", "as", "described", "in", "Formatter", ".", "config", ".", "These", "options", "will", "be", "merged", "with", "any", "existing", "helper", "config", "hash", "an", "output", "class", "has", "in", "Formatter", ".", "config", ".", "Any", "block", "given", "is", "passed", "along", "to", "a", "helper", "class", "." ]
264f72c7c0f0966001e802414a5b0641036c7860
https://github.com/cldwalker/hirb/blob/264f72c7c0f0966001e802414a5b0641036c7860/lib/hirb/formatter.rb#L52-L57
16,171
cldwalker/hirb
lib/hirb/dynamic_view.rb
Hirb.DynamicView.dynamic_options
def dynamic_options(obj) view_methods.each do |meth| if obj.class.ancestors.map {|e| e.to_s }.include?(method_to_class(meth)) begin return send(meth, obj) rescue raise "View failed to generate for '#{method_to_class(meth)}' "+ "while in '#{meth}' with error:\n#{$!.message}" end end end nil end
ruby
def dynamic_options(obj) view_methods.each do |meth| if obj.class.ancestors.map {|e| e.to_s }.include?(method_to_class(meth)) begin return send(meth, obj) rescue raise "View failed to generate for '#{method_to_class(meth)}' "+ "while in '#{meth}' with error:\n#{$!.message}" end end end nil end
[ "def", "dynamic_options", "(", "obj", ")", "view_methods", ".", "each", "do", "|", "meth", "|", "if", "obj", ".", "class", ".", "ancestors", ".", "map", "{", "|", "e", "|", "e", ".", "to_s", "}", ".", "include?", "(", "method_to_class", "(", "meth", ")", ")", "begin", "return", "send", "(", "meth", ",", "obj", ")", "rescue", "raise", "\"View failed to generate for '#{method_to_class(meth)}' \"", "+", "\"while in '#{meth}' with error:\\n#{$!.message}\"", "end", "end", "end", "nil", "end" ]
Returns a hash of options based on dynamic views defined for the object's ancestry. If no config is found returns nil.
[ "Returns", "a", "hash", "of", "options", "based", "on", "dynamic", "views", "defined", "for", "the", "object", "s", "ancestry", ".", "If", "no", "config", "is", "found", "returns", "nil", "." ]
264f72c7c0f0966001e802414a5b0641036c7860
https://github.com/cldwalker/hirb/blob/264f72c7c0f0966001e802414a5b0641036c7860/lib/hirb/dynamic_view.rb#L69-L81
16,172
cldwalker/hirb
lib/hirb/pager.rb
Hirb.Pager.activated_by?
def activated_by?(string_to_page, inspect_mode=false) inspect_mode ? (String.size(string_to_page) > @height * @width) : (string_to_page.count("\n") > @height) end
ruby
def activated_by?(string_to_page, inspect_mode=false) inspect_mode ? (String.size(string_to_page) > @height * @width) : (string_to_page.count("\n") > @height) end
[ "def", "activated_by?", "(", "string_to_page", ",", "inspect_mode", "=", "false", ")", "inspect_mode", "?", "(", "String", ".", "size", "(", "string_to_page", ")", ">", "@height", "*", "@width", ")", ":", "(", "string_to_page", ".", "count", "(", "\"\\n\"", ")", ">", "@height", ")", "end" ]
Determines if string should be paged based on configured width and height.
[ "Determines", "if", "string", "should", "be", "paged", "based", "on", "configured", "width", "and", "height", "." ]
264f72c7c0f0966001e802414a5b0641036c7860
https://github.com/cldwalker/hirb/blob/264f72c7c0f0966001e802414a5b0641036c7860/lib/hirb/pager.rb#L88-L90
16,173
cldwalker/hirb
lib/hirb/util.rb
Hirb.Util.recursive_hash_merge
def recursive_hash_merge(hash1, hash2) hash1.merge(hash2) {|k,o,n| (o.is_a?(Hash)) ? recursive_hash_merge(o,n) : n} end
ruby
def recursive_hash_merge(hash1, hash2) hash1.merge(hash2) {|k,o,n| (o.is_a?(Hash)) ? recursive_hash_merge(o,n) : n} end
[ "def", "recursive_hash_merge", "(", "hash1", ",", "hash2", ")", "hash1", ".", "merge", "(", "hash2", ")", "{", "|", "k", ",", "o", ",", "n", "|", "(", "o", ".", "is_a?", "(", "Hash", ")", ")", "?", "recursive_hash_merge", "(", "o", ",", "n", ")", ":", "n", "}", "end" ]
Recursively merge hash1 with hash2.
[ "Recursively", "merge", "hash1", "with", "hash2", "." ]
264f72c7c0f0966001e802414a5b0641036c7860
https://github.com/cldwalker/hirb/blob/264f72c7c0f0966001e802414a5b0641036c7860/lib/hirb/util.rb#L21-L23
16,174
cldwalker/hirb
lib/hirb/util.rb
Hirb.Util.find_home
def find_home ['HOME', 'USERPROFILE'].each {|e| return ENV[e] if ENV[e] } return "#{ENV['HOMEDRIVE']}#{ENV['HOMEPATH']}" if ENV['HOMEDRIVE'] && ENV['HOMEPATH'] File.expand_path("~") rescue File::ALT_SEPARATOR ? "C:/" : "/" end
ruby
def find_home ['HOME', 'USERPROFILE'].each {|e| return ENV[e] if ENV[e] } return "#{ENV['HOMEDRIVE']}#{ENV['HOMEPATH']}" if ENV['HOMEDRIVE'] && ENV['HOMEPATH'] File.expand_path("~") rescue File::ALT_SEPARATOR ? "C:/" : "/" end
[ "def", "find_home", "[", "'HOME'", ",", "'USERPROFILE'", "]", ".", "each", "{", "|", "e", "|", "return", "ENV", "[", "e", "]", "if", "ENV", "[", "e", "]", "}", "return", "\"#{ENV['HOMEDRIVE']}#{ENV['HOMEPATH']}\"", "if", "ENV", "[", "'HOMEDRIVE'", "]", "&&", "ENV", "[", "'HOMEPATH'", "]", "File", ".", "expand_path", "(", "\"~\"", ")", "rescue", "File", "::", "ALT_SEPARATOR", "?", "\"C:/\"", ":", "\"/\"", "end" ]
From Rubygems, determine a user's home.
[ "From", "Rubygems", "determine", "a", "user", "s", "home", "." ]
264f72c7c0f0966001e802414a5b0641036c7860
https://github.com/cldwalker/hirb/blob/264f72c7c0f0966001e802414a5b0641036c7860/lib/hirb/util.rb#L88-L94
16,175
sendgrid/ruby-http-client
lib/ruby_http_client.rb
SendGrid.Client.build_args
def build_args(args) args.each do |arg| arg.each do |key, value| case key.to_s when 'query_params' @query_params = value when 'request_headers' update_headers(value) when 'request_body' @request_body = value end end end end
ruby
def build_args(args) args.each do |arg| arg.each do |key, value| case key.to_s when 'query_params' @query_params = value when 'request_headers' update_headers(value) when 'request_body' @request_body = value end end end end
[ "def", "build_args", "(", "args", ")", "args", ".", "each", "do", "|", "arg", "|", "arg", ".", "each", "do", "|", "key", ",", "value", "|", "case", "key", ".", "to_s", "when", "'query_params'", "@query_params", "=", "value", "when", "'request_headers'", "update_headers", "(", "value", ")", "when", "'request_body'", "@request_body", "=", "value", "end", "end", "end", "end" ]
Set the query params, request headers and request body * *Args* : - +args+ -> array of args obtained from method_missing
[ "Set", "the", "query", "params", "request", "headers", "and", "request", "body" ]
37fb6943258dd8dec0cd7fc5e7d54704471b97cc
https://github.com/sendgrid/ruby-http-client/blob/37fb6943258dd8dec0cd7fc5e7d54704471b97cc/lib/ruby_http_client.rb#L106-L119
16,176
sendgrid/ruby-http-client
lib/ruby_http_client.rb
SendGrid.Client.build_url
def build_url(query_params: nil) url = [add_version(''), *@url_path].join('/') url = build_query_params(url, query_params) if query_params URI.parse("#{@host}#{url}") end
ruby
def build_url(query_params: nil) url = [add_version(''), *@url_path].join('/') url = build_query_params(url, query_params) if query_params URI.parse("#{@host}#{url}") end
[ "def", "build_url", "(", "query_params", ":", "nil", ")", "url", "=", "[", "add_version", "(", "''", ")", ",", "@url_path", "]", ".", "join", "(", "'/'", ")", "url", "=", "build_query_params", "(", "url", ",", "query_params", ")", "if", "query_params", "URI", ".", "parse", "(", "\"#{@host}#{url}\"", ")", "end" ]
Build the final url * *Args* : - +query_params+ -> A hash of query parameters * *Returns* : - The final url string
[ "Build", "the", "final", "url" ]
37fb6943258dd8dec0cd7fc5e7d54704471b97cc
https://github.com/sendgrid/ruby-http-client/blob/37fb6943258dd8dec0cd7fc5e7d54704471b97cc/lib/ruby_http_client.rb#L128-L132
16,177
sendgrid/ruby-http-client
lib/ruby_http_client.rb
SendGrid.Client.make_request
def make_request(http, request) response = http.request(request) Response.new(response) end
ruby
def make_request(http, request) response = http.request(request) Response.new(response) end
[ "def", "make_request", "(", "http", ",", "request", ")", "response", "=", "http", ".", "request", "(", "request", ")", "Response", ".", "new", "(", "response", ")", "end" ]
Make the API call and return the response. This is separated into it's own function, so we can mock it easily for testing. * *Args* : - +http+ -> NET:HTTP request object - +request+ -> NET::HTTP request object * *Returns* : - Response object
[ "Make", "the", "API", "call", "and", "return", "the", "response", ".", "This", "is", "separated", "into", "it", "s", "own", "function", "so", "we", "can", "mock", "it", "easily", "for", "testing", "." ]
37fb6943258dd8dec0cd7fc5e7d54704471b97cc
https://github.com/sendgrid/ruby-http-client/blob/37fb6943258dd8dec0cd7fc5e7d54704471b97cc/lib/ruby_http_client.rb#L174-L177
16,178
sendgrid/ruby-http-client
lib/ruby_http_client.rb
SendGrid.Client.build_http
def build_http(host, port) params = [host, port] params += @proxy_options.values_at(:host, :port, :user, :pass) unless @proxy_options.empty? add_ssl(Net::HTTP.new(*params)) end
ruby
def build_http(host, port) params = [host, port] params += @proxy_options.values_at(:host, :port, :user, :pass) unless @proxy_options.empty? add_ssl(Net::HTTP.new(*params)) end
[ "def", "build_http", "(", "host", ",", "port", ")", "params", "=", "[", "host", ",", "port", "]", "params", "+=", "@proxy_options", ".", "values_at", "(", ":host", ",", ":port", ",", ":user", ",", ":pass", ")", "unless", "@proxy_options", ".", "empty?", "add_ssl", "(", "Net", "::", "HTTP", ".", "new", "(", "params", ")", ")", "end" ]
Build HTTP request object * *Returns* : - Request object
[ "Build", "HTTP", "request", "object" ]
37fb6943258dd8dec0cd7fc5e7d54704471b97cc
https://github.com/sendgrid/ruby-http-client/blob/37fb6943258dd8dec0cd7fc5e7d54704471b97cc/lib/ruby_http_client.rb#L183-L187
16,179
sendgrid/ruby-http-client
lib/ruby_http_client.rb
SendGrid.Client.add_ssl
def add_ssl(http) if host.start_with?('https') http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_PEER end http end
ruby
def add_ssl(http) if host.start_with?('https') http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_PEER end http end
[ "def", "add_ssl", "(", "http", ")", "if", "host", ".", "start_with?", "(", "'https'", ")", "http", ".", "use_ssl", "=", "true", "http", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_PEER", "end", "http", "end" ]
Allow for https calls * *Args* : - +http+ -> HTTP::NET object * *Returns* : - HTTP::NET object
[ "Allow", "for", "https", "calls" ]
37fb6943258dd8dec0cd7fc5e7d54704471b97cc
https://github.com/sendgrid/ruby-http-client/blob/37fb6943258dd8dec0cd7fc5e7d54704471b97cc/lib/ruby_http_client.rb#L196-L202
16,180
soveran/ohm
lib/ohm.rb
Ohm.Collection.fetch
def fetch(ids) data = nil model.synchronize do ids.each do |id| redis.queue("HGETALL", namespace[id]) end data = redis.commit end return [] if data.nil? [].tap do |result| data.each_with_index do |atts, idx| result << model.new(Utils.dict(atts).update(:id => ids[idx])) end end end
ruby
def fetch(ids) data = nil model.synchronize do ids.each do |id| redis.queue("HGETALL", namespace[id]) end data = redis.commit end return [] if data.nil? [].tap do |result| data.each_with_index do |atts, idx| result << model.new(Utils.dict(atts).update(:id => ids[idx])) end end end
[ "def", "fetch", "(", "ids", ")", "data", "=", "nil", "model", ".", "synchronize", "do", "ids", ".", "each", "do", "|", "id", "|", "redis", ".", "queue", "(", "\"HGETALL\"", ",", "namespace", "[", "id", "]", ")", "end", "data", "=", "redis", ".", "commit", "end", "return", "[", "]", "if", "data", ".", "nil?", "[", "]", ".", "tap", "do", "|", "result", "|", "data", ".", "each_with_index", "do", "|", "atts", ",", "idx", "|", "result", "<<", "model", ".", "new", "(", "Utils", ".", "dict", "(", "atts", ")", ".", "update", "(", ":id", "=>", "ids", "[", "idx", "]", ")", ")", "end", "end", "end" ]
Wraps the whole pipelining functionality.
[ "Wraps", "the", "whole", "pipelining", "functionality", "." ]
122407ee8fb2e8223bfa2cd10feea50e42dc49ae
https://github.com/soveran/ohm/blob/122407ee8fb2e8223bfa2cd10feea50e42dc49ae/lib/ohm.rb#L140-L158
16,181
soveran/ohm
lib/ohm.rb
Ohm.Set.sort
def sort(options = {}) if options.has_key?(:get) options[:get] = to_key(options[:get]) Stal.solve(redis, ["SORT", key, *Utils.sort_options(options)]) else fetch(Stal.solve(redis, ["SORT", key, *Utils.sort_options(options)])) end end
ruby
def sort(options = {}) if options.has_key?(:get) options[:get] = to_key(options[:get]) Stal.solve(redis, ["SORT", key, *Utils.sort_options(options)]) else fetch(Stal.solve(redis, ["SORT", key, *Utils.sort_options(options)])) end end
[ "def", "sort", "(", "options", "=", "{", "}", ")", "if", "options", ".", "has_key?", "(", ":get", ")", "options", "[", ":get", "]", "=", "to_key", "(", "options", "[", ":get", "]", ")", "Stal", ".", "solve", "(", "redis", ",", "[", "\"SORT\"", ",", "key", ",", "Utils", ".", "sort_options", "(", "options", ")", "]", ")", "else", "fetch", "(", "Stal", ".", "solve", "(", "redis", ",", "[", "\"SORT\"", ",", "key", ",", "Utils", ".", "sort_options", "(", "options", ")", "]", ")", ")", "end", "end" ]
Allows you to sort your models using their IDs. This is much faster than `sort_by`. If you simply want to get records in ascending or descending order, then this is the best method to do that. Example: class User < Ohm::Model attribute :name end User.create(:name => "John") User.create(:name => "Jane") User.all.sort.map(&:id) == ["1", "2"] # => true User.all.sort(:order => "ASC").map(&:id) == ["1", "2"] # => true User.all.sort(:order => "DESC").map(&:id) == ["2", "1"] # => true
[ "Allows", "you", "to", "sort", "your", "models", "using", "their", "IDs", ".", "This", "is", "much", "faster", "than", "sort_by", ".", "If", "you", "simply", "want", "to", "get", "records", "in", "ascending", "or", "descending", "order", "then", "this", "is", "the", "best", "method", "to", "do", "that", "." ]
122407ee8fb2e8223bfa2cd10feea50e42dc49ae
https://github.com/soveran/ohm/blob/122407ee8fb2e8223bfa2cd10feea50e42dc49ae/lib/ohm.rb#L451-L459
16,182
soveran/ohm
lib/ohm.rb
Ohm.Set.find
def find(dict) Ohm::Set.new( model, namespace, [:SINTER, key, *model.filters(dict)] ) end
ruby
def find(dict) Ohm::Set.new( model, namespace, [:SINTER, key, *model.filters(dict)] ) end
[ "def", "find", "(", "dict", ")", "Ohm", "::", "Set", ".", "new", "(", "model", ",", "namespace", ",", "[", ":SINTER", ",", "key", ",", "model", ".", "filters", "(", "dict", ")", "]", ")", "end" ]
Chain new fiters on an existing set. Example: set = User.find(:name => "John") set.find(:age => 30)
[ "Chain", "new", "fiters", "on", "an", "existing", "set", "." ]
122407ee8fb2e8223bfa2cd10feea50e42dc49ae
https://github.com/soveran/ohm/blob/122407ee8fb2e8223bfa2cd10feea50e42dc49ae/lib/ohm.rb#L521-L525
16,183
soveran/ohm
lib/ohm.rb
Ohm.MutableSet.replace
def replace(models) ids = models.map(&:id) model.synchronize do redis.queue("MULTI") redis.queue("DEL", key) ids.each { |id| redis.queue("SADD", key, id) } redis.queue("EXEC") redis.commit end end
ruby
def replace(models) ids = models.map(&:id) model.synchronize do redis.queue("MULTI") redis.queue("DEL", key) ids.each { |id| redis.queue("SADD", key, id) } redis.queue("EXEC") redis.commit end end
[ "def", "replace", "(", "models", ")", "ids", "=", "models", ".", "map", "(", ":id", ")", "model", ".", "synchronize", "do", "redis", ".", "queue", "(", "\"MULTI\"", ")", "redis", ".", "queue", "(", "\"DEL\"", ",", "key", ")", "ids", ".", "each", "{", "|", "id", "|", "redis", ".", "queue", "(", "\"SADD\"", ",", "key", ",", "id", ")", "}", "redis", ".", "queue", "(", "\"EXEC\"", ")", "redis", ".", "commit", "end", "end" ]
Replace all the existing elements of a set with a different collection of models. This happens atomically in a MULTI-EXEC block. Example: user = User.create p1 = Post.create user.posts.add(p1) p2, p3 = Post.create, Post.create user.posts.replace([p2, p3]) user.posts.include?(p1) # => false
[ "Replace", "all", "the", "existing", "elements", "of", "a", "set", "with", "a", "different", "collection", "of", "models", ".", "This", "happens", "atomically", "in", "a", "MULTI", "-", "EXEC", "block", "." ]
122407ee8fb2e8223bfa2cd10feea50e42dc49ae
https://github.com/soveran/ohm/blob/122407ee8fb2e8223bfa2cd10feea50e42dc49ae/lib/ohm.rb#L636-L646
16,184
soveran/ohm
lib/ohm.rb
Ohm.Model.set
def set(att, val) if val.to_s.empty? key.call("HDEL", att) else key.call("HSET", att, val) end @attributes[att] = val end
ruby
def set(att, val) if val.to_s.empty? key.call("HDEL", att) else key.call("HSET", att, val) end @attributes[att] = val end
[ "def", "set", "(", "att", ",", "val", ")", "if", "val", ".", "to_s", ".", "empty?", "key", ".", "call", "(", "\"HDEL\"", ",", "att", ")", "else", "key", ".", "call", "(", "\"HSET\"", ",", "att", ",", "val", ")", "end", "@attributes", "[", "att", "]", "=", "val", "end" ]
Update an attribute value atomically. The best usecase for this is when you simply want to update one value. Note: This method is dangerous because it doesn't update indices and uniques. Use it wisely. The safe equivalent is `update`.
[ "Update", "an", "attribute", "value", "atomically", ".", "The", "best", "usecase", "for", "this", "is", "when", "you", "simply", "want", "to", "update", "one", "value", "." ]
122407ee8fb2e8223bfa2cd10feea50e42dc49ae
https://github.com/soveran/ohm/blob/122407ee8fb2e8223bfa2cd10feea50e42dc49ae/lib/ohm.rb#L1181-L1189
16,185
soveran/ohm
lib/ohm.rb
Ohm.Model.save
def save indices = {} model.indices.each do |field| next unless (value = send(field)) indices[field] = Array(value).map(&:to_s) end uniques = {} model.uniques.each do |field| next unless (value = send(field)) uniques[field] = value.to_s end features = { "name" => model.name } if defined?(@id) features["id"] = @id end @id = script(LUA_SAVE, 0, features.to_json, _sanitized_attributes.to_json, indices.to_json, uniques.to_json ) return self end
ruby
def save indices = {} model.indices.each do |field| next unless (value = send(field)) indices[field] = Array(value).map(&:to_s) end uniques = {} model.uniques.each do |field| next unless (value = send(field)) uniques[field] = value.to_s end features = { "name" => model.name } if defined?(@id) features["id"] = @id end @id = script(LUA_SAVE, 0, features.to_json, _sanitized_attributes.to_json, indices.to_json, uniques.to_json ) return self end
[ "def", "save", "indices", "=", "{", "}", "model", ".", "indices", ".", "each", "do", "|", "field", "|", "next", "unless", "(", "value", "=", "send", "(", "field", ")", ")", "indices", "[", "field", "]", "=", "Array", "(", "value", ")", ".", "map", "(", ":to_s", ")", "end", "uniques", "=", "{", "}", "model", ".", "uniques", ".", "each", "do", "|", "field", "|", "next", "unless", "(", "value", "=", "send", "(", "field", ")", ")", "uniques", "[", "field", "]", "=", "value", ".", "to_s", "end", "features", "=", "{", "\"name\"", "=>", "model", ".", "name", "}", "if", "defined?", "(", "@id", ")", "features", "[", "\"id\"", "]", "=", "@id", "end", "@id", "=", "script", "(", "LUA_SAVE", ",", "0", ",", "features", ".", "to_json", ",", "_sanitized_attributes", ".", "to_json", ",", "indices", ".", "to_json", ",", "uniques", ".", "to_json", ")", "return", "self", "end" ]
Persist the model attributes and update indices and unique indices. The `counter`s and `set`s are not touched during save. Example: class User < Ohm::Model attribute :name end u = User.new(:name => "John").save u.kind_of?(User) # => true
[ "Persist", "the", "model", "attributes", "and", "update", "indices", "and", "unique", "indices", ".", "The", "counter", "s", "and", "set", "s", "are", "not", "touched", "during", "save", "." ]
122407ee8fb2e8223bfa2cd10feea50e42dc49ae
https://github.com/soveran/ohm/blob/122407ee8fb2e8223bfa2cd10feea50e42dc49ae/lib/ohm.rb#L1365-L1394
16,186
robwierzbowski/jekyll-picture-tag
lib/jekyll-picture-tag/source_image.rb
PictureTag.SourceImage.grab_file
def grab_file(source_file) source_name = File.join(PictureTag.config.source_dir, source_file) unless File.exist? source_name raise "Jekyll Picture Tag could not find #{source_name}." end source_name end
ruby
def grab_file(source_file) source_name = File.join(PictureTag.config.source_dir, source_file) unless File.exist? source_name raise "Jekyll Picture Tag could not find #{source_name}." end source_name end
[ "def", "grab_file", "(", "source_file", ")", "source_name", "=", "File", ".", "join", "(", "PictureTag", ".", "config", ".", "source_dir", ",", "source_file", ")", "unless", "File", ".", "exist?", "source_name", "raise", "\"Jekyll Picture Tag could not find #{source_name}.\"", "end", "source_name", "end" ]
Turn a relative filename into an absolute one, and make sure it exists.
[ "Turn", "a", "relative", "filename", "into", "an", "absolute", "one", "and", "make", "sure", "it", "exists", "." ]
e63cf4e024d413880f6a252ab7d7a167c96b01af
https://github.com/robwierzbowski/jekyll-picture-tag/blob/e63cf4e024d413880f6a252ab7d7a167c96b01af/lib/jekyll-picture-tag/source_image.rb#L52-L60
16,187
Mange/roadie
lib/roadie/document.rb
Roadie.Document.transform
def transform dom = Nokogiri::HTML.parse html callback before_transformation, dom improve dom inline dom, keep_uninlinable_in: :head rewrite_urls dom callback after_transformation, dom remove_ignore_markers dom serialize_document dom end
ruby
def transform dom = Nokogiri::HTML.parse html callback before_transformation, dom improve dom inline dom, keep_uninlinable_in: :head rewrite_urls dom callback after_transformation, dom remove_ignore_markers dom serialize_document dom end
[ "def", "transform", "dom", "=", "Nokogiri", "::", "HTML", ".", "parse", "html", "callback", "before_transformation", ",", "dom", "improve", "dom", "inline", "dom", ",", "keep_uninlinable_in", ":", ":head", "rewrite_urls", "dom", "callback", "after_transformation", ",", "dom", "remove_ignore_markers", "dom", "serialize_document", "dom", "end" ]
Transform the input HTML as a full document and returns the processed HTML. Before the transformation begins, the {#before_transformation} callback will be called with the parsed HTML tree and the {Document} instance, and after all work is complete the {#after_transformation} callback will be invoked in the same way. Most of the work is delegated to other classes. A list of them can be seen below. @see MarkupImprover MarkupImprover (improves the markup of the DOM) @see Inliner Inliner (inlines the stylesheets) @see UrlRewriter UrlRewriter (rewrites URLs and makes them absolute) @see #transform_partial Transforms partial documents (fragments) @return [String] the transformed HTML
[ "Transform", "the", "input", "HTML", "as", "a", "full", "document", "and", "returns", "the", "processed", "HTML", "." ]
afda57d66b7653a0978604f1d81cccd93e8748c9
https://github.com/Mange/roadie/blob/afda57d66b7653a0978604f1d81cccd93e8748c9/lib/roadie/document.rb#L80-L93
16,188
Mange/roadie
lib/roadie/asset_scanner.rb
Roadie.AssetScanner.extract_css
def extract_css stylesheets = @dom.css(STYLE_ELEMENT_QUERY).map { |element| stylesheet = read_stylesheet(element) element.remove if stylesheet stylesheet }.compact stylesheets end
ruby
def extract_css stylesheets = @dom.css(STYLE_ELEMENT_QUERY).map { |element| stylesheet = read_stylesheet(element) element.remove if stylesheet stylesheet }.compact stylesheets end
[ "def", "extract_css", "stylesheets", "=", "@dom", ".", "css", "(", "STYLE_ELEMENT_QUERY", ")", ".", "map", "{", "|", "element", "|", "stylesheet", "=", "read_stylesheet", "(", "element", ")", "element", ".", "remove", "if", "stylesheet", "stylesheet", "}", ".", "compact", "stylesheets", "end" ]
Looks for all non-ignored stylesheets, removes their references from the DOM and then returns them. This will mutate the DOM tree. The order of the array corresponds with the document order in the DOM. @see #find_css @return [Enumerable<Stylesheet>] every extracted stylesheet
[ "Looks", "for", "all", "non", "-", "ignored", "stylesheets", "removes", "their", "references", "from", "the", "DOM", "and", "then", "returns", "them", "." ]
afda57d66b7653a0978604f1d81cccd93e8748c9
https://github.com/Mange/roadie/blob/afda57d66b7653a0978604f1d81cccd93e8748c9/lib/roadie/asset_scanner.rb#L43-L50
16,189
Mange/roadie
lib/roadie/url_generator.rb
Roadie.UrlGenerator.generate_url
def generate_url(path, base = "/") return root_uri.to_s if path.nil? or path.empty? return path if path_is_anchor?(path) return add_scheme(path) if path_is_schemeless?(path) return path if Utils.path_is_absolute?(path) combine_segments(root_uri, base, path).to_s end
ruby
def generate_url(path, base = "/") return root_uri.to_s if path.nil? or path.empty? return path if path_is_anchor?(path) return add_scheme(path) if path_is_schemeless?(path) return path if Utils.path_is_absolute?(path) combine_segments(root_uri, base, path).to_s end
[ "def", "generate_url", "(", "path", ",", "base", "=", "\"/\"", ")", "return", "root_uri", ".", "to_s", "if", "path", ".", "nil?", "or", "path", ".", "empty?", "return", "path", "if", "path_is_anchor?", "(", "path", ")", "return", "add_scheme", "(", "path", ")", "if", "path_is_schemeless?", "(", "path", ")", "return", "path", "if", "Utils", ".", "path_is_absolute?", "(", "path", ")", "combine_segments", "(", "root_uri", ",", "base", ",", "path", ")", ".", "to_s", "end" ]
Create a new instance with the given URL options. Initializing without a host setting raises an error, as do unknown keys. @param [Hash] url_options @option url_options [String] :host (required) @option url_options [String, Integer] :port @option url_options [String] :path root path @option url_options [String] :scheme URL scheme ("http" is default) @option url_options [String] :protocol alias for :scheme Generate an absolute URL from a relative URL. If the passed path is already an absolute URL or just an anchor reference, it will be returned as-is. If passed a blank path, the "root URL" will be returned. The root URL is the URL that the {#url_options} would generate by themselves. An optional base can be specified. The base is another relative path from the root that specifies an "offset" from which the path was found in. A common use-case is to convert a relative path found in a stylesheet which resides in a subdirectory. @example Normal conversions generator = Roadie::UrlGenerator.new host: "foo.com", scheme: "https" generator.generate_url("bar.html") # => "https://foo.com/bar.html" generator.generate_url("/bar.html") # => "https://foo.com/bar.html" generator.generate_url("") # => "https://foo.com" @example Conversions with a base generator = Roadie::UrlGenerator.new host: "foo.com", scheme: "https" generator.generate_url("../images/logo.png", "/css") # => "https://foo.com/images/logo.png" generator.generate_url("../images/logo.png", "/assets/css") # => "https://foo.com/assets/images/logo.png" @param [String] base The base which the relative path comes from @return [String] an absolute URL
[ "Create", "a", "new", "instance", "with", "the", "given", "URL", "options", "." ]
afda57d66b7653a0978604f1d81cccd93e8748c9
https://github.com/Mange/roadie/blob/afda57d66b7653a0978604f1d81cccd93e8748c9/lib/roadie/url_generator.rb#L58-L65
16,190
Mange/roadie
lib/roadie/inliner.rb
Roadie.Inliner.add_uninlinable_styles
def add_uninlinable_styles(parent, blocks, merge_media_queries) return if blocks.empty? parent_node = case parent when :head find_head when :root dom else raise ArgumentError, "Parent must be either :head or :root. Was #{parent.inspect}" end create_style_element(blocks, parent_node, merge_media_queries) end
ruby
def add_uninlinable_styles(parent, blocks, merge_media_queries) return if blocks.empty? parent_node = case parent when :head find_head when :root dom else raise ArgumentError, "Parent must be either :head or :root. Was #{parent.inspect}" end create_style_element(blocks, parent_node, merge_media_queries) end
[ "def", "add_uninlinable_styles", "(", "parent", ",", "blocks", ",", "merge_media_queries", ")", "return", "if", "blocks", ".", "empty?", "parent_node", "=", "case", "parent", "when", ":head", "find_head", "when", ":root", "dom", "else", "raise", "ArgumentError", ",", "\"Parent must be either :head or :root. Was #{parent.inspect}\"", "end", "create_style_element", "(", "blocks", ",", "parent_node", ",", "merge_media_queries", ")", "end" ]
Adds unlineable styles in the specified part of the document either the head or in the document @param [Symbol] parent Where to put the styles @param [Array<StyleBlock>] blocks Non-inlineable style blocks @param [Boolean] merge_media_queries Whether to group media queries
[ "Adds", "unlineable", "styles", "in", "the", "specified", "part", "of", "the", "document", "either", "the", "head", "or", "in", "the", "document" ]
afda57d66b7653a0978604f1d81cccd93e8748c9
https://github.com/Mange/roadie/blob/afda57d66b7653a0978604f1d81cccd93e8748c9/lib/roadie/inliner.rb#L106-L120
16,191
geminabox/geminabox
lib/geminabox/gem_version_collection.rb
Geminabox.GemVersionCollection.by_name
def by_name(&block) @grouped ||= @gems.group_by(&:name).map{|name, collection| [name, Geminabox::GemVersionCollection.new(collection)] }.sort_by{|name, collection| name.downcase } if block_given? @grouped.each(&block) else @grouped end end
ruby
def by_name(&block) @grouped ||= @gems.group_by(&:name).map{|name, collection| [name, Geminabox::GemVersionCollection.new(collection)] }.sort_by{|name, collection| name.downcase } if block_given? @grouped.each(&block) else @grouped end end
[ "def", "by_name", "(", "&", "block", ")", "@grouped", "||=", "@gems", ".", "group_by", "(", ":name", ")", ".", "map", "{", "|", "name", ",", "collection", "|", "[", "name", ",", "Geminabox", "::", "GemVersionCollection", ".", "new", "(", "collection", ")", "]", "}", ".", "sort_by", "{", "|", "name", ",", "collection", "|", "name", ".", "downcase", "}", "if", "block_given?", "@grouped", ".", "each", "(", "block", ")", "else", "@grouped", "end", "end" ]
The collection can contain gems of different names, this method groups them by name, and then sorts the different version of each name by version and platform. yields 'foo_gem', version_collection
[ "The", "collection", "can", "contain", "gems", "of", "different", "names", "this", "method", "groups", "them", "by", "name", "and", "then", "sorts", "the", "different", "version", "of", "each", "name", "by", "version", "and", "platform", "." ]
13ce5955f4794f2f1272ada66b4d786b81fd0850
https://github.com/geminabox/geminabox/blob/13ce5955f4794f2f1272ada66b4d786b81fd0850/lib/geminabox/gem_version_collection.rb#L41-L53
16,192
chef/knife-azure
lib/azure/service_management/certificate.rb
Azure.Certificate.create_ssl_certificate
def create_ssl_certificate(cert_params) file_path = cert_params[:output_file].sub(/\.(\w+)$/, "") path = prompt_for_file_path file_path = File.join(path, file_path) unless path.empty? cert_params[:domain] = prompt_for_domain rsa_key = generate_keypair cert_params[:key_length] cert = generate_certificate(rsa_key, cert_params) write_certificate_to_file cert, file_path, rsa_key, cert_params puts "*" * 70 puts "Generated Certificates:" puts "- #{file_path}.pfx - PKCS12 format keypair. Contains both the public and private keys, usually used on the server." puts "- #{file_path}.b64 - Base64 encoded PKCS12 keypair. Contains both the public and private keys, for upload to the Azure REST API." puts "- #{file_path}.pem - Base64 encoded public certificate only. Required by the client to connect to the server." puts "Certificate Thumbprint: #{@thumbprint.to_s.upcase}" puts "*" * 70 Chef::Config[:knife][:ca_trust_file] = file_path + ".pem" if Chef::Config[:knife][:ca_trust_file].nil? cert_data = File.read (file_path + ".b64") add_certificate cert_data, @winrm_cert_passphrase, "pfx", cert_params[:azure_dns_name] @thumbprint end
ruby
def create_ssl_certificate(cert_params) file_path = cert_params[:output_file].sub(/\.(\w+)$/, "") path = prompt_for_file_path file_path = File.join(path, file_path) unless path.empty? cert_params[:domain] = prompt_for_domain rsa_key = generate_keypair cert_params[:key_length] cert = generate_certificate(rsa_key, cert_params) write_certificate_to_file cert, file_path, rsa_key, cert_params puts "*" * 70 puts "Generated Certificates:" puts "- #{file_path}.pfx - PKCS12 format keypair. Contains both the public and private keys, usually used on the server." puts "- #{file_path}.b64 - Base64 encoded PKCS12 keypair. Contains both the public and private keys, for upload to the Azure REST API." puts "- #{file_path}.pem - Base64 encoded public certificate only. Required by the client to connect to the server." puts "Certificate Thumbprint: #{@thumbprint.to_s.upcase}" puts "*" * 70 Chef::Config[:knife][:ca_trust_file] = file_path + ".pem" if Chef::Config[:knife][:ca_trust_file].nil? cert_data = File.read (file_path + ".b64") add_certificate cert_data, @winrm_cert_passphrase, "pfx", cert_params[:azure_dns_name] @thumbprint end
[ "def", "create_ssl_certificate", "(", "cert_params", ")", "file_path", "=", "cert_params", "[", ":output_file", "]", ".", "sub", "(", "/", "\\.", "\\w", "/", ",", "\"\"", ")", "path", "=", "prompt_for_file_path", "file_path", "=", "File", ".", "join", "(", "path", ",", "file_path", ")", "unless", "path", ".", "empty?", "cert_params", "[", ":domain", "]", "=", "prompt_for_domain", "rsa_key", "=", "generate_keypair", "cert_params", "[", ":key_length", "]", "cert", "=", "generate_certificate", "(", "rsa_key", ",", "cert_params", ")", "write_certificate_to_file", "cert", ",", "file_path", ",", "rsa_key", ",", "cert_params", "puts", "\"*\"", "*", "70", "puts", "\"Generated Certificates:\"", "puts", "\"- #{file_path}.pfx - PKCS12 format keypair. Contains both the public and private keys, usually used on the server.\"", "puts", "\"- #{file_path}.b64 - Base64 encoded PKCS12 keypair. Contains both the public and private keys, for upload to the Azure REST API.\"", "puts", "\"- #{file_path}.pem - Base64 encoded public certificate only. Required by the client to connect to the server.\"", "puts", "\"Certificate Thumbprint: #{@thumbprint.to_s.upcase}\"", "puts", "\"*\"", "*", "70", "Chef", "::", "Config", "[", ":knife", "]", "[", ":ca_trust_file", "]", "=", "file_path", "+", "\".pem\"", "if", "Chef", "::", "Config", "[", ":knife", "]", "[", ":ca_trust_file", "]", ".", "nil?", "cert_data", "=", "File", ".", "read", "(", "file_path", "+", "\".b64\"", ")", "add_certificate", "cert_data", ",", "@winrm_cert_passphrase", ",", "\"pfx\"", ",", "cert_params", "[", ":azure_dns_name", "]", "@thumbprint", "end" ]
SSL certificate generation for knife-azure ssl bootstrap
[ "SSL", "certificate", "generation", "for", "knife", "-", "azure", "ssl", "bootstrap" ]
2cf998b286cd169478ba547057e6c5ca57217604
https://github.com/chef/knife-azure/blob/2cf998b286cd169478ba547057e6c5ca57217604/lib/azure/service_management/certificate.rb#L128-L149
16,193
chef/knife-azure
lib/azure/service_management/image.rb
Azure.Images.get_images
def get_images(img_type) images = Hash.new if img_type == "OSImage" response = @connection.query_azure("images") elsif img_type == "VMImage" response = @connection.query_azure("vmimages") end unless response.to_s.empty? osimages = response.css(img_type) osimages.each do |image| item = Image.new(image) images[item.name] = item end end images end
ruby
def get_images(img_type) images = Hash.new if img_type == "OSImage" response = @connection.query_azure("images") elsif img_type == "VMImage" response = @connection.query_azure("vmimages") end unless response.to_s.empty? osimages = response.css(img_type) osimages.each do |image| item = Image.new(image) images[item.name] = item end end images end
[ "def", "get_images", "(", "img_type", ")", "images", "=", "Hash", ".", "new", "if", "img_type", "==", "\"OSImage\"", "response", "=", "@connection", ".", "query_azure", "(", "\"images\"", ")", "elsif", "img_type", "==", "\"VMImage\"", "response", "=", "@connection", ".", "query_azure", "(", "\"vmimages\"", ")", "end", "unless", "response", ".", "to_s", ".", "empty?", "osimages", "=", "response", ".", "css", "(", "img_type", ")", "osimages", ".", "each", "do", "|", "image", "|", "item", "=", "Image", ".", "new", "(", "image", ")", "images", "[", "item", ".", "name", "]", "=", "item", "end", "end", "images", "end" ]
img_type = OSImages or VMImage
[ "img_type", "=", "OSImages", "or", "VMImage" ]
2cf998b286cd169478ba547057e6c5ca57217604
https://github.com/chef/knife-azure/blob/2cf998b286cd169478ba547057e6c5ca57217604/lib/azure/service_management/image.rb#L39-L58
16,194
chef/knife-azure
lib/azure/service_management/storageaccount.rb
Azure.StorageAccounts.exists_on_cloud?
def exists_on_cloud?(name) ret_val = @connection.query_azure("storageservices/#{name}") error_code, error_message = error_from_response_xml(ret_val) if ret_val if ret_val.nil? || error_code.length > 0 Chef::Log.warn "Unable to find storage account:" + error_message + " : " + error_message if ret_val false else true end end
ruby
def exists_on_cloud?(name) ret_val = @connection.query_azure("storageservices/#{name}") error_code, error_message = error_from_response_xml(ret_val) if ret_val if ret_val.nil? || error_code.length > 0 Chef::Log.warn "Unable to find storage account:" + error_message + " : " + error_message if ret_val false else true end end
[ "def", "exists_on_cloud?", "(", "name", ")", "ret_val", "=", "@connection", ".", "query_azure", "(", "\"storageservices/#{name}\"", ")", "error_code", ",", "error_message", "=", "error_from_response_xml", "(", "ret_val", ")", "if", "ret_val", "if", "ret_val", ".", "nil?", "||", "error_code", ".", "length", ">", "0", "Chef", "::", "Log", ".", "warn", "\"Unable to find storage account:\"", "+", "error_message", "+", "\" : \"", "+", "error_message", "if", "ret_val", "false", "else", "true", "end", "end" ]
Look up on cloud and not local cache
[ "Look", "up", "on", "cloud", "and", "not", "local", "cache" ]
2cf998b286cd169478ba547057e6c5ca57217604
https://github.com/chef/knife-azure/blob/2cf998b286cd169478ba547057e6c5ca57217604/lib/azure/service_management/storageaccount.rb#L55-L64
16,195
chef/knife-azure
lib/azure/resource_management/vnet_config.rb
Azure::ARM.VnetConfig.subnets_list_for_specific_address_space
def subnets_list_for_specific_address_space(address_prefix, subnets_list) list = [] address_space = IPAddress(address_prefix) subnets_list.each do |sbn| subnet_address_prefix = IPAddress(sbn.address_prefix) ## check if the subnet belongs to this address space or not ## list << sbn if address_space.include? subnet_address_prefix end list end
ruby
def subnets_list_for_specific_address_space(address_prefix, subnets_list) list = [] address_space = IPAddress(address_prefix) subnets_list.each do |sbn| subnet_address_prefix = IPAddress(sbn.address_prefix) ## check if the subnet belongs to this address space or not ## list << sbn if address_space.include? subnet_address_prefix end list end
[ "def", "subnets_list_for_specific_address_space", "(", "address_prefix", ",", "subnets_list", ")", "list", "=", "[", "]", "address_space", "=", "IPAddress", "(", "address_prefix", ")", "subnets_list", ".", "each", "do", "|", "sbn", "|", "subnet_address_prefix", "=", "IPAddress", "(", "sbn", ".", "address_prefix", ")", "## check if the subnet belongs to this address space or not ##", "list", "<<", "sbn", "if", "address_space", ".", "include?", "subnet_address_prefix", "end", "list", "end" ]
lists subnets of only a specific virtual network address space
[ "lists", "subnets", "of", "only", "a", "specific", "virtual", "network", "address", "space" ]
2cf998b286cd169478ba547057e6c5ca57217604
https://github.com/chef/knife-azure/blob/2cf998b286cd169478ba547057e6c5ca57217604/lib/azure/resource_management/vnet_config.rb#L26-L37
16,196
chef/knife-azure
lib/azure/resource_management/vnet_config.rb
Azure::ARM.VnetConfig.subnets_list
def subnets_list(resource_group_name, vnet_name, address_prefix = nil) list = network_resource_client.subnets.list(resource_group_name, vnet_name) !address_prefix.nil? && !list.empty? ? subnets_list_for_specific_address_space(address_prefix, list) : list end
ruby
def subnets_list(resource_group_name, vnet_name, address_prefix = nil) list = network_resource_client.subnets.list(resource_group_name, vnet_name) !address_prefix.nil? && !list.empty? ? subnets_list_for_specific_address_space(address_prefix, list) : list end
[ "def", "subnets_list", "(", "resource_group_name", ",", "vnet_name", ",", "address_prefix", "=", "nil", ")", "list", "=", "network_resource_client", ".", "subnets", ".", "list", "(", "resource_group_name", ",", "vnet_name", ")", "!", "address_prefix", ".", "nil?", "&&", "!", "list", ".", "empty?", "?", "subnets_list_for_specific_address_space", "(", "address_prefix", ",", "list", ")", ":", "list", "end" ]
lists all subnets under a virtual network or lists subnets of only a particular address space
[ "lists", "all", "subnets", "under", "a", "virtual", "network", "or", "lists", "subnets", "of", "only", "a", "particular", "address", "space" ]
2cf998b286cd169478ba547057e6c5ca57217604
https://github.com/chef/knife-azure/blob/2cf998b286cd169478ba547057e6c5ca57217604/lib/azure/resource_management/vnet_config.rb#L53-L56
16,197
chef/knife-azure
lib/azure/resource_management/vnet_config.rb
Azure::ARM.VnetConfig.sort_available_networks
def sort_available_networks(available_networks) available_networks.sort_by { |nwrk| nwrk.network.address.split(".").map(&:to_i) } end
ruby
def sort_available_networks(available_networks) available_networks.sort_by { |nwrk| nwrk.network.address.split(".").map(&:to_i) } end
[ "def", "sort_available_networks", "(", "available_networks", ")", "available_networks", ".", "sort_by", "{", "|", "nwrk", "|", "nwrk", ".", "network", ".", "address", ".", "split", "(", "\".\"", ")", ".", "map", "(", ":to_i", ")", "}", "end" ]
sort available networks pool in ascending order based on the network's IP address to allocate the network for the new subnet to be added in the existing virtual network
[ "sort", "available", "networks", "pool", "in", "ascending", "order", "based", "on", "the", "network", "s", "IP", "address", "to", "allocate", "the", "network", "for", "the", "new", "subnet", "to", "be", "added", "in", "the", "existing", "virtual", "network" ]
2cf998b286cd169478ba547057e6c5ca57217604
https://github.com/chef/knife-azure/blob/2cf998b286cd169478ba547057e6c5ca57217604/lib/azure/resource_management/vnet_config.rb#L81-L83
16,198
chef/knife-azure
lib/azure/resource_management/vnet_config.rb
Azure::ARM.VnetConfig.sort_subnets_by_cidr_prefix
def sort_subnets_by_cidr_prefix(subnets) subnets.sort_by.with_index { |sbn, i| [subnet_address_prefix(sbn).split("/")[1].to_i, i] } end
ruby
def sort_subnets_by_cidr_prefix(subnets) subnets.sort_by.with_index { |sbn, i| [subnet_address_prefix(sbn).split("/")[1].to_i, i] } end
[ "def", "sort_subnets_by_cidr_prefix", "(", "subnets", ")", "subnets", ".", "sort_by", ".", "with_index", "{", "|", "sbn", ",", "i", "|", "[", "subnet_address_prefix", "(", "sbn", ")", ".", "split", "(", "\"/\"", ")", "[", "1", "]", ".", "to_i", ",", "i", "]", "}", "end" ]
sort existing subnets in ascending order based on their cidr prefix or netmask to have subnets with larger networks on the top
[ "sort", "existing", "subnets", "in", "ascending", "order", "based", "on", "their", "cidr", "prefix", "or", "netmask", "to", "have", "subnets", "with", "larger", "networks", "on", "the", "top" ]
2cf998b286cd169478ba547057e6c5ca57217604
https://github.com/chef/knife-azure/blob/2cf998b286cd169478ba547057e6c5ca57217604/lib/azure/resource_management/vnet_config.rb#L87-L89
16,199
chef/knife-azure
lib/azure/resource_management/vnet_config.rb
Azure::ARM.VnetConfig.sort_used_networks_by_hosts_size
def sort_used_networks_by_hosts_size(used_network) used_network.sort_by.with_index { |nwrk, i| [-nwrk.hosts.size, i] } end
ruby
def sort_used_networks_by_hosts_size(used_network) used_network.sort_by.with_index { |nwrk, i| [-nwrk.hosts.size, i] } end
[ "def", "sort_used_networks_by_hosts_size", "(", "used_network", ")", "used_network", ".", "sort_by", ".", "with_index", "{", "|", "nwrk", ",", "i", "|", "[", "-", "nwrk", ".", "hosts", ".", "size", ",", "i", "]", "}", "end" ]
sort used networks pool in descending order based on the number of hosts it contains, this helps to keep larger networks on top thereby eliminating more number of entries in available_networks_pool at a faster pace
[ "sort", "used", "networks", "pool", "in", "descending", "order", "based", "on", "the", "number", "of", "hosts", "it", "contains", "this", "helps", "to", "keep", "larger", "networks", "on", "top", "thereby", "eliminating", "more", "number", "of", "entries", "in", "available_networks_pool", "at", "a", "faster", "pace" ]
2cf998b286cd169478ba547057e6c5ca57217604
https://github.com/chef/knife-azure/blob/2cf998b286cd169478ba547057e6c5ca57217604/lib/azure/resource_management/vnet_config.rb#L94-L96