repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
thechrisoshow/rtf | lib/rtf/node.rb | RTF.CommandNode.bold | def bold
style = CharacterStyle.new
style.bold = true
if block_given?
apply(style) {|node| yield node}
else
apply(style)
end
end | ruby | def bold
style = CharacterStyle.new
style.bold = true
if block_given?
apply(style) {|node| yield node}
else
apply(style)
end
end | [
"def",
"bold",
"style",
"=",
"CharacterStyle",
".",
"new",
"style",
".",
"bold",
"=",
"true",
"if",
"block_given?",
"apply",
"(",
"style",
")",
"{",
"|",
"node",
"|",
"yield",
"node",
"}",
"else",
"apply",
"(",
"style",
")",
"end",
"end"
] | This method provides a short cut means of creating a bold command node.
The method accepts a block that will be passed a single parameter which
will be a reference to the bold node created. After the block is
complete the bold node is appended to the end of the child nodes on
the object that the method is call against. | [
"This",
"method",
"provides",
"a",
"short",
"cut",
"means",
"of",
"creating",
"a",
"bold",
"command",
"node",
".",
"The",
"method",
"accepts",
"a",
"block",
"that",
"will",
"be",
"passed",
"a",
"single",
"parameter",
"which",
"will",
"be",
"a",
"reference"... | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L396-L404 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.CommandNode.italic | def italic
style = CharacterStyle.new
style.italic = true
if block_given?
apply(style) {|node| yield node}
else
apply(style)
end
end | ruby | def italic
style = CharacterStyle.new
style.italic = true
if block_given?
apply(style) {|node| yield node}
else
apply(style)
end
end | [
"def",
"italic",
"style",
"=",
"CharacterStyle",
".",
"new",
"style",
".",
"italic",
"=",
"true",
"if",
"block_given?",
"apply",
"(",
"style",
")",
"{",
"|",
"node",
"|",
"yield",
"node",
"}",
"else",
"apply",
"(",
"style",
")",
"end",
"end"
] | This method provides a short cut means of creating an italic command
node. The method accepts a block that will be passed a single parameter
which will be a reference to the italic node created. After the block is
complete the italic node is appended to the end of the child nodes on
the object that the method is call against. | [
"This",
"method",
"provides",
"a",
"short",
"cut",
"means",
"of",
"creating",
"an",
"italic",
"command",
"node",
".",
"The",
"method",
"accepts",
"a",
"block",
"that",
"will",
"be",
"passed",
"a",
"single",
"parameter",
"which",
"will",
"be",
"a",
"referen... | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L411-L419 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.CommandNode.underline | def underline
style = CharacterStyle.new
style.underline = true
if block_given?
apply(style) {|node| yield node}
else
apply(style)
end
end | ruby | def underline
style = CharacterStyle.new
style.underline = true
if block_given?
apply(style) {|node| yield node}
else
apply(style)
end
end | [
"def",
"underline",
"style",
"=",
"CharacterStyle",
".",
"new",
"style",
".",
"underline",
"=",
"true",
"if",
"block_given?",
"apply",
"(",
"style",
")",
"{",
"|",
"node",
"|",
"yield",
"node",
"}",
"else",
"apply",
"(",
"style",
")",
"end",
"end"
] | This method provides a short cut means of creating an underline command
node. The method accepts a block that will be passed a single parameter
which will be a reference to the underline node created. After the block
is complete the underline node is appended to the end of the child nodes
on the object that the method is call against. | [
"This",
"method",
"provides",
"a",
"short",
"cut",
"means",
"of",
"creating",
"an",
"underline",
"command",
"node",
".",
"The",
"method",
"accepts",
"a",
"block",
"that",
"will",
"be",
"passed",
"a",
"single",
"parameter",
"which",
"will",
"be",
"a",
"refe... | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L426-L434 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.CommandNode.subscript | def subscript
style = CharacterStyle.new
style.subscript = true
if block_given?
apply(style) {|node| yield node}
else
apply(style)
end
end | ruby | def subscript
style = CharacterStyle.new
style.subscript = true
if block_given?
apply(style) {|node| yield node}
else
apply(style)
end
end | [
"def",
"subscript",
"style",
"=",
"CharacterStyle",
".",
"new",
"style",
".",
"subscript",
"=",
"true",
"if",
"block_given?",
"apply",
"(",
"style",
")",
"{",
"|",
"node",
"|",
"yield",
"node",
"}",
"else",
"apply",
"(",
"style",
")",
"end",
"end"
] | This method provides a short cut means of creating a subscript command
node. The method accepts a block that will be passed a single parameter
which will be a reference to the subscript node created. After the
block is complete the subscript node is appended to the end of the
child nodes on the object that the method is call against. | [
"This",
"method",
"provides",
"a",
"short",
"cut",
"means",
"of",
"creating",
"a",
"subscript",
"command",
"node",
".",
"The",
"method",
"accepts",
"a",
"block",
"that",
"will",
"be",
"passed",
"a",
"single",
"parameter",
"which",
"will",
"be",
"a",
"refer... | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L441-L449 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.CommandNode.superscript | def superscript
style = CharacterStyle.new
style.superscript = true
if block_given?
apply(style) {|node| yield node}
else
apply(style)
end
end | ruby | def superscript
style = CharacterStyle.new
style.superscript = true
if block_given?
apply(style) {|node| yield node}
else
apply(style)
end
end | [
"def",
"superscript",
"style",
"=",
"CharacterStyle",
".",
"new",
"style",
".",
"superscript",
"=",
"true",
"if",
"block_given?",
"apply",
"(",
"style",
")",
"{",
"|",
"node",
"|",
"yield",
"node",
"}",
"else",
"apply",
"(",
"style",
")",
"end",
"end"
] | This method provides a short cut means of creating a superscript command
node. The method accepts a block that will be passed a single parameter
which will be a reference to the superscript node created. After the
block is complete the superscript node is appended to the end of the
child nodes on the object that the method is call against. | [
"This",
"method",
"provides",
"a",
"short",
"cut",
"means",
"of",
"creating",
"a",
"superscript",
"command",
"node",
".",
"The",
"method",
"accepts",
"a",
"block",
"that",
"will",
"be",
"passed",
"a",
"single",
"parameter",
"which",
"will",
"be",
"a",
"ref... | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L456-L464 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.CommandNode.strike | def strike
style = CharacterStyle.new
style.strike = true
if block_given?
apply(style) {|node| yield node}
else
apply(style)
end
end | ruby | def strike
style = CharacterStyle.new
style.strike = true
if block_given?
apply(style) {|node| yield node}
else
apply(style)
end
end | [
"def",
"strike",
"style",
"=",
"CharacterStyle",
".",
"new",
"style",
".",
"strike",
"=",
"true",
"if",
"block_given?",
"apply",
"(",
"style",
")",
"{",
"|",
"node",
"|",
"yield",
"node",
"}",
"else",
"apply",
"(",
"style",
")",
"end",
"end"
] | This method provides a short cut means of creating a strike command
node. The method accepts a block that will be passed a single parameter
which will be a reference to the strike node created. After the
block is complete the strike node is appended to the end of the
child nodes on the object that the method is call against. | [
"This",
"method",
"provides",
"a",
"short",
"cut",
"means",
"of",
"creating",
"a",
"strike",
"command",
"node",
".",
"The",
"method",
"accepts",
"a",
"block",
"that",
"will",
"be",
"passed",
"a",
"single",
"parameter",
"which",
"will",
"be",
"a",
"referenc... | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L471-L479 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.CommandNode.font | def font(font, size=nil)
style = CharacterStyle.new
style.font = font
style.font_size = size
root.fonts << font
if block_given?
apply(style) {|node| yield node}
else
apply(style)
end
end | ruby | def font(font, size=nil)
style = CharacterStyle.new
style.font = font
style.font_size = size
root.fonts << font
if block_given?
apply(style) {|node| yield node}
else
apply(style)
end
end | [
"def",
"font",
"(",
"font",
",",
"size",
"=",
"nil",
")",
"style",
"=",
"CharacterStyle",
".",
"new",
"style",
".",
"font",
"=",
"font",
"style",
".",
"font_size",
"=",
"size",
"root",
".",
"fonts",
"<<",
"font",
"if",
"block_given?",
"apply",
"(",
"... | This method provides a short cut means of creating a font command node.
The method accepts a block that will be passed a single parameter which
will be a reference to the font node created. After the block is
complete the font node is appended to the end of the child nodes on the
object that the method is called against.
==== Parameters
font:: A reference to font object that represents the font to be used
within the node.
size:: An integer size setting for the font. Defaults to nil to
indicate that the current font size should be used. | [
"This",
"method",
"provides",
"a",
"short",
"cut",
"means",
"of",
"creating",
"a",
"font",
"command",
"node",
".",
"The",
"method",
"accepts",
"a",
"block",
"that",
"will",
"be",
"passed",
"a",
"single",
"parameter",
"which",
"will",
"be",
"a",
"reference"... | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L492-L502 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.CommandNode.foreground | def foreground(colour)
style = CharacterStyle.new
style.foreground = colour
root.colours << colour
if block_given?
apply(style) {|node| yield node}
else
apply(style)
end
end | ruby | def foreground(colour)
style = CharacterStyle.new
style.foreground = colour
root.colours << colour
if block_given?
apply(style) {|node| yield node}
else
apply(style)
end
end | [
"def",
"foreground",
"(",
"colour",
")",
"style",
"=",
"CharacterStyle",
".",
"new",
"style",
".",
"foreground",
"=",
"colour",
"root",
".",
"colours",
"<<",
"colour",
"if",
"block_given?",
"apply",
"(",
"style",
")",
"{",
"|",
"node",
"|",
"yield",
"nod... | This method provides a short cut means of creating a foreground colour
command node. The method accepts a block that will be passed a single
parameter which will be a reference to the foreground colour node
created. After the block is complete the foreground colour node is
appended to the end of the child nodes on the object that the method
is called against.
==== Parameters
colour:: The foreground colour to be applied by the command. | [
"This",
"method",
"provides",
"a",
"short",
"cut",
"means",
"of",
"creating",
"a",
"foreground",
"colour",
"command",
"node",
".",
"The",
"method",
"accepts",
"a",
"block",
"that",
"will",
"be",
"passed",
"a",
"single",
"parameter",
"which",
"will",
"be",
... | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L513-L522 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.CommandNode.colour | def colour(fore, back)
style = CharacterStyle.new
style.foreground = fore
style.background = back
root.colours << fore
root.colours << back
if block_given?
apply(style) {|node| yield node}
else
apply(style)
end
end | ruby | def colour(fore, back)
style = CharacterStyle.new
style.foreground = fore
style.background = back
root.colours << fore
root.colours << back
if block_given?
apply(style) {|node| yield node}
else
apply(style)
end
end | [
"def",
"colour",
"(",
"fore",
",",
"back",
")",
"style",
"=",
"CharacterStyle",
".",
"new",
"style",
".",
"foreground",
"=",
"fore",
"style",
".",
"background",
"=",
"back",
"root",
".",
"colours",
"<<",
"fore",
"root",
".",
"colours",
"<<",
"back",
"i... | This method provides a short cut menas of creating a colour node that
deals with foreground and background colours. The method accepts a
block that will be passed a single parameter which will be a reference
to the colour node created. After the block is complete the colour node
is append to the end of the child nodes on the object that the method
is called against.
==== Parameters
fore:: The foreground colour to be applied by the command.
back:: The background colour to be applied by the command. | [
"This",
"method",
"provides",
"a",
"short",
"cut",
"menas",
"of",
"creating",
"a",
"colour",
"node",
"that",
"deals",
"with",
"foreground",
"and",
"background",
"colours",
".",
"The",
"method",
"accepts",
"a",
"block",
"that",
"will",
"be",
"passed",
"a",
... | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L554-L565 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.CommandNode.table | def table(rows, columns, *widths)
node = TableNode.new(self, rows, columns, *widths)
yield node if block_given?
store(node)
node
end | ruby | def table(rows, columns, *widths)
node = TableNode.new(self, rows, columns, *widths)
yield node if block_given?
store(node)
node
end | [
"def",
"table",
"(",
"rows",
",",
"columns",
",",
"*",
"widths",
")",
"node",
"=",
"TableNode",
".",
"new",
"(",
"self",
",",
"rows",
",",
"columns",
",",
"*",
"widths",
")",
"yield",
"node",
"if",
"block_given?",
"store",
"(",
"node",
")",
"node",
... | This method creates a new table node and returns it. The method accepts
a block that will be passed the table as a parameter. The node is added
to the node the method is called upon after the block is complete.
==== Parameters
rows:: The number of rows that the table contains.
columns:: The number of columns that the table contains.
*widths:: One or more integers representing the widths for the table
columns. | [
"This",
"method",
"creates",
"a",
"new",
"table",
"node",
"and",
"returns",
"it",
".",
"The",
"method",
"accepts",
"a",
"block",
"that",
"will",
"be",
"passed",
"the",
"table",
"as",
"a",
"parameter",
".",
"The",
"node",
"is",
"added",
"to",
"the",
"no... | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L576-L581 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.ListLevelNode.list | def list(kind=@kind)
node = ListLevelNode.new(self, @template, kind, @level.level+1)
yield node
self.store(node)
end | ruby | def list(kind=@kind)
node = ListLevelNode.new(self, @template, kind, @level.level+1)
yield node
self.store(node)
end | [
"def",
"list",
"(",
"kind",
"=",
"@kind",
")",
"node",
"=",
"ListLevelNode",
".",
"new",
"(",
"self",
",",
"@template",
",",
"kind",
",",
"@level",
".",
"level",
"+",
"1",
")",
"yield",
"node",
"self",
".",
"store",
"(",
"node",
")",
"end"
] | Creates a new +ListLevelNode+ to implement nested lists | [
"Creates",
"a",
"new",
"+",
"ListLevelNode",
"+",
"to",
"implement",
"nested",
"lists"
] | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L664-L668 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.TableNode.column_shading_colour | def column_shading_colour(index, colour)
self.each do |row|
cell = row[index]
cell.shading_colour = colour if cell != nil
end
end | ruby | def column_shading_colour(index, colour)
self.each do |row|
cell = row[index]
cell.shading_colour = colour if cell != nil
end
end | [
"def",
"column_shading_colour",
"(",
"index",
",",
"colour",
")",
"self",
".",
"each",
"do",
"|",
"row",
"|",
"cell",
"=",
"row",
"[",
"index",
"]",
"cell",
".",
"shading_colour",
"=",
"colour",
"if",
"cell",
"!=",
"nil",
"end",
"end"
] | This method assigns a shading colour to a specified column within a
TableNode object.
==== Parameters
index:: The offset from the first column of the column to have shading
applied to it.
colour:: A reference to a Colour object representing the shading colour
to be used. Set to nil to clear shading. | [
"This",
"method",
"assigns",
"a",
"shading",
"colour",
"to",
"a",
"specified",
"column",
"within",
"a",
"TableNode",
"object",
"."
] | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L776-L781 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.TableNode.shading_colour | def shading_colour(colour)
if block_given?
0.upto(self.size - 1) do |x|
row = self[x]
0.upto(row.size - 1) do |y|
apply = yield row[y], x, y
row[y].shading_colour = colour if apply
end
end
end
end | ruby | def shading_colour(colour)
if block_given?
0.upto(self.size - 1) do |x|
row = self[x]
0.upto(row.size - 1) do |y|
apply = yield row[y], x, y
row[y].shading_colour = colour if apply
end
end
end
end | [
"def",
"shading_colour",
"(",
"colour",
")",
"if",
"block_given?",
"0",
".",
"upto",
"(",
"self",
".",
"size",
"-",
"1",
")",
"do",
"|",
"x",
"|",
"row",
"=",
"self",
"[",
"x",
"]",
"0",
".",
"upto",
"(",
"row",
".",
"size",
"-",
"1",
")",
"d... | This method provides a means of assigning a shading colour to a
selection of cells within a table. The method accepts a block that
takes three parameters - a TableCellNode representing a cell within the
table, an integer representing the x offset of the cell and an integer
representing the y offset of the cell. If the block returns true then
shading will be applied to the cell.
==== Parameters
colour:: A reference to a Colour object representing the shading colour
to be applied. Set to nil to remove shading. | [
"This",
"method",
"provides",
"a",
"means",
"of",
"assigning",
"a",
"shading",
"colour",
"to",
"a",
"selection",
"of",
"cells",
"within",
"a",
"table",
".",
"The",
"method",
"accepts",
"a",
"block",
"that",
"takes",
"three",
"parameters",
"-",
"a",
"TableC... | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L793-L803 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.TableRowNode.to_rtf | def to_rtf
text = StringIO.new
temp = StringIO.new
offset = 0
text << "\\trowd\\tgraph#{parent.cell_margin}"
self.each do |entry|
widths = entry.border_widths
colour = entry.shading_colour
text << "\n"
text << "\\clbrdrt\\brdrw#{widths[0]}\\brdrs" if widths[0] != 0
text << "\\clbrdrl\\brdrw#{widths[3]}\\brdrs" if widths[3] != 0
text << "\\clbrdrb\\brdrw#{widths[2]}\\brdrs" if widths[2] != 0
text << "\\clbrdrr\\brdrw#{widths[1]}\\brdrs" if widths[1] != 0
text << "\\clcbpat#{root.colours.index(colour)}" if colour != nil
text << "\\cellx#{entry.width + offset}"
temp << "\n#{entry.to_rtf}"
offset += entry.width
end
text << "#{temp.string}\n\\row"
text.string
end | ruby | def to_rtf
text = StringIO.new
temp = StringIO.new
offset = 0
text << "\\trowd\\tgraph#{parent.cell_margin}"
self.each do |entry|
widths = entry.border_widths
colour = entry.shading_colour
text << "\n"
text << "\\clbrdrt\\brdrw#{widths[0]}\\brdrs" if widths[0] != 0
text << "\\clbrdrl\\brdrw#{widths[3]}\\brdrs" if widths[3] != 0
text << "\\clbrdrb\\brdrw#{widths[2]}\\brdrs" if widths[2] != 0
text << "\\clbrdrr\\brdrw#{widths[1]}\\brdrs" if widths[1] != 0
text << "\\clcbpat#{root.colours.index(colour)}" if colour != nil
text << "\\cellx#{entry.width + offset}"
temp << "\n#{entry.to_rtf}"
offset += entry.width
end
text << "#{temp.string}\n\\row"
text.string
end | [
"def",
"to_rtf",
"text",
"=",
"StringIO",
".",
"new",
"temp",
"=",
"StringIO",
".",
"new",
"offset",
"=",
"0",
"text",
"<<",
"\"\\\\trowd\\\\tgraph#{parent.cell_margin}\"",
"self",
".",
"each",
"do",
"|",
"entry",
"|",
"widths",
"=",
"entry",
".",
"border_wi... | This method overloads the store method inherited from the ContainerNode
class to forbid addition of further nodes.
==== Parameters
node:: A reference to the node to be added.
def store(node)
RTFError.fire("Table row nodes cannot have nodes added to.")
end
This method generates the RTF document text for a TableCellNode object. | [
"This",
"method",
"overloads",
"the",
"store",
"method",
"inherited",
"from",
"the",
"ContainerNode",
"class",
"to",
"forbid",
"addition",
"of",
"further",
"nodes",
"."
] | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L902-L925 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.TableCellNode.border_width= | def border_width=(width)
size = width.nil? ? 0 : width
if size > 0
@borders[TOP] = @borders[RIGHT] = @borders[BOTTOM] = @borders[LEFT] = size.to_i
else
@borders = [nil, nil, nil, nil]
end
end | ruby | def border_width=(width)
size = width.nil? ? 0 : width
if size > 0
@borders[TOP] = @borders[RIGHT] = @borders[BOTTOM] = @borders[LEFT] = size.to_i
else
@borders = [nil, nil, nil, nil]
end
end | [
"def",
"border_width",
"=",
"(",
"width",
")",
"size",
"=",
"width",
".",
"nil?",
"?",
"0",
":",
"width",
"if",
"size",
">",
"0",
"@borders",
"[",
"TOP",
"]",
"=",
"@borders",
"[",
"RIGHT",
"]",
"=",
"@borders",
"[",
"BOTTOM",
"]",
"=",
"@borders",... | This method assigns a width, in twips, for the borders on all sides of
the cell. Negative widths will be ignored and a width of zero will
switch the border off.
==== Parameters
width:: The setting for the width of the border. | [
"This",
"method",
"assigns",
"a",
"width",
"in",
"twips",
"for",
"the",
"borders",
"on",
"all",
"sides",
"of",
"the",
"cell",
".",
"Negative",
"widths",
"will",
"be",
"ignored",
"and",
"a",
"width",
"of",
"zero",
"will",
"switch",
"the",
"border",
"off",... | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1005-L1012 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.TableCellNode.top_border_width= | def top_border_width=(width)
size = width.nil? ? 0 : width
if size > 0
@borders[TOP] = size.to_i
else
@borders[TOP] = nil
end
end | ruby | def top_border_width=(width)
size = width.nil? ? 0 : width
if size > 0
@borders[TOP] = size.to_i
else
@borders[TOP] = nil
end
end | [
"def",
"top_border_width",
"=",
"(",
"width",
")",
"size",
"=",
"width",
".",
"nil?",
"?",
"0",
":",
"width",
"if",
"size",
">",
"0",
"@borders",
"[",
"TOP",
"]",
"=",
"size",
".",
"to_i",
"else",
"@borders",
"[",
"TOP",
"]",
"=",
"nil",
"end",
"... | This method assigns a border width to the top side of a table cell.
Negative values are ignored and a value of 0 switches the border off.
==== Parameters
width:: The new border width setting. | [
"This",
"method",
"assigns",
"a",
"border",
"width",
"to",
"the",
"top",
"side",
"of",
"a",
"table",
"cell",
".",
"Negative",
"values",
"are",
"ignored",
"and",
"a",
"value",
"of",
"0",
"switches",
"the",
"border",
"off",
"."
] | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1019-L1026 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.TableCellNode.right_border_width= | def right_border_width=(width)
size = width.nil? ? 0 : width
if size > 0
@borders[RIGHT] = size.to_i
else
@borders[RIGHT] = nil
end
end | ruby | def right_border_width=(width)
size = width.nil? ? 0 : width
if size > 0
@borders[RIGHT] = size.to_i
else
@borders[RIGHT] = nil
end
end | [
"def",
"right_border_width",
"=",
"(",
"width",
")",
"size",
"=",
"width",
".",
"nil?",
"?",
"0",
":",
"width",
"if",
"size",
">",
"0",
"@borders",
"[",
"RIGHT",
"]",
"=",
"size",
".",
"to_i",
"else",
"@borders",
"[",
"RIGHT",
"]",
"=",
"nil",
"end... | This method assigns a border width to the right side of a table cell.
Negative values are ignored and a value of 0 switches the border off.
==== Parameters
width:: The new border width setting. | [
"This",
"method",
"assigns",
"a",
"border",
"width",
"to",
"the",
"right",
"side",
"of",
"a",
"table",
"cell",
".",
"Negative",
"values",
"are",
"ignored",
"and",
"a",
"value",
"of",
"0",
"switches",
"the",
"border",
"off",
"."
] | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1033-L1040 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.TableCellNode.bottom_border_width= | def bottom_border_width=(width)
size = width.nil? ? 0 : width
if size > 0
@borders[BOTTOM] = size.to_i
else
@borders[BOTTOM] = nil
end
end | ruby | def bottom_border_width=(width)
size = width.nil? ? 0 : width
if size > 0
@borders[BOTTOM] = size.to_i
else
@borders[BOTTOM] = nil
end
end | [
"def",
"bottom_border_width",
"=",
"(",
"width",
")",
"size",
"=",
"width",
".",
"nil?",
"?",
"0",
":",
"width",
"if",
"size",
">",
"0",
"@borders",
"[",
"BOTTOM",
"]",
"=",
"size",
".",
"to_i",
"else",
"@borders",
"[",
"BOTTOM",
"]",
"=",
"nil",
"... | This method assigns a border width to the bottom side of a table cell.
Negative values are ignored and a value of 0 switches the border off.
==== Parameters
width:: The new border width setting. | [
"This",
"method",
"assigns",
"a",
"border",
"width",
"to",
"the",
"bottom",
"side",
"of",
"a",
"table",
"cell",
".",
"Negative",
"values",
"are",
"ignored",
"and",
"a",
"value",
"of",
"0",
"switches",
"the",
"border",
"off",
"."
] | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1047-L1054 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.TableCellNode.left_border_width= | def left_border_width=(width)
size = width.nil? ? 0 : width
if size > 0
@borders[LEFT] = size.to_i
else
@borders[LEFT] = nil
end
end | ruby | def left_border_width=(width)
size = width.nil? ? 0 : width
if size > 0
@borders[LEFT] = size.to_i
else
@borders[LEFT] = nil
end
end | [
"def",
"left_border_width",
"=",
"(",
"width",
")",
"size",
"=",
"width",
".",
"nil?",
"?",
"0",
":",
"width",
"if",
"size",
">",
"0",
"@borders",
"[",
"LEFT",
"]",
"=",
"size",
".",
"to_i",
"else",
"@borders",
"[",
"LEFT",
"]",
"=",
"nil",
"end",
... | This method assigns a border width to the left side of a table cell.
Negative values are ignored and a value of 0 switches the border off.
==== Parameters
width:: The new border width setting. | [
"This",
"method",
"assigns",
"a",
"border",
"width",
"to",
"the",
"left",
"side",
"of",
"a",
"table",
"cell",
".",
"Negative",
"values",
"are",
"ignored",
"and",
"a",
"value",
"of",
"0",
"switches",
"the",
"border",
"off",
"."
] | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1061-L1068 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.TableCellNode.border_widths | def border_widths
widths = []
@borders.each {|entry| widths.push(entry.nil? ? 0 : entry)}
widths
end | ruby | def border_widths
widths = []
@borders.each {|entry| widths.push(entry.nil? ? 0 : entry)}
widths
end | [
"def",
"border_widths",
"widths",
"=",
"[",
"]",
"@borders",
".",
"each",
"{",
"|",
"entry",
"|",
"widths",
".",
"push",
"(",
"entry",
".",
"nil?",
"?",
"0",
":",
"entry",
")",
"}",
"widths",
"end"
] | This method retrieves an array with the cell border width settings.
The values are inserted in top, right, bottom, left order. | [
"This",
"method",
"retrieves",
"an",
"array",
"with",
"the",
"cell",
"border",
"width",
"settings",
".",
"The",
"values",
"are",
"inserted",
"in",
"top",
"right",
"bottom",
"left",
"order",
"."
] | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1083-L1087 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.ImageNode.get_file_type | def get_file_type
type = nil
read = []
open_file do |file|
# Check if the file is a JPEG.
read_source(file, read, 2)
if read[0,2] == [255, 216]
type = JPEG
else
# Check if it's a PNG.
read_source(file, read, 6)
if read[0,8] == [137, 80, 78, 71, 13, 10, 26, 10]
type = PNG
else
# Check if its a bitmap.
if read[0,2] == [66, 77]
size = to_integer(read[2,4])
type = BITMAP if size == File.size(@source)
end
end
end
end
type
end | ruby | def get_file_type
type = nil
read = []
open_file do |file|
# Check if the file is a JPEG.
read_source(file, read, 2)
if read[0,2] == [255, 216]
type = JPEG
else
# Check if it's a PNG.
read_source(file, read, 6)
if read[0,8] == [137, 80, 78, 71, 13, 10, 26, 10]
type = PNG
else
# Check if its a bitmap.
if read[0,2] == [66, 77]
size = to_integer(read[2,4])
type = BITMAP if size == File.size(@source)
end
end
end
end
type
end | [
"def",
"get_file_type",
"type",
"=",
"nil",
"read",
"=",
"[",
"]",
"open_file",
"do",
"|",
"file",
"|",
"read_source",
"(",
"file",
",",
"read",
",",
"2",
")",
"if",
"read",
"[",
"0",
",",
"2",
"]",
"==",
"[",
"255",
",",
"216",
"]",
"type",
"=... | This method attempts to determine the image type associated with a
file, returning nil if it fails to make the determination. | [
"This",
"method",
"attempts",
"to",
"determine",
"the",
"image",
"type",
"associated",
"with",
"a",
"file",
"returning",
"nil",
"if",
"it",
"fails",
"to",
"make",
"the",
"determination",
"."
] | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1345-L1371 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.ImageNode.to_rtf | def to_rtf
text = StringIO.new
count = 0
#text << '{\pard{\*\shppict{\pict'
text << '{\*\shppict{\pict'
text << "\\picscalex#{@x_scaling}" if @x_scaling != nil
text << "\\picscaley#{@y_scaling}" if @y_scaling != nil
text << "\\piccropl#{@left_crop}" if @left_crop != nil
text << "\\piccropr#{@right_crop}" if @right_crop != nil
text << "\\piccropt#{@top_crop}" if @top_crop != nil
text << "\\piccropb#{@bottom_crop}" if @bottom_crop != nil
text << "\\picwgoal#{@displayed_width}" if @displayed_width != nil
text << "\\pichgoal#{@displayed_height}" if @displayed_height != nil
text << "\\picw#{@width}\\pich#{@height}\\bliptag#{@id}"
text << "\\#{@type.id2name}\n"
open_file do |file|
file.each_byte do |byte|
hex_str = byte.to_s(16)
hex_str.insert(0,'0') if hex_str.length == 1
text << hex_str
count += 1
if count == 40
text << "\n"
count = 0
end
end
end
#text << "\n}}\\par}"
text << "\n}}"
text.string
end | ruby | def to_rtf
text = StringIO.new
count = 0
#text << '{\pard{\*\shppict{\pict'
text << '{\*\shppict{\pict'
text << "\\picscalex#{@x_scaling}" if @x_scaling != nil
text << "\\picscaley#{@y_scaling}" if @y_scaling != nil
text << "\\piccropl#{@left_crop}" if @left_crop != nil
text << "\\piccropr#{@right_crop}" if @right_crop != nil
text << "\\piccropt#{@top_crop}" if @top_crop != nil
text << "\\piccropb#{@bottom_crop}" if @bottom_crop != nil
text << "\\picwgoal#{@displayed_width}" if @displayed_width != nil
text << "\\pichgoal#{@displayed_height}" if @displayed_height != nil
text << "\\picw#{@width}\\pich#{@height}\\bliptag#{@id}"
text << "\\#{@type.id2name}\n"
open_file do |file|
file.each_byte do |byte|
hex_str = byte.to_s(16)
hex_str.insert(0,'0') if hex_str.length == 1
text << hex_str
count += 1
if count == 40
text << "\n"
count = 0
end
end
end
#text << "\n}}\\par}"
text << "\n}}"
text.string
end | [
"def",
"to_rtf",
"text",
"=",
"StringIO",
".",
"new",
"count",
"=",
"0",
"text",
"<<",
"'{\\*\\shppict{\\pict'",
"text",
"<<",
"\"\\\\picscalex#{@x_scaling}\"",
"if",
"@x_scaling",
"!=",
"nil",
"text",
"<<",
"\"\\\\picscaley#{@y_scaling}\"",
"if",
"@y_scaling",
"!="... | This method generates the RTF for an ImageNode object. | [
"This",
"method",
"generates",
"the",
"RTF",
"for",
"an",
"ImageNode",
"object",
"."
] | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1374-L1407 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.ImageNode.to_integer | def to_integer(array, signed=false)
from = nil
to = nil
data = []
if array.size == 2
data.concat(get_endian == BIG_ENDIAN ? array.reverse : array)
from = 'C2'
to = signed ? 's' : 'S'
else
data.concat(get_endian == BIG_ENDIAN ? array[0,4].reverse : array)
from = 'C4'
to = signed ? 'l' : 'L'
end
data.pack(from).unpack(to)[0]
end | ruby | def to_integer(array, signed=false)
from = nil
to = nil
data = []
if array.size == 2
data.concat(get_endian == BIG_ENDIAN ? array.reverse : array)
from = 'C2'
to = signed ? 's' : 'S'
else
data.concat(get_endian == BIG_ENDIAN ? array[0,4].reverse : array)
from = 'C4'
to = signed ? 'l' : 'L'
end
data.pack(from).unpack(to)[0]
end | [
"def",
"to_integer",
"(",
"array",
",",
"signed",
"=",
"false",
")",
"from",
"=",
"nil",
"to",
"=",
"nil",
"data",
"=",
"[",
"]",
"if",
"array",
".",
"size",
"==",
"2",
"data",
".",
"concat",
"(",
"get_endian",
"==",
"BIG_ENDIAN",
"?",
"array",
"."... | This method converts an array to an integer. The array must be either
two or four bytes in length.
==== Parameters
array:: A reference to the array containing the data to be converted.
signed:: A boolean to indicate whether the value is signed. Defaults
to false. | [
"This",
"method",
"converts",
"an",
"array",
"to",
"an",
"integer",
".",
"The",
"array",
"must",
"be",
"either",
"two",
"or",
"four",
"bytes",
"in",
"length",
"."
] | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1422-L1437 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.ImageNode.read_source | def read_source(file, read, size=nil)
if block_given?
done = false
while !done and !file.eof?
read << file.getbyte
done = yield read[-1]
end
else
if size != nil
if size > 0
total = 0
while !file.eof? and total < size
read << file.getbyte
total += 1
end
end
else
file.each_byte {|byte| read << byte}
end
end
end | ruby | def read_source(file, read, size=nil)
if block_given?
done = false
while !done and !file.eof?
read << file.getbyte
done = yield read[-1]
end
else
if size != nil
if size > 0
total = 0
while !file.eof? and total < size
read << file.getbyte
total += 1
end
end
else
file.each_byte {|byte| read << byte}
end
end
end | [
"def",
"read_source",
"(",
"file",
",",
"read",
",",
"size",
"=",
"nil",
")",
"if",
"block_given?",
"done",
"=",
"false",
"while",
"!",
"done",
"and",
"!",
"file",
".",
"eof?",
"read",
"<<",
"file",
".",
"getbyte",
"done",
"=",
"yield",
"read",
"[",
... | This method loads the data for an image from its source. The method
accepts two call approaches. If called without a block then the method
considers the size parameter it is passed. If called with a block the
method executes until the block returns true.
==== Parameters
size:: The maximum number of bytes to be read from the file. Defaults
to nil to indicate that the remainder of the file should be read
in. | [
"This",
"method",
"loads",
"the",
"data",
"for",
"an",
"image",
"from",
"its",
"source",
".",
"The",
"method",
"accepts",
"two",
"call",
"approaches",
".",
"If",
"called",
"without",
"a",
"block",
"then",
"the",
"method",
"considers",
"the",
"size",
"param... | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1448-L1469 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.ImageNode.get_dimensions | def get_dimensions
dimensions = nil
open_file do |file|
file.pos = DIMENSIONS_OFFSET[@type]
read = []
# Check the image type.
if @type == JPEG
# Read until we can't anymore or we've found what we're looking for.
done = false
while !file.eof? and !done
# Read to the next marker.
read_source(file,read) {|c| c == 0xff} # Read to the marker.
read_source(file,read) {|c| c != 0xff} # Skip any padding.
if read[-1] >= 0xc0 && read[-1] <= 0xc3
# Read in the width and height details.
read_source(file, read, 7)
dimensions = read[-4,4].pack('C4').unpack('nn').reverse
done = true
else
# Skip the marker block.
read_source(file, read, 2)
read_source(file, read, read[-2,2].pack('C2').unpack('n')[0] - 2)
end
end
elsif @type == PNG
# Read in the data to contain the width and height.
read_source(file, read, 16)
dimensions = read[-8,8].pack('C8').unpack('N2')
elsif @type == BITMAP
# Read in the data to contain the width and height.
read_source(file, read, 18)
dimensions = [to_integer(read[-8,4]), to_integer(read[-4,4])]
end
end
dimensions
end | ruby | def get_dimensions
dimensions = nil
open_file do |file|
file.pos = DIMENSIONS_OFFSET[@type]
read = []
# Check the image type.
if @type == JPEG
# Read until we can't anymore or we've found what we're looking for.
done = false
while !file.eof? and !done
# Read to the next marker.
read_source(file,read) {|c| c == 0xff} # Read to the marker.
read_source(file,read) {|c| c != 0xff} # Skip any padding.
if read[-1] >= 0xc0 && read[-1] <= 0xc3
# Read in the width and height details.
read_source(file, read, 7)
dimensions = read[-4,4].pack('C4').unpack('nn').reverse
done = true
else
# Skip the marker block.
read_source(file, read, 2)
read_source(file, read, read[-2,2].pack('C2').unpack('n')[0] - 2)
end
end
elsif @type == PNG
# Read in the data to contain the width and height.
read_source(file, read, 16)
dimensions = read[-8,8].pack('C8').unpack('N2')
elsif @type == BITMAP
# Read in the data to contain the width and height.
read_source(file, read, 18)
dimensions = [to_integer(read[-8,4]), to_integer(read[-4,4])]
end
end
dimensions
end | [
"def",
"get_dimensions",
"dimensions",
"=",
"nil",
"open_file",
"do",
"|",
"file",
"|",
"file",
".",
"pos",
"=",
"DIMENSIONS_OFFSET",
"[",
"@type",
"]",
"read",
"=",
"[",
"]",
"if",
"@type",
"==",
"JPEG",
"done",
"=",
"false",
"while",
"!",
"file",
"."... | This method fetches details of the dimensions associated with an image. | [
"This",
"method",
"fetches",
"details",
"of",
"the",
"dimensions",
"associated",
"with",
"an",
"image",
"."
] | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1473-L1512 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.Document.header= | def header=(header)
if header.type == HeaderNode::UNIVERSAL
@headers[0] = header
elsif header.type == HeaderNode::LEFT_PAGE
@headers[1] = header
elsif header.type == HeaderNode::RIGHT_PAGE
@headers[2] = header
elsif header.type == HeaderNode::FIRST_PAGE
@headers[3] = header
end
end | ruby | def header=(header)
if header.type == HeaderNode::UNIVERSAL
@headers[0] = header
elsif header.type == HeaderNode::LEFT_PAGE
@headers[1] = header
elsif header.type == HeaderNode::RIGHT_PAGE
@headers[2] = header
elsif header.type == HeaderNode::FIRST_PAGE
@headers[3] = header
end
end | [
"def",
"header",
"=",
"(",
"header",
")",
"if",
"header",
".",
"type",
"==",
"HeaderNode",
"::",
"UNIVERSAL",
"@headers",
"[",
"0",
"]",
"=",
"header",
"elsif",
"header",
".",
"type",
"==",
"HeaderNode",
"::",
"LEFT_PAGE",
"@headers",
"[",
"1",
"]",
"=... | This method assigns a new header to a document. A Document object can
have up to four header - a default header, a header for left pages, a
header for right pages and a header for the first page. The method
checks the header type and stores it appropriately.
==== Parameters
header:: A reference to the header object to be stored. Existing header
objects are overwritten. | [
"This",
"method",
"assigns",
"a",
"new",
"header",
"to",
"a",
"document",
".",
"A",
"Document",
"object",
"can",
"have",
"up",
"to",
"four",
"header",
"-",
"a",
"default",
"header",
"a",
"header",
"for",
"left",
"pages",
"a",
"header",
"for",
"right",
... | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1719-L1729 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.Document.footer= | def footer=(footer)
if footer.type == FooterNode::UNIVERSAL
@footers[0] = footer
elsif footer.type == FooterNode::LEFT_PAGE
@footers[1] = footer
elsif footer.type == FooterNode::RIGHT_PAGE
@footers[2] = footer
elsif footer.type == FooterNode::FIRST_PAGE
@footers[3] = footer
end
end | ruby | def footer=(footer)
if footer.type == FooterNode::UNIVERSAL
@footers[0] = footer
elsif footer.type == FooterNode::LEFT_PAGE
@footers[1] = footer
elsif footer.type == FooterNode::RIGHT_PAGE
@footers[2] = footer
elsif footer.type == FooterNode::FIRST_PAGE
@footers[3] = footer
end
end | [
"def",
"footer",
"=",
"(",
"footer",
")",
"if",
"footer",
".",
"type",
"==",
"FooterNode",
"::",
"UNIVERSAL",
"@footers",
"[",
"0",
"]",
"=",
"footer",
"elsif",
"footer",
".",
"type",
"==",
"FooterNode",
"::",
"LEFT_PAGE",
"@footers",
"[",
"1",
"]",
"=... | This method assigns a new footer to a document. A Document object can
have up to four footers - a default footer, a footer for left pages, a
footer for right pages and a footer for the first page. The method
checks the footer type and stores it appropriately.
==== Parameters
footer:: A reference to the footer object to be stored. Existing footer
objects are overwritten. | [
"This",
"method",
"assigns",
"a",
"new",
"footer",
"to",
"a",
"document",
".",
"A",
"Document",
"object",
"can",
"have",
"up",
"to",
"four",
"footers",
"-",
"a",
"default",
"footer",
"a",
"footer",
"for",
"left",
"pages",
"a",
"footer",
"for",
"right",
... | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1739-L1749 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.Document.header | def header(type=HeaderNode::UNIVERSAL)
index = 0
if type == HeaderNode::LEFT_PAGE
index = 1
elsif type == HeaderNode::RIGHT_PAGE
index = 2
elsif type == HeaderNode::FIRST_PAGE
index = 3
end
@headers[index]
end | ruby | def header(type=HeaderNode::UNIVERSAL)
index = 0
if type == HeaderNode::LEFT_PAGE
index = 1
elsif type == HeaderNode::RIGHT_PAGE
index = 2
elsif type == HeaderNode::FIRST_PAGE
index = 3
end
@headers[index]
end | [
"def",
"header",
"(",
"type",
"=",
"HeaderNode",
"::",
"UNIVERSAL",
")",
"index",
"=",
"0",
"if",
"type",
"==",
"HeaderNode",
"::",
"LEFT_PAGE",
"index",
"=",
"1",
"elsif",
"type",
"==",
"HeaderNode",
"::",
"RIGHT_PAGE",
"index",
"=",
"2",
"elsif",
"type... | This method fetches a header from a Document object.
==== Parameters
type:: One of the header types defined in the header class. Defaults to
HeaderNode::UNIVERSAL. | [
"This",
"method",
"fetches",
"a",
"header",
"from",
"a",
"Document",
"object",
"."
] | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1756-L1766 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.Document.footer | def footer(type=FooterNode::UNIVERSAL)
index = 0
if type == FooterNode::LEFT_PAGE
index = 1
elsif type == FooterNode::RIGHT_PAGE
index = 2
elsif type == FooterNode::FIRST_PAGE
index = 3
end
@footers[index]
end | ruby | def footer(type=FooterNode::UNIVERSAL)
index = 0
if type == FooterNode::LEFT_PAGE
index = 1
elsif type == FooterNode::RIGHT_PAGE
index = 2
elsif type == FooterNode::FIRST_PAGE
index = 3
end
@footers[index]
end | [
"def",
"footer",
"(",
"type",
"=",
"FooterNode",
"::",
"UNIVERSAL",
")",
"index",
"=",
"0",
"if",
"type",
"==",
"FooterNode",
"::",
"LEFT_PAGE",
"index",
"=",
"1",
"elsif",
"type",
"==",
"FooterNode",
"::",
"RIGHT_PAGE",
"index",
"=",
"2",
"elsif",
"type... | This method fetches a footer from a Document object.
==== Parameters
type:: One of the footer types defined in the footer class. Defaults to
FooterNode::UNIVERSAL. | [
"This",
"method",
"fetches",
"a",
"footer",
"from",
"a",
"Document",
"object",
"."
] | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1773-L1783 | valid |
thechrisoshow/rtf | lib/rtf/node.rb | RTF.Document.to_rtf | def to_rtf
text = StringIO.new
text << "{#{prefix}\\#{@character_set.id2name}"
text << "\\deff#{@default_font}"
text << "\\deflang#{@language}" if !@language.nil?
text << "\\plain\\fs24\\fet1"
text << "\n#{@fonts.to_rtf}"
text << "\n#{@colours.to_rtf}" if @colours.size > 0
text << "\n#{@information.to_rtf}"
text << "\n#{@lists.to_rtf}"
if @headers.compact != []
text << "\n#{@headers[3].to_rtf}" if !@headers[3].nil?
text << "\n#{@headers[2].to_rtf}" if !@headers[2].nil?
text << "\n#{@headers[1].to_rtf}" if !@headers[1].nil?
if @headers[1].nil? or @headers[2].nil?
text << "\n#{@headers[0].to_rtf}"
end
end
if @footers.compact != []
text << "\n#{@footers[3].to_rtf}" if !@footers[3].nil?
text << "\n#{@footers[2].to_rtf}" if !@footers[2].nil?
text << "\n#{@footers[1].to_rtf}" if !@footers[1].nil?
if @footers[1].nil? or @footers[2].nil?
text << "\n#{@footers[0].to_rtf}"
end
end
text << "\n#{@style.prefix(self)}" if !@style.nil?
self.each {|entry| text << "\n#{entry.to_rtf}"}
text << "\n}"
text.string
end | ruby | def to_rtf
text = StringIO.new
text << "{#{prefix}\\#{@character_set.id2name}"
text << "\\deff#{@default_font}"
text << "\\deflang#{@language}" if !@language.nil?
text << "\\plain\\fs24\\fet1"
text << "\n#{@fonts.to_rtf}"
text << "\n#{@colours.to_rtf}" if @colours.size > 0
text << "\n#{@information.to_rtf}"
text << "\n#{@lists.to_rtf}"
if @headers.compact != []
text << "\n#{@headers[3].to_rtf}" if !@headers[3].nil?
text << "\n#{@headers[2].to_rtf}" if !@headers[2].nil?
text << "\n#{@headers[1].to_rtf}" if !@headers[1].nil?
if @headers[1].nil? or @headers[2].nil?
text << "\n#{@headers[0].to_rtf}"
end
end
if @footers.compact != []
text << "\n#{@footers[3].to_rtf}" if !@footers[3].nil?
text << "\n#{@footers[2].to_rtf}" if !@footers[2].nil?
text << "\n#{@footers[1].to_rtf}" if !@footers[1].nil?
if @footers[1].nil? or @footers[2].nil?
text << "\n#{@footers[0].to_rtf}"
end
end
text << "\n#{@style.prefix(self)}" if !@style.nil?
self.each {|entry| text << "\n#{entry.to_rtf}"}
text << "\n}"
text.string
end | [
"def",
"to_rtf",
"text",
"=",
"StringIO",
".",
"new",
"text",
"<<",
"\"{#{prefix}\\\\#{@character_set.id2name}\"",
"text",
"<<",
"\"\\\\deff#{@default_font}\"",
"text",
"<<",
"\"\\\\deflang#{@language}\"",
"if",
"!",
"@language",
".",
"nil?",
"text",
"<<",
"\"\\\\plain\... | This method generates the RTF text for a Document object. | [
"This",
"method",
"generates",
"the",
"RTF",
"text",
"for",
"a",
"Document",
"object",
"."
] | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1831-L1863 | valid |
thechrisoshow/rtf | lib/rtf/colour.rb | RTF.ColourTable.add | def add(colour)
if colour.instance_of?(Colour)
@colours.push(colour) if @colours.index(colour).nil?
end
self
end | ruby | def add(colour)
if colour.instance_of?(Colour)
@colours.push(colour) if @colours.index(colour).nil?
end
self
end | [
"def",
"add",
"(",
"colour",
")",
"if",
"colour",
".",
"instance_of?",
"(",
"Colour",
")",
"@colours",
".",
"push",
"(",
"colour",
")",
"if",
"@colours",
".",
"index",
"(",
"colour",
")",
".",
"nil?",
"end",
"self",
"end"
] | This method adds a new colour to a ColourTable object. If the colour
already exists within the table or is not a Colour object then this
method does nothing.
==== Parameters
colour:: The colour to be added to the table. | [
"This",
"method",
"adds",
"a",
"new",
"colour",
"to",
"a",
"ColourTable",
"object",
".",
"If",
"the",
"colour",
"already",
"exists",
"within",
"the",
"table",
"or",
"is",
"not",
"a",
"Colour",
"object",
"then",
"this",
"method",
"does",
"nothing",
"."
] | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/colour.rb#L103-L108 | valid |
thechrisoshow/rtf | lib/rtf/colour.rb | RTF.ColourTable.to_s | def to_s(indent=0)
prefix = indent > 0 ? ' ' * indent : ''
text = StringIO.new
text << "#{prefix}Colour Table (#{@colours.size} colours)"
@colours.each {|colour| text << "\n#{prefix} #{colour}"}
text.string
end | ruby | def to_s(indent=0)
prefix = indent > 0 ? ' ' * indent : ''
text = StringIO.new
text << "#{prefix}Colour Table (#{@colours.size} colours)"
@colours.each {|colour| text << "\n#{prefix} #{colour}"}
text.string
end | [
"def",
"to_s",
"(",
"indent",
"=",
"0",
")",
"prefix",
"=",
"indent",
">",
"0",
"?",
"' '",
"*",
"indent",
":",
"''",
"text",
"=",
"StringIO",
".",
"new",
"text",
"<<",
"\"#{prefix}Colour Table (#{@colours.size} colours)\"",
"@colours",
".",
"each",
"{",
"... | This method generates a textual description for a ColourTable object.
==== Parameters
indent:: The number of spaces to prefix to the lines generated by the
method. Defaults to zero. | [
"This",
"method",
"generates",
"a",
"textual",
"description",
"for",
"a",
"ColourTable",
"object",
"."
] | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/colour.rb#L145-L153 | valid |
thechrisoshow/rtf | lib/rtf/information.rb | RTF.Information.created= | def created=(setting)
if setting.instance_of?(Time)
@created = setting
else
datetime = Date._parse(setting.to_s).values_at(:year, :mon, :mday, :hour, :min, :sec, :zone, :wday)
if datetime == nil
RTFError.fire("Invalid document creation date/time information "\
"specified.")
end
@created = Time.local(datetime[0], datetime[1], datetime[2],
datetime[3], datetime[4], datetime[5])
end
end | ruby | def created=(setting)
if setting.instance_of?(Time)
@created = setting
else
datetime = Date._parse(setting.to_s).values_at(:year, :mon, :mday, :hour, :min, :sec, :zone, :wday)
if datetime == nil
RTFError.fire("Invalid document creation date/time information "\
"specified.")
end
@created = Time.local(datetime[0], datetime[1], datetime[2],
datetime[3], datetime[4], datetime[5])
end
end | [
"def",
"created",
"=",
"(",
"setting",
")",
"if",
"setting",
".",
"instance_of?",
"(",
"Time",
")",
"@created",
"=",
"setting",
"else",
"datetime",
"=",
"Date",
".",
"_parse",
"(",
"setting",
".",
"to_s",
")",
".",
"values_at",
"(",
":year",
",",
":mon... | This is the constructor for the Information class.
==== Parameters
title:: A string containing the document title information. Defaults
to nil.
author:: A string containing the document author information.
Defaults to nil.
company:: A string containing the company name information. Defaults
to nil.
comments:: A string containing the information comments. Defaults to
nil to indicate no comments.
creation:: A Time object or a String that can be parsed into a Time
object (using ParseDate) indicating the document creation
date and time. Defaults to nil to indicate the current
date and time.
==== Exceptions
RTFError:: Generated whenever invalid creation date/time details are
specified.
This method provides the created attribute mutator for the Information
class.
==== Parameters
setting:: The new creation date/time setting for the object. This
should be either a Time object or a string containing
date/time details that can be parsed into a Time object
(using the parsedate method).
==== Exceptions
RTFError:: Generated whenever invalid creation date/time details are
specified. | [
"This",
"is",
"the",
"constructor",
"for",
"the",
"Information",
"class",
"."
] | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/information.rb#L54-L66 | valid |
thechrisoshow/rtf | lib/rtf/information.rb | RTF.Information.to_s | def to_s(indent=0)
prefix = indent > 0 ? ' ' * indent : ''
text = StringIO.new
text << "#{prefix}Information"
text << "\n#{prefix} Title: #{@title}" unless @title.nil?
text << "\n#{prefix} Author: #{@author}" unless @author.nil?
text << "\n#{prefix} Company: #{@company}" unless @company.nil?
text << "\n#{prefix} Comments: #{@comments}" unless @comments.nil?
text << "\n#{prefix} Created: #{@created}" unless @created.nil?
text.string
end | ruby | def to_s(indent=0)
prefix = indent > 0 ? ' ' * indent : ''
text = StringIO.new
text << "#{prefix}Information"
text << "\n#{prefix} Title: #{@title}" unless @title.nil?
text << "\n#{prefix} Author: #{@author}" unless @author.nil?
text << "\n#{prefix} Company: #{@company}" unless @company.nil?
text << "\n#{prefix} Comments: #{@comments}" unless @comments.nil?
text << "\n#{prefix} Created: #{@created}" unless @created.nil?
text.string
end | [
"def",
"to_s",
"(",
"indent",
"=",
"0",
")",
"prefix",
"=",
"indent",
">",
"0",
"?",
"' '",
"*",
"indent",
":",
"''",
"text",
"=",
"StringIO",
".",
"new",
"text",
"<<",
"\"#{prefix}Information\"",
"text",
"<<",
"\"\\n#{prefix} Title: #{@title}\"",
"unle... | This method creates a textual description for an Information object.
==== Parameters
indent:: The number of spaces to prefix to the lines generated by the
method. Defaults to zero. | [
"This",
"method",
"creates",
"a",
"textual",
"description",
"for",
"an",
"Information",
"object",
"."
] | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/information.rb#L73-L85 | valid |
thechrisoshow/rtf | lib/rtf/information.rb | RTF.Information.to_rtf | def to_rtf(indent=0)
prefix = indent > 0 ? ' ' * indent : ''
text = StringIO.new
text << "#{prefix}{\\info"
text << "\n#{prefix}{\\title #{@title}}" unless @title.nil?
text << "\n#{prefix}{\\author #{@author}}" unless @author.nil?
text << "\n#{prefix}{\\company #{@company}}" unless @company.nil?
text << "\n#{prefix}{\\doccomm #{@comments}}" unless @comments.nil?
unless @created.nil?
text << "\n#{prefix}{\\createim\\yr#{@created.year}"
text << "\\mo#{@created.month}\\dy#{@created.day}"
text << "\\hr#{@created.hour}\\min#{@created.min}}"
end
text << "\n#{prefix}}"
text.string
end | ruby | def to_rtf(indent=0)
prefix = indent > 0 ? ' ' * indent : ''
text = StringIO.new
text << "#{prefix}{\\info"
text << "\n#{prefix}{\\title #{@title}}" unless @title.nil?
text << "\n#{prefix}{\\author #{@author}}" unless @author.nil?
text << "\n#{prefix}{\\company #{@company}}" unless @company.nil?
text << "\n#{prefix}{\\doccomm #{@comments}}" unless @comments.nil?
unless @created.nil?
text << "\n#{prefix}{\\createim\\yr#{@created.year}"
text << "\\mo#{@created.month}\\dy#{@created.day}"
text << "\\hr#{@created.hour}\\min#{@created.min}}"
end
text << "\n#{prefix}}"
text.string
end | [
"def",
"to_rtf",
"(",
"indent",
"=",
"0",
")",
"prefix",
"=",
"indent",
">",
"0",
"?",
"' '",
"*",
"indent",
":",
"''",
"text",
"=",
"StringIO",
".",
"new",
"text",
"<<",
"\"#{prefix}{\\\\info\"",
"text",
"<<",
"\"\\n#{prefix}{\\\\title #{@title}}\"",
"unles... | This method generates the RTF text for an Information object.
==== Parameters
indent:: The number of spaces to prefix to the lines generated by the
method. Defaults to zero. | [
"This",
"method",
"generates",
"the",
"RTF",
"text",
"for",
"an",
"Information",
"object",
"."
] | d6455933262a25628006101be802d7f7b2c3feb7 | https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/information.rb#L92-L109 | valid |
cotag/spider-gazelle | lib/spider-gazelle/signaller.rb | SpiderGazelle.Signaller.process_request | def process_request(data, client)
validated = @validated.include?(client)
parser = @validating[client.object_id]
if validated
parser.process data
else
result = parser.signal(data)
case result
when :validated
@validated.each do |old|
old.write "\x02update\x03"
end
@validated << client
if @validated.length > 1
client.write "\x02wait\x03"
else
client.write "\x02ready\x03"
end
@logger.verbose { "Client <0x#{client.object_id.to_s(16)}> connection was validated" }
when :close_connection
client.close
@logger.warn "Client <0x#{client.object_id.to_s(16)}> connection was closed due to bad credentials"
end
end
end | ruby | def process_request(data, client)
validated = @validated.include?(client)
parser = @validating[client.object_id]
if validated
parser.process data
else
result = parser.signal(data)
case result
when :validated
@validated.each do |old|
old.write "\x02update\x03"
end
@validated << client
if @validated.length > 1
client.write "\x02wait\x03"
else
client.write "\x02ready\x03"
end
@logger.verbose { "Client <0x#{client.object_id.to_s(16)}> connection was validated" }
when :close_connection
client.close
@logger.warn "Client <0x#{client.object_id.to_s(16)}> connection was closed due to bad credentials"
end
end
end | [
"def",
"process_request",
"(",
"data",
",",
"client",
")",
"validated",
"=",
"@validated",
".",
"include?",
"(",
"client",
")",
"parser",
"=",
"@validating",
"[",
"client",
".",
"object_id",
"]",
"if",
"validated",
"parser",
".",
"process",
"data",
"else",
... | The server processes requests here | [
"The",
"server",
"processes",
"requests",
"here"
] | 9eb8ffdf713f66e06579d1a9170618f457e1065c | https://github.com/cotag/spider-gazelle/blob/9eb8ffdf713f66e06579d1a9170618f457e1065c/lib/spider-gazelle/signaller.rb#L188-L214 | valid |
cotag/spider-gazelle | lib/spider-gazelle/reactor.rb | SpiderGazelle.Reactor.log | def log(error, context, trace = nil)
msg = String.new
if error.respond_to?(:backtrace)
msg << "unhandled exception: #{error.message} (#{context})"
backtrace = error.backtrace
msg << "\n#{backtrace.join("\n")}" if backtrace
msg << "\n#{trace.join("\n")}" if trace
else
msg << "unhandled exception: #{args}"
end
@logger.error msg
end | ruby | def log(error, context, trace = nil)
msg = String.new
if error.respond_to?(:backtrace)
msg << "unhandled exception: #{error.message} (#{context})"
backtrace = error.backtrace
msg << "\n#{backtrace.join("\n")}" if backtrace
msg << "\n#{trace.join("\n")}" if trace
else
msg << "unhandled exception: #{args}"
end
@logger.error msg
end | [
"def",
"log",
"(",
"error",
",",
"context",
",",
"trace",
"=",
"nil",
")",
"msg",
"=",
"String",
".",
"new",
"if",
"error",
".",
"respond_to?",
"(",
":backtrace",
")",
"msg",
"<<",
"\"unhandled exception: #{error.message} (#{context})\"",
"backtrace",
"=",
"er... | This is an unhandled error on the Libuv Event loop | [
"This",
"is",
"an",
"unhandled",
"error",
"on",
"the",
"Libuv",
"Event",
"loop"
] | 9eb8ffdf713f66e06579d1a9170618f457e1065c | https://github.com/cotag/spider-gazelle/blob/9eb8ffdf713f66e06579d1a9170618f457e1065c/lib/spider-gazelle/reactor.rb#L54-L65 | valid |
cotag/spider-gazelle | lib/spider-gazelle/spider.rb | SpiderGazelle.Spider.ready | def ready
load_promise = load_applications
load_promise.then do
# Check a shutdown request didn't occur as we were loading
if @running
@logger.verbose "All gazelles running"
# This happends on the master thread so we don't need to check
# for the shutdown events here
@loaded = true
bind_application_ports unless @delay_port_binding
else
@logger.warn "A shutdown event occured while loading"
perform_shutdown
end
end
# Provide applications with a load complete callback
@load_complete.resolve(load_promise)
end | ruby | def ready
load_promise = load_applications
load_promise.then do
# Check a shutdown request didn't occur as we were loading
if @running
@logger.verbose "All gazelles running"
# This happends on the master thread so we don't need to check
# for the shutdown events here
@loaded = true
bind_application_ports unless @delay_port_binding
else
@logger.warn "A shutdown event occured while loading"
perform_shutdown
end
end
# Provide applications with a load complete callback
@load_complete.resolve(load_promise)
end | [
"def",
"ready",
"load_promise",
"=",
"load_applications",
"load_promise",
".",
"then",
"do",
"if",
"@running",
"@logger",
".",
"verbose",
"\"All gazelles running\"",
"@loaded",
"=",
"true",
"bind_application_ports",
"unless",
"@delay_port_binding",
"else",
"@logger",
".... | Load gazelles and make the required bindings | [
"Load",
"gazelles",
"and",
"make",
"the",
"required",
"bindings"
] | 9eb8ffdf713f66e06579d1a9170618f457e1065c | https://github.com/cotag/spider-gazelle/blob/9eb8ffdf713f66e06579d1a9170618f457e1065c/lib/spider-gazelle/spider.rb#L66-L85 | valid |
barkerest/hidapi | lib/hidapi/engine.rb | HIDAPI.Engine.enumerate | def enumerate(vendor_id = 0, product_id = 0, options = {})
raise HIDAPI::HidApiError, 'not initialized' unless @context
if vendor_id.is_a?(Hash) || (vendor_id.is_a?(String) && options.empty?)
options = vendor_id
vendor_id = 0
product_id = 0
end
if product_id.is_a?(Hash) || (product_id.is_a?(String) && options.empty?)
options = product_id
product_id = 0
end
if options.is_a?(String) || options.is_a?(Symbol)
options = { as: options }
end
unless options.nil? || options.is_a?(Hash)
raise ArgumentError, 'options hash is invalid'
end
klass = (options || {}).delete(:as) || 'HIDAPI::Device'
klass = Object.const_get(klass) unless klass == :no_mapping
filters = { bClass: HID_CLASS }
unless vendor_id.nil? || vendor_id.to_i == 0
filters[:idVendor] = vendor_id.to_i
end
unless product_id.nil? || product_id.to_i == 0
filters[:idProduct] = product_id.to_i
end
list = @context.devices(filters)
if klass != :no_mapping
list.to_a.map{ |dev| klass.new(dev) }
else
list.to_a
end
end | ruby | def enumerate(vendor_id = 0, product_id = 0, options = {})
raise HIDAPI::HidApiError, 'not initialized' unless @context
if vendor_id.is_a?(Hash) || (vendor_id.is_a?(String) && options.empty?)
options = vendor_id
vendor_id = 0
product_id = 0
end
if product_id.is_a?(Hash) || (product_id.is_a?(String) && options.empty?)
options = product_id
product_id = 0
end
if options.is_a?(String) || options.is_a?(Symbol)
options = { as: options }
end
unless options.nil? || options.is_a?(Hash)
raise ArgumentError, 'options hash is invalid'
end
klass = (options || {}).delete(:as) || 'HIDAPI::Device'
klass = Object.const_get(klass) unless klass == :no_mapping
filters = { bClass: HID_CLASS }
unless vendor_id.nil? || vendor_id.to_i == 0
filters[:idVendor] = vendor_id.to_i
end
unless product_id.nil? || product_id.to_i == 0
filters[:idProduct] = product_id.to_i
end
list = @context.devices(filters)
if klass != :no_mapping
list.to_a.map{ |dev| klass.new(dev) }
else
list.to_a
end
end | [
"def",
"enumerate",
"(",
"vendor_id",
"=",
"0",
",",
"product_id",
"=",
"0",
",",
"options",
"=",
"{",
"}",
")",
"raise",
"HIDAPI",
"::",
"HidApiError",
",",
"'not initialized'",
"unless",
"@context",
"if",
"vendor_id",
".",
"is_a?",
"(",
"Hash",
")",
"|... | Creates a new engine.
Enumerates the HID devices matching the vendor and product IDs.
Both vendor_id and product_id are optional. They will act as a wild card if set to 0 (the default). | [
"Creates",
"a",
"new",
"engine",
"."
] | d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7 | https://github.com/barkerest/hidapi/blob/d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7/lib/hidapi/engine.rb#L23-L64 | valid |
barkerest/hidapi | lib/hidapi/engine.rb | HIDAPI.Engine.get_device | def get_device(vendor_id, product_id, serial_number = nil, options = {})
raise ArgumentError, 'vendor_id must be provided' if vendor_id.to_i == 0
raise ArgumentError, 'product_id must be provided' if product_id.to_i == 0
if serial_number.is_a?(Hash)
options = serial_number
serial_number = nil
end
klass = (options || {}).delete(:as) || 'HIDAPI::Device'
klass = Object.const_get(klass) unless klass == :no_mapping
list = enumerate(vendor_id, product_id, as: :no_mapping)
return nil unless list && list.count > 0
if serial_number.to_s == ''
if klass != :no_mapping
return klass.new(list.first)
else
return list.first
end
end
list.each do |dev|
if dev.serial_number == serial_number
if klass != :no_mapping
return klass.new(dev)
else
return dev
end
end
end
nil
end | ruby | def get_device(vendor_id, product_id, serial_number = nil, options = {})
raise ArgumentError, 'vendor_id must be provided' if vendor_id.to_i == 0
raise ArgumentError, 'product_id must be provided' if product_id.to_i == 0
if serial_number.is_a?(Hash)
options = serial_number
serial_number = nil
end
klass = (options || {}).delete(:as) || 'HIDAPI::Device'
klass = Object.const_get(klass) unless klass == :no_mapping
list = enumerate(vendor_id, product_id, as: :no_mapping)
return nil unless list && list.count > 0
if serial_number.to_s == ''
if klass != :no_mapping
return klass.new(list.first)
else
return list.first
end
end
list.each do |dev|
if dev.serial_number == serial_number
if klass != :no_mapping
return klass.new(dev)
else
return dev
end
end
end
nil
end | [
"def",
"get_device",
"(",
"vendor_id",
",",
"product_id",
",",
"serial_number",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
",",
"'vendor_id must be provided'",
"if",
"vendor_id",
".",
"to_i",
"==",
"0",
"raise",
"ArgumentError",
... | Gets the first device with the specified vendor_id, product_id, and optionally serial_number. | [
"Gets",
"the",
"first",
"device",
"with",
"the",
"specified",
"vendor_id",
"product_id",
"and",
"optionally",
"serial_number",
"."
] | d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7 | https://github.com/barkerest/hidapi/blob/d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7/lib/hidapi/engine.rb#L68-L99 | valid |
barkerest/hidapi | lib/hidapi/engine.rb | HIDAPI.Engine.open | def open(vendor_id, product_id, serial_number = nil, options = {})
dev = get_device(vendor_id, product_id, serial_number, options)
dev.open if dev
end | ruby | def open(vendor_id, product_id, serial_number = nil, options = {})
dev = get_device(vendor_id, product_id, serial_number, options)
dev.open if dev
end | [
"def",
"open",
"(",
"vendor_id",
",",
"product_id",
",",
"serial_number",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"dev",
"=",
"get_device",
"(",
"vendor_id",
",",
"product_id",
",",
"serial_number",
",",
"options",
")",
"dev",
".",
"open",
"if",
... | Opens the first device with the specified vendor_id, product_id, and optionally serial_number. | [
"Opens",
"the",
"first",
"device",
"with",
"the",
"specified",
"vendor_id",
"product_id",
"and",
"optionally",
"serial_number",
"."
] | d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7 | https://github.com/barkerest/hidapi/blob/d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7/lib/hidapi/engine.rb#L103-L106 | valid |
barkerest/hidapi | lib/hidapi/engine.rb | HIDAPI.Engine.get_device_by_path | def get_device_by_path(path, options = {})
# Our linux setup routine creates convenient /dev/hidapi/* links.
# If the user wants to open one of those, we can simple parse the link to generate
# the path that the library expects.
if File.exist?(path)
hidapi_regex = /^\/dev\/hidapi\//
usb_bus_regex = /^\/dev\/bus\/usb\/(?<BUS>\d+)\/(?<ADDR>\d+)$/
if hidapi_regex.match(path)
path = File.expand_path(File.readlink(path), File.dirname(path))
elsif !usb_bus_regex.match(path)
raise HIDAPI::DevicePathInvalid, 'Cannot open file paths other than /dev/hidapi/XXX or /dev/bus/usb/XXX/XXX paths.'
end
# path should now be in the form /dev/bus/usb/AAA/BBB
match = usb_bus_regex.match(path)
raise HIDAPI::DevicePathInvalid, "Link target does not appear valid (#{path})." unless match
interface = (options.delete(:interface) || 0).to_s(16)
path = HIDAPI::Device.validate_path("#{match['BUS']}:#{match['ADDR']}:#{interface}")
end
valid_path = HIDAPI::Device.validate_path(path)
raise HIDAPI::DevicePathInvalid, "Path should be in BUS:ADDRESS:INTERFACE format with each value being in hexadecimal (ie - 0001:01A:00), not #{path}." unless valid_path
path = valid_path
klass = (options || {}).delete(:as) || 'HIDAPI::Device'
klass = Object.const_get(klass) unless klass == :no_mapping
enumerate(as: :no_mapping).each do |usb_dev|
usb_dev.settings.each do |intf_desc|
if intf_desc.bInterfaceClass == HID_CLASS
dev_path = HIDAPI::Device.make_path(usb_dev, intf_desc.bInterfaceNumber)
if dev_path == path
if klass != :no_mapping
return klass.new(usb_dev, intf_desc.bInterfaceNumber)
else
return usb_dev
end
end
end
end
end
end | ruby | def get_device_by_path(path, options = {})
# Our linux setup routine creates convenient /dev/hidapi/* links.
# If the user wants to open one of those, we can simple parse the link to generate
# the path that the library expects.
if File.exist?(path)
hidapi_regex = /^\/dev\/hidapi\//
usb_bus_regex = /^\/dev\/bus\/usb\/(?<BUS>\d+)\/(?<ADDR>\d+)$/
if hidapi_regex.match(path)
path = File.expand_path(File.readlink(path), File.dirname(path))
elsif !usb_bus_regex.match(path)
raise HIDAPI::DevicePathInvalid, 'Cannot open file paths other than /dev/hidapi/XXX or /dev/bus/usb/XXX/XXX paths.'
end
# path should now be in the form /dev/bus/usb/AAA/BBB
match = usb_bus_regex.match(path)
raise HIDAPI::DevicePathInvalid, "Link target does not appear valid (#{path})." unless match
interface = (options.delete(:interface) || 0).to_s(16)
path = HIDAPI::Device.validate_path("#{match['BUS']}:#{match['ADDR']}:#{interface}")
end
valid_path = HIDAPI::Device.validate_path(path)
raise HIDAPI::DevicePathInvalid, "Path should be in BUS:ADDRESS:INTERFACE format with each value being in hexadecimal (ie - 0001:01A:00), not #{path}." unless valid_path
path = valid_path
klass = (options || {}).delete(:as) || 'HIDAPI::Device'
klass = Object.const_get(klass) unless klass == :no_mapping
enumerate(as: :no_mapping).each do |usb_dev|
usb_dev.settings.each do |intf_desc|
if intf_desc.bInterfaceClass == HID_CLASS
dev_path = HIDAPI::Device.make_path(usb_dev, intf_desc.bInterfaceNumber)
if dev_path == path
if klass != :no_mapping
return klass.new(usb_dev, intf_desc.bInterfaceNumber)
else
return usb_dev
end
end
end
end
end
end | [
"def",
"get_device_by_path",
"(",
"path",
",",
"options",
"=",
"{",
"}",
")",
"if",
"File",
".",
"exist?",
"(",
"path",
")",
"hidapi_regex",
"=",
"/",
"\\/",
"\\/",
"\\/",
"/",
"usb_bus_regex",
"=",
"/",
"\\/",
"\\/",
"\\/",
"\\/",
"\\d",
"\\/",
"\\d... | Gets the device with the specified path. | [
"Gets",
"the",
"device",
"with",
"the",
"specified",
"path",
"."
] | d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7 | https://github.com/barkerest/hidapi/blob/d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7/lib/hidapi/engine.rb#L110-L157 | valid |
barkerest/hidapi | lib/hidapi/engine.rb | HIDAPI.Engine.open_path | def open_path(path, options = {})
dev = get_device_by_path(path, options)
dev.open if dev
end | ruby | def open_path(path, options = {})
dev = get_device_by_path(path, options)
dev.open if dev
end | [
"def",
"open_path",
"(",
"path",
",",
"options",
"=",
"{",
"}",
")",
"dev",
"=",
"get_device_by_path",
"(",
"path",
",",
"options",
")",
"dev",
".",
"open",
"if",
"dev",
"end"
] | Opens the device with the specified path. | [
"Opens",
"the",
"device",
"with",
"the",
"specified",
"path",
"."
] | d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7 | https://github.com/barkerest/hidapi/blob/d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7/lib/hidapi/engine.rb#L161-L164 | valid |
barkerest/hidapi | lib/hidapi/engine.rb | HIDAPI.Engine.usb_code_for_current_locale | def usb_code_for_current_locale
@usb_code_for_current_locale ||=
begin
locale = I18n.locale
if locale
locale = locale.to_s.partition('.')[0] # remove encoding
result = HIDAPI::Language.get_by_code(locale)
unless result
locale = locale.partition('_')[0] # chop off extra specification
result = HIDAPI::Language.get_by_code(locale)
end
result ? result[:usb_code] : 0
else
0
end
end
end | ruby | def usb_code_for_current_locale
@usb_code_for_current_locale ||=
begin
locale = I18n.locale
if locale
locale = locale.to_s.partition('.')[0] # remove encoding
result = HIDAPI::Language.get_by_code(locale)
unless result
locale = locale.partition('_')[0] # chop off extra specification
result = HIDAPI::Language.get_by_code(locale)
end
result ? result[:usb_code] : 0
else
0
end
end
end | [
"def",
"usb_code_for_current_locale",
"@usb_code_for_current_locale",
"||=",
"begin",
"locale",
"=",
"I18n",
".",
"locale",
"if",
"locale",
"locale",
"=",
"locale",
".",
"to_s",
".",
"partition",
"(",
"'.'",
")",
"[",
"0",
"]",
"result",
"=",
"HIDAPI",
"::",
... | Gets the USB code for the current locale. | [
"Gets",
"the",
"USB",
"code",
"for",
"the",
"current",
"locale",
"."
] | d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7 | https://github.com/barkerest/hidapi/blob/d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7/lib/hidapi/engine.rb#L168-L184 | valid |
barkerest/hidapi | lib/hidapi/device.rb | HIDAPI.Device.open | def open
if open?
self.open_count += 1
if open_count < 1
HIDAPI.debug "open_count for open device #{path} is #{open_count}"
self.open_count = 1
end
return self
end
self.open_count = 0
begin
self.handle = usb_device.open
raise 'no handle returned' unless handle
begin
if handle.kernel_driver_active?(interface)
handle.detach_kernel_driver(interface)
end
rescue LIBUSB::ERROR_NOT_SUPPORTED
HIDAPI.debug 'cannot determine kernel driver status, continuing to open device'
end
handle.claim_interface(interface)
self.input_endpoint = self.output_endpoint = nil
# now we need to find the endpoints.
usb_device.settings
.keep_if {|item| item.bInterfaceNumber == interface}
.each do |intf_desc|
intf_desc.endpoints.each do |ep|
if ep.transfer_type == :interrupt
if input_endpoint.nil? && ep.direction == :in
self.input_endpoint = ep.bEndpointAddress
self.input_ep_max_packet_size = ep.wMaxPacketSize
end
if output_endpoint.nil? && ep.direction == :out
self.output_endpoint = ep.bEndpointAddress
end
end
break if input_endpoint && output_endpoint
end
end
# output_ep is optional, input_ep is required
raise 'failed to locate input endpoint' unless input_endpoint
# start the read thread
self.input_reports = []
self.thread_initialized = false
self.shutdown_thread = false
self.thread = Thread.start(self) { |dev| dev.send(:execute_read_thread) }
sleep 0.001 until thread_initialized
rescue =>e
handle.close rescue nil
self.handle = nil
HIDAPI.debug "failed to open device #{path}: #{e.inspect}"
raise DeviceOpenFailed, e.inspect
end
HIDAPI.debug "opened device #{path}"
self.open_count = 1
self
end | ruby | def open
if open?
self.open_count += 1
if open_count < 1
HIDAPI.debug "open_count for open device #{path} is #{open_count}"
self.open_count = 1
end
return self
end
self.open_count = 0
begin
self.handle = usb_device.open
raise 'no handle returned' unless handle
begin
if handle.kernel_driver_active?(interface)
handle.detach_kernel_driver(interface)
end
rescue LIBUSB::ERROR_NOT_SUPPORTED
HIDAPI.debug 'cannot determine kernel driver status, continuing to open device'
end
handle.claim_interface(interface)
self.input_endpoint = self.output_endpoint = nil
# now we need to find the endpoints.
usb_device.settings
.keep_if {|item| item.bInterfaceNumber == interface}
.each do |intf_desc|
intf_desc.endpoints.each do |ep|
if ep.transfer_type == :interrupt
if input_endpoint.nil? && ep.direction == :in
self.input_endpoint = ep.bEndpointAddress
self.input_ep_max_packet_size = ep.wMaxPacketSize
end
if output_endpoint.nil? && ep.direction == :out
self.output_endpoint = ep.bEndpointAddress
end
end
break if input_endpoint && output_endpoint
end
end
# output_ep is optional, input_ep is required
raise 'failed to locate input endpoint' unless input_endpoint
# start the read thread
self.input_reports = []
self.thread_initialized = false
self.shutdown_thread = false
self.thread = Thread.start(self) { |dev| dev.send(:execute_read_thread) }
sleep 0.001 until thread_initialized
rescue =>e
handle.close rescue nil
self.handle = nil
HIDAPI.debug "failed to open device #{path}: #{e.inspect}"
raise DeviceOpenFailed, e.inspect
end
HIDAPI.debug "opened device #{path}"
self.open_count = 1
self
end | [
"def",
"open",
"if",
"open?",
"self",
".",
"open_count",
"+=",
"1",
"if",
"open_count",
"<",
"1",
"HIDAPI",
".",
"debug",
"\"open_count for open device #{path} is #{open_count}\"",
"self",
".",
"open_count",
"=",
"1",
"end",
"return",
"self",
"end",
"self",
".",... | Opens the device.
Returns the device. | [
"Opens",
"the",
"device",
"."
] | d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7 | https://github.com/barkerest/hidapi/blob/d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7/lib/hidapi/device.rb#L193-L256 | valid |
barkerest/hidapi | lib/hidapi/device.rb | HIDAPI.Device.read_timeout | def read_timeout(milliseconds)
raise DeviceNotOpen unless open?
mutex.synchronize do
if input_reports.count > 0
data = input_reports.delete_at(0)
HIDAPI.debug "read data from device #{path}: #{data.inspect}"
return data
end
if shutdown_thread
HIDAPI.debug "read thread for device #{path} is not running"
return nil
end
end
# no data to return, do not block.
return '' if milliseconds == 0
if milliseconds < 0
# wait forever (as long as the read thread doesn't die)
until shutdown_thread
mutex.synchronize do
if input_reports.count > 0
data = input_reports.delete_at(0)
HIDAPI.debug "read data from device #{path}: #{data.inspect}"
return data
end
end
sleep 0.001
end
# error, return nil
HIDAPI.debug "read thread ended while waiting on device #{path}"
nil
else
# wait up to so many milliseconds for input.
stop_at = Time.now + (milliseconds * 0.001)
while Time.now < stop_at
mutex.synchronize do
if input_reports.count > 0
data = input_reports.delete_at(0)
HIDAPI.debug "read data from device #{path}: #{data.inspect}"
return data
end
end
sleep 0.001
end
# no input, return empty.
''
end
end | ruby | def read_timeout(milliseconds)
raise DeviceNotOpen unless open?
mutex.synchronize do
if input_reports.count > 0
data = input_reports.delete_at(0)
HIDAPI.debug "read data from device #{path}: #{data.inspect}"
return data
end
if shutdown_thread
HIDAPI.debug "read thread for device #{path} is not running"
return nil
end
end
# no data to return, do not block.
return '' if milliseconds == 0
if milliseconds < 0
# wait forever (as long as the read thread doesn't die)
until shutdown_thread
mutex.synchronize do
if input_reports.count > 0
data = input_reports.delete_at(0)
HIDAPI.debug "read data from device #{path}: #{data.inspect}"
return data
end
end
sleep 0.001
end
# error, return nil
HIDAPI.debug "read thread ended while waiting on device #{path}"
nil
else
# wait up to so many milliseconds for input.
stop_at = Time.now + (milliseconds * 0.001)
while Time.now < stop_at
mutex.synchronize do
if input_reports.count > 0
data = input_reports.delete_at(0)
HIDAPI.debug "read data from device #{path}: #{data.inspect}"
return data
end
end
sleep 0.001
end
# no input, return empty.
''
end
end | [
"def",
"read_timeout",
"(",
"milliseconds",
")",
"raise",
"DeviceNotOpen",
"unless",
"open?",
"mutex",
".",
"synchronize",
"do",
"if",
"input_reports",
".",
"count",
">",
"0",
"data",
"=",
"input_reports",
".",
"delete_at",
"(",
"0",
")",
"HIDAPI",
".",
"deb... | Attempts to read from the device, waiting up to +milliseconds+ before returning.
If milliseconds is less than 1, it will wait forever.
If milliseconds is 0, then it will return immediately.
Returns the next report on success. If no report is available and it is not waiting
forever, it will return an empty string.
Returns nil on error. | [
"Attempts",
"to",
"read",
"from",
"the",
"device",
"waiting",
"up",
"to",
"+",
"milliseconds",
"+",
"before",
"returning",
"."
] | d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7 | https://github.com/barkerest/hidapi/blob/d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7/lib/hidapi/device.rb#L301-L353 | valid |
barkerest/hidapi | lib/hidapi/device.rb | HIDAPI.Device.send_feature_report | def send_feature_report(data)
raise ArgumentError, 'data must not be blank' if data.nil? || data.length < 1
raise HIDAPI::DeviceNotOpen unless open?
data, report_number, skipped_report_id = clean_output_data(data)
mutex.synchronize do
handle.control_transfer(
bmRequestType: LIBUSB::REQUEST_TYPE_CLASS | LIBUSB::RECIPIENT_INTERFACE | LIBUSB::ENDPOINT_OUT,
bRequest: 0x09, # HID Set_Report
wValue: (3 << 8) | report_number, # HID feature = 3
wIndex: interface,
dataOut: data
)
end
data.length + (skipped_report_id ? 1 : 0)
end | ruby | def send_feature_report(data)
raise ArgumentError, 'data must not be blank' if data.nil? || data.length < 1
raise HIDAPI::DeviceNotOpen unless open?
data, report_number, skipped_report_id = clean_output_data(data)
mutex.synchronize do
handle.control_transfer(
bmRequestType: LIBUSB::REQUEST_TYPE_CLASS | LIBUSB::RECIPIENT_INTERFACE | LIBUSB::ENDPOINT_OUT,
bRequest: 0x09, # HID Set_Report
wValue: (3 << 8) | report_number, # HID feature = 3
wIndex: interface,
dataOut: data
)
end
data.length + (skipped_report_id ? 1 : 0)
end | [
"def",
"send_feature_report",
"(",
"data",
")",
"raise",
"ArgumentError",
",",
"'data must not be blank'",
"if",
"data",
".",
"nil?",
"||",
"data",
".",
"length",
"<",
"1",
"raise",
"HIDAPI",
"::",
"DeviceNotOpen",
"unless",
"open?",
"data",
",",
"report_number"... | Sends a feature report to the device. | [
"Sends",
"a",
"feature",
"report",
"to",
"the",
"device",
"."
] | d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7 | https://github.com/barkerest/hidapi/blob/d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7/lib/hidapi/device.rb#L374-L391 | valid |
barkerest/hidapi | lib/hidapi/device.rb | HIDAPI.Device.get_feature_report | def get_feature_report(report_number, buffer_size = nil)
buffer_size ||= input_ep_max_packet_size
mutex.synchronize do
handle.control_transfer(
bmRequestType: LIBUSB::REQUEST_TYPE_CLASS | LIBUSB::RECIPIENT_INTERFACE | LIBUSB::ENDPOINT_IN,
bRequest: 0x01, # HID Get_Report
wValue: (3 << 8) | report_number,
wIndex: interface,
dataIn: buffer_size
)
end
end | ruby | def get_feature_report(report_number, buffer_size = nil)
buffer_size ||= input_ep_max_packet_size
mutex.synchronize do
handle.control_transfer(
bmRequestType: LIBUSB::REQUEST_TYPE_CLASS | LIBUSB::RECIPIENT_INTERFACE | LIBUSB::ENDPOINT_IN,
bRequest: 0x01, # HID Get_Report
wValue: (3 << 8) | report_number,
wIndex: interface,
dataIn: buffer_size
)
end
end | [
"def",
"get_feature_report",
"(",
"report_number",
",",
"buffer_size",
"=",
"nil",
")",
"buffer_size",
"||=",
"input_ep_max_packet_size",
"mutex",
".",
"synchronize",
"do",
"handle",
".",
"control_transfer",
"(",
"bmRequestType",
":",
"LIBUSB",
"::",
"REQUEST_TYPE_CLA... | Gets a feature report from the device. | [
"Gets",
"a",
"feature",
"report",
"from",
"the",
"device",
"."
] | d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7 | https://github.com/barkerest/hidapi/blob/d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7/lib/hidapi/device.rb#L395-L409 | valid |
barkerest/hidapi | lib/hidapi/device.rb | HIDAPI.Device.read_string | def read_string(index, on_failure = '')
begin
# does not require an interface, so open from the usb_dev instead of using our open method.
data = mutex.synchronize do
if open?
handle.string_descriptor_ascii(index)
else
usb_device.open { |handle| handle.string_descriptor_ascii(index) }
end
end
HIDAPI.debug("read string at index #{index} for device #{path}: #{data.inspect}")
data
rescue =>e
HIDAPI.debug("failed to read string at index #{index} for device #{path}: #{e.inspect}")
on_failure || ''
end
end | ruby | def read_string(index, on_failure = '')
begin
# does not require an interface, so open from the usb_dev instead of using our open method.
data = mutex.synchronize do
if open?
handle.string_descriptor_ascii(index)
else
usb_device.open { |handle| handle.string_descriptor_ascii(index) }
end
end
HIDAPI.debug("read string at index #{index} for device #{path}: #{data.inspect}")
data
rescue =>e
HIDAPI.debug("failed to read string at index #{index} for device #{path}: #{e.inspect}")
on_failure || ''
end
end | [
"def",
"read_string",
"(",
"index",
",",
"on_failure",
"=",
"''",
")",
"begin",
"data",
"=",
"mutex",
".",
"synchronize",
"do",
"if",
"open?",
"handle",
".",
"string_descriptor_ascii",
"(",
"index",
")",
"else",
"usb_device",
".",
"open",
"{",
"|",
"handle... | Reads a string descriptor from the USB device. | [
"Reads",
"a",
"string",
"descriptor",
"from",
"the",
"USB",
"device",
"."
] | d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7 | https://github.com/barkerest/hidapi/blob/d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7/lib/hidapi/device.rb#L452-L469 | valid |
gtarnovan/simple_audit | lib/simple_audit/audit.rb | SimpleAudit.Audit.delta | def delta(other_audit)
return self.change_log if other_audit.nil?
{}.tap do |d|
# first for keys present only in this audit
(self.change_log.keys - other_audit.change_log.keys).each do |k|
d[k] = [nil, self.change_log[k]]
end
# .. then for keys present only in other audit
(other_audit.change_log.keys - self.change_log.keys).each do |k|
d[k] = [other_audit.change_log[k], nil]
end
# .. finally for keys present in both, but with different values
self.change_log.keys.each do |k|
if self.change_log[k] != other_audit.change_log[k]
d[k] = [other_audit.change_log[k], self.change_log[k]]
end
end
end
end | ruby | def delta(other_audit)
return self.change_log if other_audit.nil?
{}.tap do |d|
# first for keys present only in this audit
(self.change_log.keys - other_audit.change_log.keys).each do |k|
d[k] = [nil, self.change_log[k]]
end
# .. then for keys present only in other audit
(other_audit.change_log.keys - self.change_log.keys).each do |k|
d[k] = [other_audit.change_log[k], nil]
end
# .. finally for keys present in both, but with different values
self.change_log.keys.each do |k|
if self.change_log[k] != other_audit.change_log[k]
d[k] = [other_audit.change_log[k], self.change_log[k]]
end
end
end
end | [
"def",
"delta",
"(",
"other_audit",
")",
"return",
"self",
".",
"change_log",
"if",
"other_audit",
".",
"nil?",
"{",
"}",
".",
"tap",
"do",
"|",
"d",
"|",
"(",
"self",
".",
"change_log",
".",
"keys",
"-",
"other_audit",
".",
"change_log",
".",
"keys",
... | Computes the differences of the change logs between two audits.
Returns a hash containing arrays of the form
{
:key_1 => [<value_in_other_audit>, <value_in_this_audit>],
:key_2 => [<value_in_other_audit>, <value_in_this_audit>],
} | [
"Computes",
"the",
"differences",
"of",
"the",
"change",
"logs",
"between",
"two",
"audits",
"."
] | c68b8b30c51117c75a838d066b60e31213598471 | https://github.com/gtarnovan/simple_audit/blob/c68b8b30c51117c75a838d066b60e31213598471/lib/simple_audit/audit.rb#L16-L41 | valid |
gtarnovan/simple_audit | lib/simple_audit/helper.rb | SimpleAudit.Helper.render_audits | def render_audits(audited_model)
return '' unless audited_model.respond_to?(:audits)
audits = (audited_model.audits || []).dup.sort{|a,b| b.created_at <=> a.created_at}
res = ''
audits.each_with_index do |audit, index|
older_audit = audits[index + 1]
res += content_tag(:div, :class => 'audit') do
content_tag(:div, audit.action, :class => "action #{audit.action}") +
content_tag(:div, audit.username, :class => "user") +
content_tag(:div, l(audit.created_at), :class => "timestamp") +
content_tag(:div, :class => 'changes') do
changes = if older_audit.present?
audit.delta(older_audit).sort{|x,y| audited_model.class.human_attribute_name(x.first) <=> audited_model.class.human_attribute_name(y.first)}.collect do |k, v|
next if k.to_s == 'created_at' || k.to_s == 'updated_at'
"\n" +
audited_model.class.human_attribute_name(k) +
":" +
content_tag(:span, v.last, :class => 'current') +
content_tag(:span, v.first, :class => 'previous')
end
else
audit.change_log.sort{|x,y| audited_model.class.human_attribute_name(x.first) <=> audited_model.class.human_attribute_name(y.first)}.reject{|k, v| v.blank?}.collect {|k, v| "\n#{audited_model.class.human_attribute_name(k)}: #{v}"}
end
raw changes.join
end
end
end
raw res
end | ruby | def render_audits(audited_model)
return '' unless audited_model.respond_to?(:audits)
audits = (audited_model.audits || []).dup.sort{|a,b| b.created_at <=> a.created_at}
res = ''
audits.each_with_index do |audit, index|
older_audit = audits[index + 1]
res += content_tag(:div, :class => 'audit') do
content_tag(:div, audit.action, :class => "action #{audit.action}") +
content_tag(:div, audit.username, :class => "user") +
content_tag(:div, l(audit.created_at), :class => "timestamp") +
content_tag(:div, :class => 'changes') do
changes = if older_audit.present?
audit.delta(older_audit).sort{|x,y| audited_model.class.human_attribute_name(x.first) <=> audited_model.class.human_attribute_name(y.first)}.collect do |k, v|
next if k.to_s == 'created_at' || k.to_s == 'updated_at'
"\n" +
audited_model.class.human_attribute_name(k) +
":" +
content_tag(:span, v.last, :class => 'current') +
content_tag(:span, v.first, :class => 'previous')
end
else
audit.change_log.sort{|x,y| audited_model.class.human_attribute_name(x.first) <=> audited_model.class.human_attribute_name(y.first)}.reject{|k, v| v.blank?}.collect {|k, v| "\n#{audited_model.class.human_attribute_name(k)}: #{v}"}
end
raw changes.join
end
end
end
raw res
end | [
"def",
"render_audits",
"(",
"audited_model",
")",
"return",
"''",
"unless",
"audited_model",
".",
"respond_to?",
"(",
":audits",
")",
"audits",
"=",
"(",
"audited_model",
".",
"audits",
"||",
"[",
"]",
")",
".",
"dup",
".",
"sort",
"{",
"|",
"a",
",",
... | Render the change log for the given audited model | [
"Render",
"the",
"change",
"log",
"for",
"the",
"given",
"audited",
"model"
] | c68b8b30c51117c75a838d066b60e31213598471 | https://github.com/gtarnovan/simple_audit/blob/c68b8b30c51117c75a838d066b60e31213598471/lib/simple_audit/helper.rb#L6-L34 | valid |
guard/guard-haml | lib/guard/haml.rb | Guard.Haml._output_paths | def _output_paths(file)
input_file_dir = File.dirname(file)
file_name = _output_filename(file)
file_name = "#{file_name}.html" if _append_html_ext_to_output_path?(file_name)
input_file_dir = input_file_dir.gsub(Regexp.new("#{options[:input]}(\/){0,1}"), '') if options[:input]
if options[:output]
Array(options[:output]).map do |output_dir|
File.join(output_dir, input_file_dir, file_name)
end
else
if input_file_dir == ''
[file_name]
else
[File.join(input_file_dir, file_name)]
end
end
end | ruby | def _output_paths(file)
input_file_dir = File.dirname(file)
file_name = _output_filename(file)
file_name = "#{file_name}.html" if _append_html_ext_to_output_path?(file_name)
input_file_dir = input_file_dir.gsub(Regexp.new("#{options[:input]}(\/){0,1}"), '') if options[:input]
if options[:output]
Array(options[:output]).map do |output_dir|
File.join(output_dir, input_file_dir, file_name)
end
else
if input_file_dir == ''
[file_name]
else
[File.join(input_file_dir, file_name)]
end
end
end | [
"def",
"_output_paths",
"(",
"file",
")",
"input_file_dir",
"=",
"File",
".",
"dirname",
"(",
"file",
")",
"file_name",
"=",
"_output_filename",
"(",
"file",
")",
"file_name",
"=",
"\"#{file_name}.html\"",
"if",
"_append_html_ext_to_output_path?",
"(",
"file_name",
... | Get the file path to output the html based on the file being
built. The output path is relative to where guard is being run.
@param file [String, Array<String>] path to file being built
@return [Array<String>] path(s) to file where output should be written | [
"Get",
"the",
"file",
"path",
"to",
"output",
"the",
"html",
"based",
"on",
"the",
"file",
"being",
"built",
".",
"The",
"output",
"path",
"is",
"relative",
"to",
"where",
"guard",
"is",
"being",
"run",
"."
] | ea981b68ce86ff7dac1972b1c303b3426d2d263e | https://github.com/guard/guard-haml/blob/ea981b68ce86ff7dac1972b1c303b3426d2d263e/lib/guard/haml.rb#L84-L101 | valid |
guard/guard-haml | lib/guard/haml.rb | Guard.Haml._output_filename | def _output_filename(file)
sub_strings = File.basename(file).split('.')
base_name, extensions = sub_strings.first, sub_strings[1..-1]
if extensions.last == 'haml'
extensions.pop
if extensions.empty?
[base_name, options[:default_ext]].join('.')
else
[base_name, extensions].flatten.join('.')
end
else
[base_name, extensions, options[:default_ext]].flatten.compact.join('.')
end
end | ruby | def _output_filename(file)
sub_strings = File.basename(file).split('.')
base_name, extensions = sub_strings.first, sub_strings[1..-1]
if extensions.last == 'haml'
extensions.pop
if extensions.empty?
[base_name, options[:default_ext]].join('.')
else
[base_name, extensions].flatten.join('.')
end
else
[base_name, extensions, options[:default_ext]].flatten.compact.join('.')
end
end | [
"def",
"_output_filename",
"(",
"file",
")",
"sub_strings",
"=",
"File",
".",
"basename",
"(",
"file",
")",
".",
"split",
"(",
"'.'",
")",
"base_name",
",",
"extensions",
"=",
"sub_strings",
".",
"first",
",",
"sub_strings",
"[",
"1",
"..",
"-",
"1",
"... | Generate a file name based on the provided file path.
Provide a logical extension.
Examples:
"path/foo.haml" -> "foo.html"
"path/foo" -> "foo.html"
"path/foo.bar" -> "foo.bar.html"
"path/foo.bar.haml" -> "foo.bar"
@param file String path to file
@return String file name including extension | [
"Generate",
"a",
"file",
"name",
"based",
"on",
"the",
"provided",
"file",
"path",
".",
"Provide",
"a",
"logical",
"extension",
"."
] | ea981b68ce86ff7dac1972b1c303b3426d2d263e | https://github.com/guard/guard-haml/blob/ea981b68ce86ff7dac1972b1c303b3426d2d263e/lib/guard/haml.rb#L115-L129 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vapp.rb | VCloudClient.Connection.get_vapp_by_name | def get_vapp_by_name(organization, vdcName, vAppName)
result = nil
get_vdc_by_name(organization, vdcName)[:vapps].each do |vapp|
if vapp[0].downcase == vAppName.downcase
result = get_vapp(vapp[1])
end
end
result
end | ruby | def get_vapp_by_name(organization, vdcName, vAppName)
result = nil
get_vdc_by_name(organization, vdcName)[:vapps].each do |vapp|
if vapp[0].downcase == vAppName.downcase
result = get_vapp(vapp[1])
end
end
result
end | [
"def",
"get_vapp_by_name",
"(",
"organization",
",",
"vdcName",
",",
"vAppName",
")",
"result",
"=",
"nil",
"get_vdc_by_name",
"(",
"organization",
",",
"vdcName",
")",
"[",
":vapps",
"]",
".",
"each",
"do",
"|",
"vapp",
"|",
"if",
"vapp",
"[",
"0",
"]",... | Friendly helper method to fetch a vApp by name
- Organization object
- Organization VDC Name
- vApp name | [
"Friendly",
"helper",
"method",
"to",
"fetch",
"a",
"vApp",
"by",
"name",
"-",
"Organization",
"object",
"-",
"Organization",
"VDC",
"Name",
"-",
"vApp",
"name"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp.rb#L117-L127 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vapp.rb | VCloudClient.Connection.poweroff_vapp | def poweroff_vapp(vAppId)
builder = Nokogiri::XML::Builder.new do |xml|
xml.UndeployVAppParams(
"xmlns" => "http://www.vmware.com/vcloud/v1.5") {
xml.UndeployPowerAction 'powerOff'
}
end
params = {
'method' => :post,
'command' => "/vApp/vapp-#{vAppId}/action/undeploy"
}
response, headers = send_request(params, builder.to_xml,
"application/vnd.vmware.vcloud.undeployVAppParams+xml")
task_id = headers[:location].gsub(/.*\/task\//, "")
task_id
end | ruby | def poweroff_vapp(vAppId)
builder = Nokogiri::XML::Builder.new do |xml|
xml.UndeployVAppParams(
"xmlns" => "http://www.vmware.com/vcloud/v1.5") {
xml.UndeployPowerAction 'powerOff'
}
end
params = {
'method' => :post,
'command' => "/vApp/vapp-#{vAppId}/action/undeploy"
}
response, headers = send_request(params, builder.to_xml,
"application/vnd.vmware.vcloud.undeployVAppParams+xml")
task_id = headers[:location].gsub(/.*\/task\//, "")
task_id
end | [
"def",
"poweroff_vapp",
"(",
"vAppId",
")",
"builder",
"=",
"Nokogiri",
"::",
"XML",
"::",
"Builder",
".",
"new",
"do",
"|",
"xml",
"|",
"xml",
".",
"UndeployVAppParams",
"(",
"\"xmlns\"",
"=>",
"\"http://www.vmware.com/vcloud/v1.5\"",
")",
"{",
"xml",
".",
... | Shutdown a given vapp | [
"Shutdown",
"a",
"given",
"vapp"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp.rb#L145-L162 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vapp.rb | VCloudClient.Connection.create_vapp_from_template | def create_vapp_from_template(vdc, vapp_name, vapp_description, vapp_templateid, poweron=false)
builder = Nokogiri::XML::Builder.new do |xml|
xml.InstantiateVAppTemplateParams(
"xmlns" => "http://www.vmware.com/vcloud/v1.5",
"xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance",
"xmlns:ovf" => "http://schemas.dmtf.org/ovf/envelope/1",
"name" => vapp_name,
"deploy" => "true",
"powerOn" => poweron) {
xml.Description vapp_description
xml.Source("href" => "#{@api_url}/vAppTemplate/#{vapp_templateid}")
}
end
params = {
"method" => :post,
"command" => "/vdc/#{vdc}/action/instantiateVAppTemplate"
}
response, headers = send_request(params, builder.to_xml, "application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml")
vapp_id = headers[:location].gsub(/.*\/vApp\/vapp\-/, "")
task = response.css("VApp Task[operationName='vdcInstantiateVapp']").first
task_id = task["href"].gsub(/.*\/task\//, "")
{ :vapp_id => vapp_id, :task_id => task_id }
end | ruby | def create_vapp_from_template(vdc, vapp_name, vapp_description, vapp_templateid, poweron=false)
builder = Nokogiri::XML::Builder.new do |xml|
xml.InstantiateVAppTemplateParams(
"xmlns" => "http://www.vmware.com/vcloud/v1.5",
"xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance",
"xmlns:ovf" => "http://schemas.dmtf.org/ovf/envelope/1",
"name" => vapp_name,
"deploy" => "true",
"powerOn" => poweron) {
xml.Description vapp_description
xml.Source("href" => "#{@api_url}/vAppTemplate/#{vapp_templateid}")
}
end
params = {
"method" => :post,
"command" => "/vdc/#{vdc}/action/instantiateVAppTemplate"
}
response, headers = send_request(params, builder.to_xml, "application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml")
vapp_id = headers[:location].gsub(/.*\/vApp\/vapp\-/, "")
task = response.css("VApp Task[operationName='vdcInstantiateVapp']").first
task_id = task["href"].gsub(/.*\/task\//, "")
{ :vapp_id => vapp_id, :task_id => task_id }
end | [
"def",
"create_vapp_from_template",
"(",
"vdc",
",",
"vapp_name",
",",
"vapp_description",
",",
"vapp_templateid",
",",
"poweron",
"=",
"false",
")",
"builder",
"=",
"Nokogiri",
"::",
"XML",
"::",
"Builder",
".",
"new",
"do",
"|",
"xml",
"|",
"xml",
".",
"... | Create a vapp starting from a template
Params:
- vdc: the associated VDC
- vapp_name: name of the target vapp
- vapp_description: description of the target vapp
- vapp_templateid: ID of the vapp template | [
"Create",
"a",
"vapp",
"starting",
"from",
"a",
"template"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp.rb#L207-L233 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vapp.rb | VCloudClient.Connection.compose_vapp_from_vm | def compose_vapp_from_vm(vdc, vapp_name, vapp_description, vm_list={}, network_config={})
builder = Nokogiri::XML::Builder.new do |xml|
xml.ComposeVAppParams(
"xmlns" => "http://www.vmware.com/vcloud/v1.5",
"xmlns:ovf" => "http://schemas.dmtf.org/ovf/envelope/1",
"name" => vapp_name) {
xml.Description vapp_description
xml.InstantiationParams {
xml.NetworkConfigSection {
xml['ovf'].Info "Configuration parameters for logical networks"
xml.NetworkConfig("networkName" => network_config[:name]) {
xml.Configuration {
xml.IpScopes {
xml.IpScope {
xml.IsInherited(network_config[:is_inherited] || "false")
xml.Gateway network_config[:gateway]
xml.Netmask network_config[:netmask]
xml.Dns1 network_config[:dns1] if network_config[:dns1]
xml.Dns2 network_config[:dns2] if network_config[:dns2]
xml.DnsSuffix network_config[:dns_suffix] if network_config[:dns_suffix]
xml.IpRanges {
xml.IpRange {
xml.StartAddress network_config[:start_address]
xml.EndAddress network_config[:end_address]
}
}
}
}
xml.ParentNetwork("href" => "#{@api_url}/network/#{network_config[:parent_network]}")
xml.FenceMode network_config[:fence_mode]
xml.Features {
xml.FirewallService {
xml.IsEnabled(network_config[:enable_firewall] || "false")
}
if network_config.has_key? :nat_type
xml.NatService {
xml.IsEnabled "true"
xml.NatType network_config[:nat_type]
xml.Policy(network_config[:nat_policy_type] || "allowTraffic")
}
end
}
}
}
}
}
vm_list.each do |vm_name, vm_id|
xml.SourcedItem {
xml.Source("href" => "#{@api_url}/vAppTemplate/vm-#{vm_id}", "name" => vm_name)
xml.InstantiationParams {
xml.NetworkConnectionSection(
"xmlns:ovf" => "http://schemas.dmtf.org/ovf/envelope/1",
"type" => "application/vnd.vmware.vcloud.networkConnectionSection+xml",
"href" => "#{@api_url}/vAppTemplate/vm-#{vm_id}/networkConnectionSection/") {
xml['ovf'].Info "Network config for sourced item"
xml.PrimaryNetworkConnectionIndex "0"
xml.NetworkConnection("network" => network_config[:name]) {
xml.NetworkConnectionIndex "0"
xml.IsConnected "true"
xml.IpAddressAllocationMode(network_config[:ip_allocation_mode] || "POOL")
}
}
}
xml.NetworkAssignment("containerNetwork" => network_config[:name], "innerNetwork" => network_config[:name])
}
end
xml.AllEULAsAccepted "true"
}
end
params = {
"method" => :post,
"command" => "/vdc/#{vdc}/action/composeVApp"
}
response, headers = send_request(params, builder.to_xml, "application/vnd.vmware.vcloud.composeVAppParams+xml")
vapp_id = headers[:location].gsub(/.*\/vApp\/vapp\-/, "")
task = response.css("VApp Task[operationName='vdcComposeVapp']").first
task_id = task["href"].gsub(/.*\/task\//, "")
{ :vapp_id => vapp_id, :task_id => task_id }
end | ruby | def compose_vapp_from_vm(vdc, vapp_name, vapp_description, vm_list={}, network_config={})
builder = Nokogiri::XML::Builder.new do |xml|
xml.ComposeVAppParams(
"xmlns" => "http://www.vmware.com/vcloud/v1.5",
"xmlns:ovf" => "http://schemas.dmtf.org/ovf/envelope/1",
"name" => vapp_name) {
xml.Description vapp_description
xml.InstantiationParams {
xml.NetworkConfigSection {
xml['ovf'].Info "Configuration parameters for logical networks"
xml.NetworkConfig("networkName" => network_config[:name]) {
xml.Configuration {
xml.IpScopes {
xml.IpScope {
xml.IsInherited(network_config[:is_inherited] || "false")
xml.Gateway network_config[:gateway]
xml.Netmask network_config[:netmask]
xml.Dns1 network_config[:dns1] if network_config[:dns1]
xml.Dns2 network_config[:dns2] if network_config[:dns2]
xml.DnsSuffix network_config[:dns_suffix] if network_config[:dns_suffix]
xml.IpRanges {
xml.IpRange {
xml.StartAddress network_config[:start_address]
xml.EndAddress network_config[:end_address]
}
}
}
}
xml.ParentNetwork("href" => "#{@api_url}/network/#{network_config[:parent_network]}")
xml.FenceMode network_config[:fence_mode]
xml.Features {
xml.FirewallService {
xml.IsEnabled(network_config[:enable_firewall] || "false")
}
if network_config.has_key? :nat_type
xml.NatService {
xml.IsEnabled "true"
xml.NatType network_config[:nat_type]
xml.Policy(network_config[:nat_policy_type] || "allowTraffic")
}
end
}
}
}
}
}
vm_list.each do |vm_name, vm_id|
xml.SourcedItem {
xml.Source("href" => "#{@api_url}/vAppTemplate/vm-#{vm_id}", "name" => vm_name)
xml.InstantiationParams {
xml.NetworkConnectionSection(
"xmlns:ovf" => "http://schemas.dmtf.org/ovf/envelope/1",
"type" => "application/vnd.vmware.vcloud.networkConnectionSection+xml",
"href" => "#{@api_url}/vAppTemplate/vm-#{vm_id}/networkConnectionSection/") {
xml['ovf'].Info "Network config for sourced item"
xml.PrimaryNetworkConnectionIndex "0"
xml.NetworkConnection("network" => network_config[:name]) {
xml.NetworkConnectionIndex "0"
xml.IsConnected "true"
xml.IpAddressAllocationMode(network_config[:ip_allocation_mode] || "POOL")
}
}
}
xml.NetworkAssignment("containerNetwork" => network_config[:name], "innerNetwork" => network_config[:name])
}
end
xml.AllEULAsAccepted "true"
}
end
params = {
"method" => :post,
"command" => "/vdc/#{vdc}/action/composeVApp"
}
response, headers = send_request(params, builder.to_xml, "application/vnd.vmware.vcloud.composeVAppParams+xml")
vapp_id = headers[:location].gsub(/.*\/vApp\/vapp\-/, "")
task = response.css("VApp Task[operationName='vdcComposeVapp']").first
task_id = task["href"].gsub(/.*\/task\//, "")
{ :vapp_id => vapp_id, :task_id => task_id }
end | [
"def",
"compose_vapp_from_vm",
"(",
"vdc",
",",
"vapp_name",
",",
"vapp_description",
",",
"vm_list",
"=",
"{",
"}",
",",
"network_config",
"=",
"{",
"}",
")",
"builder",
"=",
"Nokogiri",
"::",
"XML",
"::",
"Builder",
".",
"new",
"do",
"|",
"xml",
"|",
... | Compose a vapp using existing virtual machines
Params:
- vdc: the associated VDC
- vapp_name: name of the target vapp
- vapp_description: description of the target vapp
- vm_list: hash with IDs of the VMs to be used in the composing process
- network_config: hash of the network configuration for the vapp | [
"Compose",
"a",
"vapp",
"using",
"existing",
"virtual",
"machines"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp.rb#L244-L328 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vapp.rb | VCloudClient.Connection.add_vm_to_vapp | def add_vm_to_vapp(vapp, vm, network_config={})
builder = Nokogiri::XML::Builder.new do |xml|
xml.RecomposeVAppParams(
"xmlns" => "http://www.vmware.com/vcloud/v1.5",
"xmlns:ovf" => "http://schemas.dmtf.org/ovf/envelope/1",
"name" => vapp[:name]) {
xml.SourcedItem {
xml.Source("href" => "#{@api_url}/vAppTemplate/vm-#{vm[:template_id]}", "name" => vm[:vm_name])
xml.InstantiationParams {
xml.NetworkConnectionSection(
"xmlns:ovf" => "http://schemas.dmtf.org/ovf/envelope/1",
"type" => "application/vnd.vmware.vcloud.networkConnectionSection+xml",
"href" => "#{@api_url}/vAppTemplate/vm-#{vm[:template_id]}/networkConnectionSection/") {
xml['ovf'].Info "Network config for sourced item"
xml.PrimaryNetworkConnectionIndex "0"
xml.NetworkConnection("network" => network_config[:name]) {
xml.NetworkConnectionIndex "0"
xml.IsConnected "true"
xml.IpAddressAllocationMode(network_config[:ip_allocation_mode] || "POOL")
}
}
}
xml.NetworkAssignment("containerNetwork" => network_config[:name], "innerNetwork" => network_config[:name])
}
xml.AllEULAsAccepted "true"
}
end
params = {
"method" => :post,
"command" => "/vApp/vapp-#{vapp[:id]}/action/recomposeVApp"
}
response, headers = send_request(params, builder.to_xml, "application/vnd.vmware.vcloud.recomposeVAppParams+xml")
task = response.css("Task[operationName='vdcRecomposeVapp']").first
task_id = task["href"].gsub(/.*\/task\//, "")
task_id
end | ruby | def add_vm_to_vapp(vapp, vm, network_config={})
builder = Nokogiri::XML::Builder.new do |xml|
xml.RecomposeVAppParams(
"xmlns" => "http://www.vmware.com/vcloud/v1.5",
"xmlns:ovf" => "http://schemas.dmtf.org/ovf/envelope/1",
"name" => vapp[:name]) {
xml.SourcedItem {
xml.Source("href" => "#{@api_url}/vAppTemplate/vm-#{vm[:template_id]}", "name" => vm[:vm_name])
xml.InstantiationParams {
xml.NetworkConnectionSection(
"xmlns:ovf" => "http://schemas.dmtf.org/ovf/envelope/1",
"type" => "application/vnd.vmware.vcloud.networkConnectionSection+xml",
"href" => "#{@api_url}/vAppTemplate/vm-#{vm[:template_id]}/networkConnectionSection/") {
xml['ovf'].Info "Network config for sourced item"
xml.PrimaryNetworkConnectionIndex "0"
xml.NetworkConnection("network" => network_config[:name]) {
xml.NetworkConnectionIndex "0"
xml.IsConnected "true"
xml.IpAddressAllocationMode(network_config[:ip_allocation_mode] || "POOL")
}
}
}
xml.NetworkAssignment("containerNetwork" => network_config[:name], "innerNetwork" => network_config[:name])
}
xml.AllEULAsAccepted "true"
}
end
params = {
"method" => :post,
"command" => "/vApp/vapp-#{vapp[:id]}/action/recomposeVApp"
}
response, headers = send_request(params, builder.to_xml, "application/vnd.vmware.vcloud.recomposeVAppParams+xml")
task = response.css("Task[operationName='vdcRecomposeVapp']").first
task_id = task["href"].gsub(/.*\/task\//, "")
task_id
end | [
"def",
"add_vm_to_vapp",
"(",
"vapp",
",",
"vm",
",",
"network_config",
"=",
"{",
"}",
")",
"builder",
"=",
"Nokogiri",
"::",
"XML",
"::",
"Builder",
".",
"new",
"do",
"|",
"xml",
"|",
"xml",
".",
"RecomposeVAppParams",
"(",
"\"xmlns\"",
"=>",
"\"http://... | Create a new virtual machine from a template in an existing vApp.
Params:
- vapp: the target vapp
- vm: hash with template ID and new VM name
- network_config: hash of the network configuration for the VM | [
"Create",
"a",
"new",
"virtual",
"machine",
"from",
"a",
"template",
"in",
"an",
"existing",
"vApp",
"."
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp.rb#L337-L375 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vapp.rb | VCloudClient.Connection.clone_vapp | def clone_vapp(vdc_id, source_vapp_id, name, deploy="true", poweron="false", linked="false", delete_source="false")
params = {
"method" => :post,
"command" => "/vdc/#{vdc_id}/action/cloneVApp"
}
builder = Nokogiri::XML::Builder.new do |xml|
xml.CloneVAppParams(
"xmlns" => "http://www.vmware.com/vcloud/v1.5",
"name" => name,
"deploy"=> deploy,
"linkedClone"=> linked,
"powerOn"=> poweron
) {
xml.Source "href" => "#{@api_url}/vApp/vapp-#{source_vapp_id}"
xml.IsSourceDelete delete_source
}
end
response, headers = send_request(params, builder.to_xml, "application/vnd.vmware.vcloud.cloneVAppParams+xml")
vapp_id = headers[:location].gsub(/.*\/vApp\/vapp\-/, "")
task = response.css("VApp Task[operationName='vdcCopyVapp']").first
task_id = task["href"].gsub(/.*\/task\//, "")
{:vapp_id => vapp_id, :task_id => task_id}
end | ruby | def clone_vapp(vdc_id, source_vapp_id, name, deploy="true", poweron="false", linked="false", delete_source="false")
params = {
"method" => :post,
"command" => "/vdc/#{vdc_id}/action/cloneVApp"
}
builder = Nokogiri::XML::Builder.new do |xml|
xml.CloneVAppParams(
"xmlns" => "http://www.vmware.com/vcloud/v1.5",
"name" => name,
"deploy"=> deploy,
"linkedClone"=> linked,
"powerOn"=> poweron
) {
xml.Source "href" => "#{@api_url}/vApp/vapp-#{source_vapp_id}"
xml.IsSourceDelete delete_source
}
end
response, headers = send_request(params, builder.to_xml, "application/vnd.vmware.vcloud.cloneVAppParams+xml")
vapp_id = headers[:location].gsub(/.*\/vApp\/vapp\-/, "")
task = response.css("VApp Task[operationName='vdcCopyVapp']").first
task_id = task["href"].gsub(/.*\/task\//, "")
{:vapp_id => vapp_id, :task_id => task_id}
end | [
"def",
"clone_vapp",
"(",
"vdc_id",
",",
"source_vapp_id",
",",
"name",
",",
"deploy",
"=",
"\"true\"",
",",
"poweron",
"=",
"\"false\"",
",",
"linked",
"=",
"\"false\"",
",",
"delete_source",
"=",
"\"false\"",
")",
"params",
"=",
"{",
"\"method\"",
"=>",
... | Clone a vapp in a given VDC to a new Vapp | [
"Clone",
"a",
"vapp",
"in",
"a",
"given",
"VDC",
"to",
"a",
"new",
"Vapp"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp.rb#L413-L438 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vapp_networking.rb | VCloudClient.Connection.set_vapp_network_config | def set_vapp_network_config(vappid, network, config={})
params = {
'method' => :get,
'command' => "/vApp/vapp-#{vappid}/networkConfigSection"
}
netconfig_response, headers = send_request(params)
picked_network = netconfig_response.css("NetworkConfig").select do |net|
net.attribute('networkName').text == network[:name]
end.first
raise WrongItemIDError, "Network named #{network[:name]} not found." unless picked_network
picked_network.css('FenceMode').first.content = config[:fence_mode] if config[:fence_mode]
picked_network.css('IsInherited').first.content = "true"
picked_network.css('RetainNetInfoAcrossDeployments').first.content = config[:retain_network] if config[:retain_network]
if config[:parent_network]
parent_network = picked_network.css('ParentNetwork').first
new_parent = false
unless parent_network
new_parent = true
ipscopes = picked_network.css('IpScopes').first
parent_network = Nokogiri::XML::Node.new "ParentNetwork", ipscopes.parent
end
parent_network["name"] = "#{config[:parent_network][:name]}"
parent_network["id"] = "#{config[:parent_network][:id]}"
parent_network["href"] = "#{@api_url}/admin/network/#{config[:parent_network][:id]}"
ipscopes.add_next_sibling(parent_network) if new_parent
end
data = netconfig_response.to_xml
params = {
'method' => :put,
'command' => "/vApp/vapp-#{vappid}/networkConfigSection"
}
response, headers = send_request(params, data, "application/vnd.vmware.vcloud.networkConfigSection+xml")
task_id = headers[:location].gsub(/.*\/task\//, "")
task_id
end | ruby | def set_vapp_network_config(vappid, network, config={})
params = {
'method' => :get,
'command' => "/vApp/vapp-#{vappid}/networkConfigSection"
}
netconfig_response, headers = send_request(params)
picked_network = netconfig_response.css("NetworkConfig").select do |net|
net.attribute('networkName').text == network[:name]
end.first
raise WrongItemIDError, "Network named #{network[:name]} not found." unless picked_network
picked_network.css('FenceMode').first.content = config[:fence_mode] if config[:fence_mode]
picked_network.css('IsInherited').first.content = "true"
picked_network.css('RetainNetInfoAcrossDeployments').first.content = config[:retain_network] if config[:retain_network]
if config[:parent_network]
parent_network = picked_network.css('ParentNetwork').first
new_parent = false
unless parent_network
new_parent = true
ipscopes = picked_network.css('IpScopes').first
parent_network = Nokogiri::XML::Node.new "ParentNetwork", ipscopes.parent
end
parent_network["name"] = "#{config[:parent_network][:name]}"
parent_network["id"] = "#{config[:parent_network][:id]}"
parent_network["href"] = "#{@api_url}/admin/network/#{config[:parent_network][:id]}"
ipscopes.add_next_sibling(parent_network) if new_parent
end
data = netconfig_response.to_xml
params = {
'method' => :put,
'command' => "/vApp/vapp-#{vappid}/networkConfigSection"
}
response, headers = send_request(params, data, "application/vnd.vmware.vcloud.networkConfigSection+xml")
task_id = headers[:location].gsub(/.*\/task\//, "")
task_id
end | [
"def",
"set_vapp_network_config",
"(",
"vappid",
",",
"network",
",",
"config",
"=",
"{",
"}",
")",
"params",
"=",
"{",
"'method'",
"=>",
":get",
",",
"'command'",
"=>",
"\"/vApp/vapp-#{vappid}/networkConfigSection\"",
"}",
"netconfig_response",
",",
"headers",
"=... | Set vApp Network Config
Retrieve the existing network config section and edit it
to ensure settings are not lost | [
"Set",
"vApp",
"Network",
"Config"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp_networking.rb#L8-L53 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vapp_networking.rb | VCloudClient.Connection.set_vapp_port_forwarding_rules | def set_vapp_port_forwarding_rules(vappid, network_name, config={})
builder = Nokogiri::XML::Builder.new do |xml|
xml.NetworkConfigSection(
"xmlns" => "http://www.vmware.com/vcloud/v1.5",
"xmlns:ovf" => "http://schemas.dmtf.org/ovf/envelope/1") {
xml['ovf'].Info "Network configuration"
xml.NetworkConfig("networkName" => network_name) {
xml.Configuration {
xml.ParentNetwork("href" => "#{@api_url}/network/#{config[:parent_network]}")
xml.FenceMode(config[:fence_mode] || 'isolated')
xml.Features {
xml.NatService {
xml.IsEnabled "true"
xml.NatType "portForwarding"
xml.Policy(config[:nat_policy_type] || "allowTraffic")
config[:nat_rules].each do |nat_rule|
xml.NatRule {
xml.VmRule {
xml.ExternalPort nat_rule[:nat_external_port]
xml.VAppScopedVmId nat_rule[:vm_scoped_local_id]
xml.VmNicId(nat_rule[:nat_vmnic_id] || "0")
xml.InternalPort nat_rule[:nat_internal_port]
xml.Protocol(nat_rule[:nat_protocol] || "TCP")
}
}
end
}
}
}
}
}
end
params = {
'method' => :put,
'command' => "/vApp/vapp-#{vappid}/networkConfigSection"
}
response, headers = send_request(params, builder.to_xml, "application/vnd.vmware.vcloud.networkConfigSection+xml")
task_id = headers[:location].gsub(/.*\/task\//, "")
task_id
end | ruby | def set_vapp_port_forwarding_rules(vappid, network_name, config={})
builder = Nokogiri::XML::Builder.new do |xml|
xml.NetworkConfigSection(
"xmlns" => "http://www.vmware.com/vcloud/v1.5",
"xmlns:ovf" => "http://schemas.dmtf.org/ovf/envelope/1") {
xml['ovf'].Info "Network configuration"
xml.NetworkConfig("networkName" => network_name) {
xml.Configuration {
xml.ParentNetwork("href" => "#{@api_url}/network/#{config[:parent_network]}")
xml.FenceMode(config[:fence_mode] || 'isolated')
xml.Features {
xml.NatService {
xml.IsEnabled "true"
xml.NatType "portForwarding"
xml.Policy(config[:nat_policy_type] || "allowTraffic")
config[:nat_rules].each do |nat_rule|
xml.NatRule {
xml.VmRule {
xml.ExternalPort nat_rule[:nat_external_port]
xml.VAppScopedVmId nat_rule[:vm_scoped_local_id]
xml.VmNicId(nat_rule[:nat_vmnic_id] || "0")
xml.InternalPort nat_rule[:nat_internal_port]
xml.Protocol(nat_rule[:nat_protocol] || "TCP")
}
}
end
}
}
}
}
}
end
params = {
'method' => :put,
'command' => "/vApp/vapp-#{vappid}/networkConfigSection"
}
response, headers = send_request(params, builder.to_xml, "application/vnd.vmware.vcloud.networkConfigSection+xml")
task_id = headers[:location].gsub(/.*\/task\//, "")
task_id
end | [
"def",
"set_vapp_port_forwarding_rules",
"(",
"vappid",
",",
"network_name",
",",
"config",
"=",
"{",
"}",
")",
"builder",
"=",
"Nokogiri",
"::",
"XML",
"::",
"Builder",
".",
"new",
"do",
"|",
"xml",
"|",
"xml",
".",
"NetworkConfigSection",
"(",
"\"xmlns\"",... | Set vApp port forwarding rules
- vappid: id of the vapp to be modified
- network_name: name of the vapp network to be modified
- config: hash with network configuration specifications, must contain an array inside :nat_rules with the nat rules to be applied. | [
"Set",
"vApp",
"port",
"forwarding",
"rules"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp_networking.rb#L107-L149 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vapp_networking.rb | VCloudClient.Connection.get_vapp_port_forwarding_rules | def get_vapp_port_forwarding_rules(vAppId)
params = {
'method' => :get,
'command' => "/vApp/vapp-#{vAppId}/networkConfigSection"
}
response, headers = send_request(params)
# FIXME: this will return nil if the vApp uses multiple vApp Networks
# with Edge devices in natRouted/portForwarding mode.
config = response.css('NetworkConfigSection/NetworkConfig/Configuration')
fenceMode = config.css('/FenceMode').text
natType = config.css('/Features/NatService/NatType').text
raise InvalidStateError, "Invalid request because FenceMode must be set to natRouted." unless fenceMode == "natRouted"
raise InvalidStateError, "Invalid request because NatType must be set to portForwarding." unless natType == "portForwarding"
nat_rules = {}
config.css('/Features/NatService/NatRule').each do |rule|
# portforwarding rules information
ruleId = rule.css('Id').text
vmRule = rule.css('VmRule')
nat_rules[rule.css('Id').text] = {
:ExternalIpAddress => vmRule.css('ExternalIpAddress').text,
:ExternalPort => vmRule.css('ExternalPort').text,
:VAppScopedVmId => vmRule.css('VAppScopedVmId').text,
:VmNicId => vmRule.css('VmNicId').text,
:InternalPort => vmRule.css('InternalPort').text,
:Protocol => vmRule.css('Protocol').text
}
end
nat_rules
end | ruby | def get_vapp_port_forwarding_rules(vAppId)
params = {
'method' => :get,
'command' => "/vApp/vapp-#{vAppId}/networkConfigSection"
}
response, headers = send_request(params)
# FIXME: this will return nil if the vApp uses multiple vApp Networks
# with Edge devices in natRouted/portForwarding mode.
config = response.css('NetworkConfigSection/NetworkConfig/Configuration')
fenceMode = config.css('/FenceMode').text
natType = config.css('/Features/NatService/NatType').text
raise InvalidStateError, "Invalid request because FenceMode must be set to natRouted." unless fenceMode == "natRouted"
raise InvalidStateError, "Invalid request because NatType must be set to portForwarding." unless natType == "portForwarding"
nat_rules = {}
config.css('/Features/NatService/NatRule').each do |rule|
# portforwarding rules information
ruleId = rule.css('Id').text
vmRule = rule.css('VmRule')
nat_rules[rule.css('Id').text] = {
:ExternalIpAddress => vmRule.css('ExternalIpAddress').text,
:ExternalPort => vmRule.css('ExternalPort').text,
:VAppScopedVmId => vmRule.css('VAppScopedVmId').text,
:VmNicId => vmRule.css('VmNicId').text,
:InternalPort => vmRule.css('InternalPort').text,
:Protocol => vmRule.css('Protocol').text
}
end
nat_rules
end | [
"def",
"get_vapp_port_forwarding_rules",
"(",
"vAppId",
")",
"params",
"=",
"{",
"'method'",
"=>",
":get",
",",
"'command'",
"=>",
"\"/vApp/vapp-#{vAppId}/networkConfigSection\"",
"}",
"response",
",",
"headers",
"=",
"send_request",
"(",
"params",
")",
"config",
"=... | Get vApp port forwarding rules
- vappid: id of the vApp | [
"Get",
"vApp",
"port",
"forwarding",
"rules"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp_networking.rb#L155-L188 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vapp_networking.rb | VCloudClient.Connection.merge_network_config | def merge_network_config(vapp_networks, new_network, config)
net_configuration = new_network.css('Configuration').first
fence_mode = new_network.css('FenceMode').first
fence_mode.content = config[:fence_mode] || 'isolated'
network_features = Nokogiri::XML::Node.new "Features", net_configuration
firewall_service = Nokogiri::XML::Node.new "FirewallService", network_features
firewall_enabled = Nokogiri::XML::Node.new "IsEnabled", firewall_service
firewall_enabled.content = config[:firewall_enabled] || "false"
firewall_service.add_child(firewall_enabled)
network_features.add_child(firewall_service)
net_configuration.add_child(network_features)
if config[:parent_network]
# At this stage, set itself as parent network
parent_network = Nokogiri::XML::Node.new "ParentNetwork", net_configuration
parent_network["href"] = "#{@api_url}/network/#{config[:parent_network][:id]}"
parent_network["name"] = config[:parent_network][:name]
parent_network["type"] = "application/vnd.vmware.vcloud.network+xml"
new_network.css('IpScopes').first.add_next_sibling(parent_network)
end
vapp_networks.to_xml.gsub("<PLACEHOLDER/>", new_network.css('Configuration').to_xml)
end | ruby | def merge_network_config(vapp_networks, new_network, config)
net_configuration = new_network.css('Configuration').first
fence_mode = new_network.css('FenceMode').first
fence_mode.content = config[:fence_mode] || 'isolated'
network_features = Nokogiri::XML::Node.new "Features", net_configuration
firewall_service = Nokogiri::XML::Node.new "FirewallService", network_features
firewall_enabled = Nokogiri::XML::Node.new "IsEnabled", firewall_service
firewall_enabled.content = config[:firewall_enabled] || "false"
firewall_service.add_child(firewall_enabled)
network_features.add_child(firewall_service)
net_configuration.add_child(network_features)
if config[:parent_network]
# At this stage, set itself as parent network
parent_network = Nokogiri::XML::Node.new "ParentNetwork", net_configuration
parent_network["href"] = "#{@api_url}/network/#{config[:parent_network][:id]}"
parent_network["name"] = config[:parent_network][:name]
parent_network["type"] = "application/vnd.vmware.vcloud.network+xml"
new_network.css('IpScopes').first.add_next_sibling(parent_network)
end
vapp_networks.to_xml.gsub("<PLACEHOLDER/>", new_network.css('Configuration').to_xml)
end | [
"def",
"merge_network_config",
"(",
"vapp_networks",
",",
"new_network",
",",
"config",
")",
"net_configuration",
"=",
"new_network",
".",
"css",
"(",
"'Configuration'",
")",
".",
"first",
"fence_mode",
"=",
"new_network",
".",
"css",
"(",
"'FenceMode'",
")",
".... | Merge the Configuration section of a new network and add specific configuration | [
"Merge",
"the",
"Configuration",
"section",
"of",
"a",
"new",
"network",
"and",
"add",
"specific",
"configuration"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp_networking.rb#L224-L249 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vapp_networking.rb | VCloudClient.Connection.add_network_to_vapp | def add_network_to_vapp(vAppId, network_section)
params = {
'method' => :put,
'command' => "/vApp/vapp-#{vAppId}/networkConfigSection"
}
response, headers = send_request(params, network_section, "application/vnd.vmware.vcloud.networkConfigSection+xml")
task_id = headers[:location].gsub(/.*\/task\//, "")
task_id
end | ruby | def add_network_to_vapp(vAppId, network_section)
params = {
'method' => :put,
'command' => "/vApp/vapp-#{vAppId}/networkConfigSection"
}
response, headers = send_request(params, network_section, "application/vnd.vmware.vcloud.networkConfigSection+xml")
task_id = headers[:location].gsub(/.*\/task\//, "")
task_id
end | [
"def",
"add_network_to_vapp",
"(",
"vAppId",
",",
"network_section",
")",
"params",
"=",
"{",
"'method'",
"=>",
":put",
",",
"'command'",
"=>",
"\"/vApp/vapp-#{vAppId}/networkConfigSection\"",
"}",
"response",
",",
"headers",
"=",
"send_request",
"(",
"params",
",",... | Add a new network to a vApp | [
"Add",
"a",
"new",
"network",
"to",
"a",
"vApp"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp_networking.rb#L253-L263 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vapp_networking.rb | VCloudClient.Connection.create_fake_network_node | def create_fake_network_node(vapp_networks, network_name)
parent_section = vapp_networks.css('NetworkConfigSection').first
new_network = Nokogiri::XML::Node.new "NetworkConfig", parent_section
new_network['networkName'] = network_name
placeholder = Nokogiri::XML::Node.new "PLACEHOLDER", new_network
new_network.add_child placeholder
parent_section.add_child(new_network)
vapp_networks
end | ruby | def create_fake_network_node(vapp_networks, network_name)
parent_section = vapp_networks.css('NetworkConfigSection').first
new_network = Nokogiri::XML::Node.new "NetworkConfig", parent_section
new_network['networkName'] = network_name
placeholder = Nokogiri::XML::Node.new "PLACEHOLDER", new_network
new_network.add_child placeholder
parent_section.add_child(new_network)
vapp_networks
end | [
"def",
"create_fake_network_node",
"(",
"vapp_networks",
",",
"network_name",
")",
"parent_section",
"=",
"vapp_networks",
".",
"css",
"(",
"'NetworkConfigSection'",
")",
".",
"first",
"new_network",
"=",
"Nokogiri",
"::",
"XML",
"::",
"Node",
".",
"new",
"\"Netwo... | Create a fake NetworkConfig node whose content will be replaced later
Note: this is a hack to avoid wrong merges through Nokogiri
that would add a default: namespace | [
"Create",
"a",
"fake",
"NetworkConfig",
"node",
"whose",
"content",
"will",
"be",
"replaced",
"later"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp_networking.rb#L270-L278 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vapp_networking.rb | VCloudClient.Connection.create_internal_network_node | def create_internal_network_node(network_config)
builder = Nokogiri::XML::Builder.new do |xml|
xml.Configuration {
xml.IpScopes {
xml.IpScope {
xml.IsInherited(network_config[:is_inherited] || "false")
xml.Gateway network_config[:gateway]
xml.Netmask network_config[:netmask]
xml.Dns1 network_config[:dns1] if network_config[:dns1]
xml.Dns2 network_config[:dns2] if network_config[:dns2]
xml.DnsSuffix network_config[:dns_suffix] if network_config[:dns_suffix]
xml.IsEnabled(network_config[:is_enabled] || true)
xml.IpRanges {
xml.IpRange {
xml.StartAddress network_config[:start_address]
xml.EndAddress network_config[:end_address]
}
}
}
}
xml.FenceMode 'isolated'
xml.RetainNetInfoAcrossDeployments(network_config[:retain_info] || false)
}
end
builder.doc
end | ruby | def create_internal_network_node(network_config)
builder = Nokogiri::XML::Builder.new do |xml|
xml.Configuration {
xml.IpScopes {
xml.IpScope {
xml.IsInherited(network_config[:is_inherited] || "false")
xml.Gateway network_config[:gateway]
xml.Netmask network_config[:netmask]
xml.Dns1 network_config[:dns1] if network_config[:dns1]
xml.Dns2 network_config[:dns2] if network_config[:dns2]
xml.DnsSuffix network_config[:dns_suffix] if network_config[:dns_suffix]
xml.IsEnabled(network_config[:is_enabled] || true)
xml.IpRanges {
xml.IpRange {
xml.StartAddress network_config[:start_address]
xml.EndAddress network_config[:end_address]
}
}
}
}
xml.FenceMode 'isolated'
xml.RetainNetInfoAcrossDeployments(network_config[:retain_info] || false)
}
end
builder.doc
end | [
"def",
"create_internal_network_node",
"(",
"network_config",
")",
"builder",
"=",
"Nokogiri",
"::",
"XML",
"::",
"Builder",
".",
"new",
"do",
"|",
"xml",
"|",
"xml",
".",
"Configuration",
"{",
"xml",
".",
"IpScopes",
"{",
"xml",
".",
"IpScope",
"{",
"xml"... | Create a fake Configuration node for internal networking | [
"Create",
"a",
"fake",
"Configuration",
"node",
"for",
"internal",
"networking"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp_networking.rb#L282-L307 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vapp_networking.rb | VCloudClient.Connection.generate_network_section | def generate_network_section(vAppId, network, config, type)
params = {
'method' => :get,
'command' => "/vApp/vapp-#{vAppId}/networkConfigSection"
}
vapp_networks, headers = send_request(params)
create_fake_network_node(vapp_networks, network[:name])
if type.to_sym == :internal
# Create a network configuration based on the config
new_network = create_internal_network_node(config)
else
# Retrieve the requested network and prepare it for customization
new_network = get_base_network(network[:id])
end
merge_network_config(vapp_networks, new_network, config)
end | ruby | def generate_network_section(vAppId, network, config, type)
params = {
'method' => :get,
'command' => "/vApp/vapp-#{vAppId}/networkConfigSection"
}
vapp_networks, headers = send_request(params)
create_fake_network_node(vapp_networks, network[:name])
if type.to_sym == :internal
# Create a network configuration based on the config
new_network = create_internal_network_node(config)
else
# Retrieve the requested network and prepare it for customization
new_network = get_base_network(network[:id])
end
merge_network_config(vapp_networks, new_network, config)
end | [
"def",
"generate_network_section",
"(",
"vAppId",
",",
"network",
",",
"config",
",",
"type",
")",
"params",
"=",
"{",
"'method'",
"=>",
":get",
",",
"'command'",
"=>",
"\"/vApp/vapp-#{vAppId}/networkConfigSection\"",
"}",
"vapp_networks",
",",
"headers",
"=",
"se... | Create a NetworkConfigSection for a new internal or external network | [
"Create",
"a",
"NetworkConfigSection",
"for",
"a",
"new",
"internal",
"or",
"external",
"network"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp_networking.rb#L311-L329 | valid |
vmware/vcloud-rest | lib/vcloud-rest/connection.rb | VCloudClient.Connection.login | def login
params = {
'method' => :post,
'command' => '/sessions'
}
response, headers = send_request(params)
if !headers.has_key?(:x_vcloud_authorization)
raise "Unable to authenticate: missing x_vcloud_authorization header"
end
extensibility_link = response.css("Link[rel='down:extensibility']")
@extensibility = extensibility_link.first['href'] unless extensibility_link.empty?
@auth_key = headers[:x_vcloud_authorization]
end | ruby | def login
params = {
'method' => :post,
'command' => '/sessions'
}
response, headers = send_request(params)
if !headers.has_key?(:x_vcloud_authorization)
raise "Unable to authenticate: missing x_vcloud_authorization header"
end
extensibility_link = response.css("Link[rel='down:extensibility']")
@extensibility = extensibility_link.first['href'] unless extensibility_link.empty?
@auth_key = headers[:x_vcloud_authorization]
end | [
"def",
"login",
"params",
"=",
"{",
"'method'",
"=>",
":post",
",",
"'command'",
"=>",
"'/sessions'",
"}",
"response",
",",
"headers",
"=",
"send_request",
"(",
"params",
")",
"if",
"!",
"headers",
".",
"has_key?",
"(",
":x_vcloud_authorization",
")",
"raise... | Authenticate against the specified server | [
"Authenticate",
"against",
"the",
"specified",
"server"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/connection.rb#L66-L82 | valid |
vmware/vcloud-rest | lib/vcloud-rest/connection.rb | VCloudClient.Connection.get_task | def get_task(taskid)
params = {
'method' => :get,
'command' => "/task/#{taskid}"
}
response, headers = send_request(params)
task = response.css('Task').first
status = task['status']
start_time = task['startTime']
end_time = task['endTime']
{ :status => status, :start_time => start_time, :end_time => end_time, :response => response }
end | ruby | def get_task(taskid)
params = {
'method' => :get,
'command' => "/task/#{taskid}"
}
response, headers = send_request(params)
task = response.css('Task').first
status = task['status']
start_time = task['startTime']
end_time = task['endTime']
{ :status => status, :start_time => start_time, :end_time => end_time, :response => response }
end | [
"def",
"get_task",
"(",
"taskid",
")",
"params",
"=",
"{",
"'method'",
"=>",
":get",
",",
"'command'",
"=>",
"\"/task/#{taskid}\"",
"}",
"response",
",",
"headers",
"=",
"send_request",
"(",
"params",
")",
"task",
"=",
"response",
".",
"css",
"(",
"'Task'"... | Fetch information for a given task | [
"Fetch",
"information",
"for",
"a",
"given",
"task"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/connection.rb#L100-L114 | valid |
vmware/vcloud-rest | lib/vcloud-rest/connection.rb | VCloudClient.Connection.wait_task_completion | def wait_task_completion(taskid)
errormsg = nil
task = {}
loop do
task = get_task(taskid)
break if task[:status] != 'running'
sleep 1
end
if task[:status] == 'error'
errormsg = task[:response].css("Error").first
errormsg = "Error code #{errormsg['majorErrorCode']} - #{errormsg['message']}"
end
{ :status => task[:status], :errormsg => errormsg,
:start_time => task[:start_time], :end_time => task[:end_time] }
end | ruby | def wait_task_completion(taskid)
errormsg = nil
task = {}
loop do
task = get_task(taskid)
break if task[:status] != 'running'
sleep 1
end
if task[:status] == 'error'
errormsg = task[:response].css("Error").first
errormsg = "Error code #{errormsg['majorErrorCode']} - #{errormsg['message']}"
end
{ :status => task[:status], :errormsg => errormsg,
:start_time => task[:start_time], :end_time => task[:end_time] }
end | [
"def",
"wait_task_completion",
"(",
"taskid",
")",
"errormsg",
"=",
"nil",
"task",
"=",
"{",
"}",
"loop",
"do",
"task",
"=",
"get_task",
"(",
"taskid",
")",
"break",
"if",
"task",
"[",
":status",
"]",
"!=",
"'running'",
"sleep",
"1",
"end",
"if",
"task... | Poll a given task until completion | [
"Poll",
"a",
"given",
"task",
"until",
"completion"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/connection.rb#L118-L135 | valid |
vmware/vcloud-rest | lib/vcloud-rest/connection.rb | VCloudClient.Connection.send_request | def send_request(params, payload=nil, content_type=nil)
req_params = setup_request(params, payload, content_type)
handled_request(req_params) do
request = RestClient::Request.new(req_params)
response = request.execute
if ![200, 201, 202, 204].include?(response.code)
@logger.warn "Warning: unattended code #{response.code}"
end
parsed_response = Nokogiri::XML(response)
@logger.debug "Send request result: #{parsed_response}"
[parsed_response, response.headers]
end
end | ruby | def send_request(params, payload=nil, content_type=nil)
req_params = setup_request(params, payload, content_type)
handled_request(req_params) do
request = RestClient::Request.new(req_params)
response = request.execute
if ![200, 201, 202, 204].include?(response.code)
@logger.warn "Warning: unattended code #{response.code}"
end
parsed_response = Nokogiri::XML(response)
@logger.debug "Send request result: #{parsed_response}"
[parsed_response, response.headers]
end
end | [
"def",
"send_request",
"(",
"params",
",",
"payload",
"=",
"nil",
",",
"content_type",
"=",
"nil",
")",
"req_params",
"=",
"setup_request",
"(",
"params",
",",
"payload",
",",
"content_type",
")",
"handled_request",
"(",
"req_params",
")",
"do",
"request",
"... | Sends a synchronous request to the vCloud API and returns the response as parsed XML + headers. | [
"Sends",
"a",
"synchronous",
"request",
"to",
"the",
"vCloud",
"API",
"and",
"returns",
"the",
"response",
"as",
"parsed",
"XML",
"+",
"headers",
"."
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/connection.rb#L140-L156 | valid |
vmware/vcloud-rest | lib/vcloud-rest/connection.rb | VCloudClient.Connection.upload_file | def upload_file(uploadURL, uploadFile, progressUrl, config={})
raise ::IOError, "#{uploadFile} not found." unless File.exists?(uploadFile)
# Set chunksize to 10M if not specified otherwise
chunkSize = (config[:chunksize] || 10485760)
# Set progress bar to default format if not specified otherwise
progressBarFormat = (config[:progressbar_format] || "%e <%B> %p%% %t")
# Set progress bar length to 120 if not specified otherwise
progressBarLength = (config[:progressbar_length] || 120)
# Open our file for upload
uploadFileHandle = File.new(uploadFile, "rb" )
fileName = File.basename(uploadFileHandle)
progressBarTitle = "Uploading: " + uploadFile.to_s
# Create a progressbar object if progress bar is enabled
if config[:progressbar_enable] == true && uploadFileHandle.size.to_i > chunkSize
progressbar = ProgressBar.create(
:title => progressBarTitle,
:starting_at => 0,
:total => uploadFileHandle.size.to_i,
:length => progressBarLength,
:format => progressBarFormat
)
else
@logger.info progressBarTitle
end
# Create a new HTTP client
clnt = HTTPClient.new
# Disable SSL cert verification
clnt.ssl_config.verify_mode=(OpenSSL::SSL::VERIFY_NONE)
# Suppress SSL depth message
clnt.ssl_config.verify_callback=proc{ |ok, ctx|; true };
# Perform ranged upload until the file reaches its end
until uploadFileHandle.eof?
# Create ranges for this chunk upload
rangeStart = uploadFileHandle.pos
rangeStop = uploadFileHandle.pos.to_i + chunkSize
# Read current chunk
fileContent = uploadFileHandle.read(chunkSize)
# If statement to handle last chunk transfer if is > than filesize
if rangeStop.to_i > uploadFileHandle.size.to_i
contentRange = "bytes #{rangeStart.to_s}-#{uploadFileHandle.size.to_s}/#{uploadFileHandle.size.to_s}"
rangeLen = uploadFileHandle.size.to_i - rangeStart.to_i
else
contentRange = "bytes #{rangeStart.to_s}-#{rangeStop.to_s}/#{uploadFileHandle.size.to_s}"
rangeLen = rangeStop.to_i - rangeStart.to_i
end
# Build headers
extheader = {
'x-vcloud-authorization' => @auth_key,
'Content-Range' => contentRange,
'Content-Length' => rangeLen.to_s
}
begin
uploadRequest = "#{@host_url}#{uploadURL}"
connection = clnt.request('PUT', uploadRequest, nil, fileContent, extheader)
if config[:progressbar_enable] == true && uploadFileHandle.size.to_i > chunkSize
params = {
'method' => :get,
'command' => progressUrl
}
response, headers = send_request(params)
response.css("Files File [name='#{fileName}']").each do |file|
progressbar.progress=file[:bytesTransferred].to_i
end
end
rescue
retryTime = (config[:retry_time] || 5)
@logger.warn "Range #{contentRange} failed to upload, retrying the chunk in #{retryTime.to_s} seconds, to stop the action press CTRL+C."
sleep retryTime.to_i
retry
end
end
uploadFileHandle.close
end | ruby | def upload_file(uploadURL, uploadFile, progressUrl, config={})
raise ::IOError, "#{uploadFile} not found." unless File.exists?(uploadFile)
# Set chunksize to 10M if not specified otherwise
chunkSize = (config[:chunksize] || 10485760)
# Set progress bar to default format if not specified otherwise
progressBarFormat = (config[:progressbar_format] || "%e <%B> %p%% %t")
# Set progress bar length to 120 if not specified otherwise
progressBarLength = (config[:progressbar_length] || 120)
# Open our file for upload
uploadFileHandle = File.new(uploadFile, "rb" )
fileName = File.basename(uploadFileHandle)
progressBarTitle = "Uploading: " + uploadFile.to_s
# Create a progressbar object if progress bar is enabled
if config[:progressbar_enable] == true && uploadFileHandle.size.to_i > chunkSize
progressbar = ProgressBar.create(
:title => progressBarTitle,
:starting_at => 0,
:total => uploadFileHandle.size.to_i,
:length => progressBarLength,
:format => progressBarFormat
)
else
@logger.info progressBarTitle
end
# Create a new HTTP client
clnt = HTTPClient.new
# Disable SSL cert verification
clnt.ssl_config.verify_mode=(OpenSSL::SSL::VERIFY_NONE)
# Suppress SSL depth message
clnt.ssl_config.verify_callback=proc{ |ok, ctx|; true };
# Perform ranged upload until the file reaches its end
until uploadFileHandle.eof?
# Create ranges for this chunk upload
rangeStart = uploadFileHandle.pos
rangeStop = uploadFileHandle.pos.to_i + chunkSize
# Read current chunk
fileContent = uploadFileHandle.read(chunkSize)
# If statement to handle last chunk transfer if is > than filesize
if rangeStop.to_i > uploadFileHandle.size.to_i
contentRange = "bytes #{rangeStart.to_s}-#{uploadFileHandle.size.to_s}/#{uploadFileHandle.size.to_s}"
rangeLen = uploadFileHandle.size.to_i - rangeStart.to_i
else
contentRange = "bytes #{rangeStart.to_s}-#{rangeStop.to_s}/#{uploadFileHandle.size.to_s}"
rangeLen = rangeStop.to_i - rangeStart.to_i
end
# Build headers
extheader = {
'x-vcloud-authorization' => @auth_key,
'Content-Range' => contentRange,
'Content-Length' => rangeLen.to_s
}
begin
uploadRequest = "#{@host_url}#{uploadURL}"
connection = clnt.request('PUT', uploadRequest, nil, fileContent, extheader)
if config[:progressbar_enable] == true && uploadFileHandle.size.to_i > chunkSize
params = {
'method' => :get,
'command' => progressUrl
}
response, headers = send_request(params)
response.css("Files File [name='#{fileName}']").each do |file|
progressbar.progress=file[:bytesTransferred].to_i
end
end
rescue
retryTime = (config[:retry_time] || 5)
@logger.warn "Range #{contentRange} failed to upload, retrying the chunk in #{retryTime.to_s} seconds, to stop the action press CTRL+C."
sleep retryTime.to_i
retry
end
end
uploadFileHandle.close
end | [
"def",
"upload_file",
"(",
"uploadURL",
",",
"uploadFile",
",",
"progressUrl",
",",
"config",
"=",
"{",
"}",
")",
"raise",
"::",
"IOError",
",",
"\"#{uploadFile} not found.\"",
"unless",
"File",
".",
"exists?",
"(",
"uploadFile",
")",
"chunkSize",
"=",
"(",
... | Upload a large file in configurable chunks, output an optional progressbar | [
"Upload",
"a",
"large",
"file",
"in",
"configurable",
"chunks",
"output",
"an",
"optional",
"progressbar"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/connection.rb#L328-L416 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/catalog.rb | VCloudClient.Connection.get_catalog | def get_catalog(catalogId)
params = {
'method' => :get,
'command' => "/catalog/#{catalogId}"
}
response, headers = send_request(params)
description = response.css("Description").first
description = description.text unless description.nil?
items = {}
response.css("CatalogItem[type='application/vnd.vmware.vcloud.catalogItem+xml']").each do |item|
items[item['name']] = item['href'].gsub(/.*\/catalogItem\//, "")
end
{ :id => catalogId, :description => description, :items => items }
end | ruby | def get_catalog(catalogId)
params = {
'method' => :get,
'command' => "/catalog/#{catalogId}"
}
response, headers = send_request(params)
description = response.css("Description").first
description = description.text unless description.nil?
items = {}
response.css("CatalogItem[type='application/vnd.vmware.vcloud.catalogItem+xml']").each do |item|
items[item['name']] = item['href'].gsub(/.*\/catalogItem\//, "")
end
{ :id => catalogId, :description => description, :items => items }
end | [
"def",
"get_catalog",
"(",
"catalogId",
")",
"params",
"=",
"{",
"'method'",
"=>",
":get",
",",
"'command'",
"=>",
"\"/catalog/#{catalogId}\"",
"}",
"response",
",",
"headers",
"=",
"send_request",
"(",
"params",
")",
"description",
"=",
"response",
".",
"css"... | Fetch details about a given catalog | [
"Fetch",
"details",
"about",
"a",
"given",
"catalog"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/catalog.rb#L5-L20 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vm.rb | VCloudClient.Connection.get_vm_disk_info | def get_vm_disk_info(vmid)
response, headers = __get_disk_info(vmid)
disks = []
response.css("Item").each do |entry|
# Pick only entries with node "HostResource"
resource = entry.css("rasd|HostResource").first
next unless resource
name = entry.css("rasd|ElementName").first
name = name.text unless name.nil?
capacity = resource.attribute("capacity").text
disks << {
:name => name,
:capacity => "#{capacity} MB"
}
end
disks
end | ruby | def get_vm_disk_info(vmid)
response, headers = __get_disk_info(vmid)
disks = []
response.css("Item").each do |entry|
# Pick only entries with node "HostResource"
resource = entry.css("rasd|HostResource").first
next unless resource
name = entry.css("rasd|ElementName").first
name = name.text unless name.nil?
capacity = resource.attribute("capacity").text
disks << {
:name => name,
:capacity => "#{capacity} MB"
}
end
disks
end | [
"def",
"get_vm_disk_info",
"(",
"vmid",
")",
"response",
",",
"headers",
"=",
"__get_disk_info",
"(",
"vmid",
")",
"disks",
"=",
"[",
"]",
"response",
".",
"css",
"(",
"\"Item\"",
")",
".",
"each",
"do",
"|",
"entry",
"|",
"resource",
"=",
"entry",
"."... | Retrieve information about Disks | [
"Retrieve",
"information",
"about",
"Disks"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vm.rb#L33-L52 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vm.rb | VCloudClient.Connection.set_vm_disk_info | def set_vm_disk_info(vmid, disk_info={})
get_response, headers = __get_disk_info(vmid)
if disk_info[:add]
data = add_disk(get_response, disk_info)
else
data = edit_disk(get_response, disk_info)
end
params = {
'method' => :put,
'command' => "/vApp/vm-#{vmid}/virtualHardwareSection/disks"
}
put_response, headers = send_request(params, data, "application/vnd.vmware.vcloud.rasdItemsList+xml")
task_id = headers[:location].gsub(/.*\/task\//, "")
task_id
end | ruby | def set_vm_disk_info(vmid, disk_info={})
get_response, headers = __get_disk_info(vmid)
if disk_info[:add]
data = add_disk(get_response, disk_info)
else
data = edit_disk(get_response, disk_info)
end
params = {
'method' => :put,
'command' => "/vApp/vm-#{vmid}/virtualHardwareSection/disks"
}
put_response, headers = send_request(params, data, "application/vnd.vmware.vcloud.rasdItemsList+xml")
task_id = headers[:location].gsub(/.*\/task\//, "")
task_id
end | [
"def",
"set_vm_disk_info",
"(",
"vmid",
",",
"disk_info",
"=",
"{",
"}",
")",
"get_response",
",",
"headers",
"=",
"__get_disk_info",
"(",
"vmid",
")",
"if",
"disk_info",
"[",
":add",
"]",
"data",
"=",
"add_disk",
"(",
"get_response",
",",
"disk_info",
")"... | Set information about Disks
Disks can be added, deleted or modified | [
"Set",
"information",
"about",
"Disks"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vm.rb#L58-L75 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vm.rb | VCloudClient.Connection.set_vm_cpus | def set_vm_cpus(vmid, cpu_number)
params = {
'method' => :get,
'command' => "/vApp/vm-#{vmid}/virtualHardwareSection/cpu"
}
get_response, headers = send_request(params)
# Change attributes from the previous invocation
get_response.css("rasd|ElementName").first.content = "#{cpu_number} virtual CPU(s)"
get_response.css("rasd|VirtualQuantity").first.content = cpu_number
params['method'] = :put
put_response, headers = send_request(params, get_response.to_xml, "application/vnd.vmware.vcloud.rasdItem+xml")
task_id = headers[:location].gsub(/.*\/task\//, "")
task_id
end | ruby | def set_vm_cpus(vmid, cpu_number)
params = {
'method' => :get,
'command' => "/vApp/vm-#{vmid}/virtualHardwareSection/cpu"
}
get_response, headers = send_request(params)
# Change attributes from the previous invocation
get_response.css("rasd|ElementName").first.content = "#{cpu_number} virtual CPU(s)"
get_response.css("rasd|VirtualQuantity").first.content = cpu_number
params['method'] = :put
put_response, headers = send_request(params, get_response.to_xml, "application/vnd.vmware.vcloud.rasdItem+xml")
task_id = headers[:location].gsub(/.*\/task\//, "")
task_id
end | [
"def",
"set_vm_cpus",
"(",
"vmid",
",",
"cpu_number",
")",
"params",
"=",
"{",
"'method'",
"=>",
":get",
",",
"'command'",
"=>",
"\"/vApp/vm-#{vmid}/virtualHardwareSection/cpu\"",
"}",
"get_response",
",",
"headers",
"=",
"send_request",
"(",
"params",
")",
"get_r... | Set VM CPUs | [
"Set",
"VM",
"CPUs"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vm.rb#L79-L96 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vm.rb | VCloudClient.Connection.set_vm_ram | def set_vm_ram(vmid, memory_size)
params = {
'method' => :get,
'command' => "/vApp/vm-#{vmid}/virtualHardwareSection/memory"
}
get_response, headers = send_request(params)
# Change attributes from the previous invocation
get_response.css("rasd|ElementName").first.content = "#{memory_size} MB of memory"
get_response.css("rasd|VirtualQuantity").first.content = memory_size
params['method'] = :put
put_response, headers = send_request(params, get_response.to_xml, "application/vnd.vmware.vcloud.rasdItem+xml")
task_id = headers[:location].gsub(/.*\/task\//, "")
task_id
end | ruby | def set_vm_ram(vmid, memory_size)
params = {
'method' => :get,
'command' => "/vApp/vm-#{vmid}/virtualHardwareSection/memory"
}
get_response, headers = send_request(params)
# Change attributes from the previous invocation
get_response.css("rasd|ElementName").first.content = "#{memory_size} MB of memory"
get_response.css("rasd|VirtualQuantity").first.content = memory_size
params['method'] = :put
put_response, headers = send_request(params, get_response.to_xml, "application/vnd.vmware.vcloud.rasdItem+xml")
task_id = headers[:location].gsub(/.*\/task\//, "")
task_id
end | [
"def",
"set_vm_ram",
"(",
"vmid",
",",
"memory_size",
")",
"params",
"=",
"{",
"'method'",
"=>",
":get",
",",
"'command'",
"=>",
"\"/vApp/vm-#{vmid}/virtualHardwareSection/memory\"",
"}",
"get_response",
",",
"headers",
"=",
"send_request",
"(",
"params",
")",
"ge... | Set VM RAM | [
"Set",
"VM",
"RAM"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vm.rb#L100-L117 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vm.rb | VCloudClient.Connection.edit_vm_network | def edit_vm_network(vmId, network, config={})
params = {
'method' => :get,
'command' => "/vApp/vm-#{vmId}/networkConnectionSection"
}
netconfig_response, headers = send_request(params)
if config[:primary_index]
node = netconfig_response.css('PrimaryNetworkConnectionIndex').first
node.content = config[:primary_index]
end
picked_network = netconfig_response.css("NetworkConnection").select do |net|
net.attribute('network').text == network[:name]
end.first
raise WrongItemIDError, "Network named #{network[:name]} not found." unless picked_network
if config[:ip_allocation_mode]
node = picked_network.css('IpAddressAllocationMode').first
node.content = config[:ip_allocation_mode]
end
if config[:network_index]
node = picked_network.css('NetworkConnectionIndex').first
node.content = config[:network_index]
end
if config[:is_connected]
node = picked_network.css('IsConnected').first
node.content = config[:is_connected]
end
if config[:ip]
node = picked_network.css('IpAddress').first
node.content = config[:ip]
end
params = {
'method' => :put,
'command' => "/vApp/vm-#{vmId}/networkConnectionSection"
}
response, headers = send_request(params, netconfig_response.to_xml, "application/vnd.vmware.vcloud.networkConnectionSection+xml")
task_id = headers[:location].gsub(/.*\/task\//, "")
task_id
end | ruby | def edit_vm_network(vmId, network, config={})
params = {
'method' => :get,
'command' => "/vApp/vm-#{vmId}/networkConnectionSection"
}
netconfig_response, headers = send_request(params)
if config[:primary_index]
node = netconfig_response.css('PrimaryNetworkConnectionIndex').first
node.content = config[:primary_index]
end
picked_network = netconfig_response.css("NetworkConnection").select do |net|
net.attribute('network').text == network[:name]
end.first
raise WrongItemIDError, "Network named #{network[:name]} not found." unless picked_network
if config[:ip_allocation_mode]
node = picked_network.css('IpAddressAllocationMode').first
node.content = config[:ip_allocation_mode]
end
if config[:network_index]
node = picked_network.css('NetworkConnectionIndex').first
node.content = config[:network_index]
end
if config[:is_connected]
node = picked_network.css('IsConnected').first
node.content = config[:is_connected]
end
if config[:ip]
node = picked_network.css('IpAddress').first
node.content = config[:ip]
end
params = {
'method' => :put,
'command' => "/vApp/vm-#{vmId}/networkConnectionSection"
}
response, headers = send_request(params, netconfig_response.to_xml, "application/vnd.vmware.vcloud.networkConnectionSection+xml")
task_id = headers[:location].gsub(/.*\/task\//, "")
task_id
end | [
"def",
"edit_vm_network",
"(",
"vmId",
",",
"network",
",",
"config",
"=",
"{",
"}",
")",
"params",
"=",
"{",
"'method'",
"=>",
":get",
",",
"'command'",
"=>",
"\"/vApp/vm-#{vmId}/networkConnectionSection\"",
"}",
"netconfig_response",
",",
"headers",
"=",
"send... | Edit VM Network Config
Retrieve the existing network config section and edit it
to ensure settings are not lost | [
"Edit",
"VM",
"Network",
"Config"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vm.rb#L124-L172 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vm.rb | VCloudClient.Connection.add_vm_network | def add_vm_network(vmId, network, config={})
params = {
'method' => :get,
'command' => "/vApp/vm-#{vmId}/networkConnectionSection"
}
netconfig_response, headers = send_request(params)
parent_section = netconfig_response.css('NetworkConnectionSection').first
# For some reasons these elements must be removed
netconfig_response.css("Link").each {|n| n.remove}
# Delete placeholder network if present (since vcloud 5.5 has been removed)
none_network = netconfig_response.css('NetworkConnection').find{|n| n.attribute('network').text == 'none'}
none_network.remove if none_network
networks_count = netconfig_response.css('NetworkConnection').count
primary_index_node = netconfig_response.css('PrimaryNetworkConnectionIndex').first
unless primary_index_node
primary_index_node = Nokogiri::XML::Node.new "PrimaryNetworkConnectionIndex", parent_section
parent_section.add_child(primary_index_node)
end
primary_index_node.content = config[:primary_index] || 0
new_network = Nokogiri::XML::Node.new "NetworkConnection", parent_section
new_network["network"] = network[:name]
new_network["needsCustomization"] = true
idx_node = Nokogiri::XML::Node.new "NetworkConnectionIndex", new_network
idx_node.content = config[:network_index] || networks_count
new_network.add_child(idx_node)
if config[:ip]
ip_node = Nokogiri::XML::Node.new "IpAddress", new_network
ip_node.content = config[:ip]
new_network.add_child(ip_node)
end
is_connected_node = Nokogiri::XML::Node.new "IsConnected", new_network
is_connected_node.content = config[:is_connected] || true
new_network.add_child(is_connected_node)
allocation_node = Nokogiri::XML::Node.new "IpAddressAllocationMode", new_network
allocation_node.content = config[:ip_allocation_mode] || "POOL"
new_network.add_child(allocation_node)
parent_section.add_child(new_network)
params = {
'method' => :put,
'command' => "/vApp/vm-#{vmId}/networkConnectionSection"
}
put_response, headers = send_request(params, netconfig_response.to_xml, "application/vnd.vmware.vcloud.networkConnectionSection+xml")
task_id = headers[:location].gsub(/.*\/task\//, "")
task_id
end | ruby | def add_vm_network(vmId, network, config={})
params = {
'method' => :get,
'command' => "/vApp/vm-#{vmId}/networkConnectionSection"
}
netconfig_response, headers = send_request(params)
parent_section = netconfig_response.css('NetworkConnectionSection').first
# For some reasons these elements must be removed
netconfig_response.css("Link").each {|n| n.remove}
# Delete placeholder network if present (since vcloud 5.5 has been removed)
none_network = netconfig_response.css('NetworkConnection').find{|n| n.attribute('network').text == 'none'}
none_network.remove if none_network
networks_count = netconfig_response.css('NetworkConnection').count
primary_index_node = netconfig_response.css('PrimaryNetworkConnectionIndex').first
unless primary_index_node
primary_index_node = Nokogiri::XML::Node.new "PrimaryNetworkConnectionIndex", parent_section
parent_section.add_child(primary_index_node)
end
primary_index_node.content = config[:primary_index] || 0
new_network = Nokogiri::XML::Node.new "NetworkConnection", parent_section
new_network["network"] = network[:name]
new_network["needsCustomization"] = true
idx_node = Nokogiri::XML::Node.new "NetworkConnectionIndex", new_network
idx_node.content = config[:network_index] || networks_count
new_network.add_child(idx_node)
if config[:ip]
ip_node = Nokogiri::XML::Node.new "IpAddress", new_network
ip_node.content = config[:ip]
new_network.add_child(ip_node)
end
is_connected_node = Nokogiri::XML::Node.new "IsConnected", new_network
is_connected_node.content = config[:is_connected] || true
new_network.add_child(is_connected_node)
allocation_node = Nokogiri::XML::Node.new "IpAddressAllocationMode", new_network
allocation_node.content = config[:ip_allocation_mode] || "POOL"
new_network.add_child(allocation_node)
parent_section.add_child(new_network)
params = {
'method' => :put,
'command' => "/vApp/vm-#{vmId}/networkConnectionSection"
}
put_response, headers = send_request(params, netconfig_response.to_xml, "application/vnd.vmware.vcloud.networkConnectionSection+xml")
task_id = headers[:location].gsub(/.*\/task\//, "")
task_id
end | [
"def",
"add_vm_network",
"(",
"vmId",
",",
"network",
",",
"config",
"=",
"{",
"}",
")",
"params",
"=",
"{",
"'method'",
"=>",
":get",
",",
"'command'",
"=>",
"\"/vApp/vm-#{vmId}/networkConnectionSection\"",
"}",
"netconfig_response",
",",
"headers",
"=",
"send_... | Add a new network to a VM | [
"Add",
"a",
"new",
"network",
"to",
"a",
"VM"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vm.rb#L176-L235 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vm.rb | VCloudClient.Connection.delete_vm_network | def delete_vm_network(vmId, network)
params = {
'method' => :get,
'command' => "/vApp/vm-#{vmId}/networkConnectionSection"
}
netconfig_response, headers = send_request(params)
picked_network = netconfig_response.css("NetworkConnection").select do |net|
net.attribute('network').text == network[:name]
end.first
raise WrongItemIDError, "Network #{network[:name]} not found on this VM." unless picked_network
picked_network.remove
params = {
'method' => :put,
'command' => "/vApp/vm-#{vmId}/networkConnectionSection"
}
put_response, headers = send_request(params, netconfig_response.to_xml, "application/vnd.vmware.vcloud.networkConnectionSection+xml")
task_id = headers[:location].gsub(/.*\/task\//, "")
task_id
end | ruby | def delete_vm_network(vmId, network)
params = {
'method' => :get,
'command' => "/vApp/vm-#{vmId}/networkConnectionSection"
}
netconfig_response, headers = send_request(params)
picked_network = netconfig_response.css("NetworkConnection").select do |net|
net.attribute('network').text == network[:name]
end.first
raise WrongItemIDError, "Network #{network[:name]} not found on this VM." unless picked_network
picked_network.remove
params = {
'method' => :put,
'command' => "/vApp/vm-#{vmId}/networkConnectionSection"
}
put_response, headers = send_request(params, netconfig_response.to_xml, "application/vnd.vmware.vcloud.networkConnectionSection+xml")
task_id = headers[:location].gsub(/.*\/task\//, "")
task_id
end | [
"def",
"delete_vm_network",
"(",
"vmId",
",",
"network",
")",
"params",
"=",
"{",
"'method'",
"=>",
":get",
",",
"'command'",
"=>",
"\"/vApp/vm-#{vmId}/networkConnectionSection\"",
"}",
"netconfig_response",
",",
"headers",
"=",
"send_request",
"(",
"params",
")",
... | Remove an existing network | [
"Remove",
"an",
"existing",
"network"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vm.rb#L239-L264 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vm.rb | VCloudClient.Connection.set_vm_guest_customization | def set_vm_guest_customization(vmid, computer_name, config={})
builder = Nokogiri::XML::Builder.new do |xml|
xml.GuestCustomizationSection(
"xmlns" => "http://www.vmware.com/vcloud/v1.5",
"xmlns:ovf" => "http://schemas.dmtf.org/ovf/envelope/1") {
xml['ovf'].Info "VM Guest Customization configuration"
xml.Enabled config[:enabled] if config[:enabled]
xml.AdminPasswordEnabled config[:admin_passwd_enabled] if config[:admin_passwd_enabled]
xml.AdminPassword config[:admin_passwd] if config[:admin_passwd]
xml.CustomizationScript config[:customization_script] if config[:customization_script]
xml.ComputerName computer_name
}
end
params = {
'method' => :put,
'command' => "/vApp/vm-#{vmid}/guestCustomizationSection"
}
response, headers = send_request(params, builder.to_xml, "application/vnd.vmware.vcloud.guestCustomizationSection+xml")
task_id = headers[:location].gsub(/.*\/task\//, "")
task_id
end | ruby | def set_vm_guest_customization(vmid, computer_name, config={})
builder = Nokogiri::XML::Builder.new do |xml|
xml.GuestCustomizationSection(
"xmlns" => "http://www.vmware.com/vcloud/v1.5",
"xmlns:ovf" => "http://schemas.dmtf.org/ovf/envelope/1") {
xml['ovf'].Info "VM Guest Customization configuration"
xml.Enabled config[:enabled] if config[:enabled]
xml.AdminPasswordEnabled config[:admin_passwd_enabled] if config[:admin_passwd_enabled]
xml.AdminPassword config[:admin_passwd] if config[:admin_passwd]
xml.CustomizationScript config[:customization_script] if config[:customization_script]
xml.ComputerName computer_name
}
end
params = {
'method' => :put,
'command' => "/vApp/vm-#{vmid}/guestCustomizationSection"
}
response, headers = send_request(params, builder.to_xml, "application/vnd.vmware.vcloud.guestCustomizationSection+xml")
task_id = headers[:location].gsub(/.*\/task\//, "")
task_id
end | [
"def",
"set_vm_guest_customization",
"(",
"vmid",
",",
"computer_name",
",",
"config",
"=",
"{",
"}",
")",
"builder",
"=",
"Nokogiri",
"::",
"XML",
"::",
"Builder",
".",
"new",
"do",
"|",
"xml",
"|",
"xml",
".",
"GuestCustomizationSection",
"(",
"\"xmlns\"",... | Set VM Guest Customization Config | [
"Set",
"VM",
"Guest",
"Customization",
"Config"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vm.rb#L268-L291 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vm.rb | VCloudClient.Connection.get_vm | def get_vm(vmId)
params = {
'method' => :get,
'command' => "/vApp/vm-#{vmId}"
}
response, headers = send_request(params)
vm_name = response.css('Vm').attribute("name")
vm_name = vm_name.text unless vm_name.nil?
status = convert_vapp_status(response.css('Vm').attribute("status").text)
os_desc = response.css('ovf|OperatingSystemSection ovf|Description').first.text
networks = {}
response.css('NetworkConnection').each do |network|
ip = network.css('IpAddress').first
ip = ip.text if ip
external_ip = network.css('ExternalIpAddress').first
external_ip = external_ip.text if external_ip
# Append NetworkConnectionIndex to network name to generate a unique hash key,
# otherwise different interfaces on the same network would use the same hash key
key = "#{network['network']}_#{network.css('NetworkConnectionIndex').first.text}"
networks[key] = {
:index => network.css('NetworkConnectionIndex').first.text,
:ip => ip,
:external_ip => external_ip,
:is_connected => network.css('IsConnected').first.text,
:mac_address => network.css('MACAddress').first.text,
:ip_allocation_mode => network.css('IpAddressAllocationMode').first.text
}
end
admin_password = response.css('GuestCustomizationSection AdminPassword').first
admin_password = admin_password.text if admin_password
guest_customizations = {
:enabled => response.css('GuestCustomizationSection Enabled').first.text,
:admin_passwd_enabled => response.css('GuestCustomizationSection AdminPasswordEnabled').first.text,
:admin_passwd_auto => response.css('GuestCustomizationSection AdminPasswordAuto').first.text,
:admin_passwd => admin_password,
:reset_passwd_required => response.css('GuestCustomizationSection ResetPasswordRequired').first.text,
:computer_name => response.css('GuestCustomizationSection ComputerName').first.text
}
{ :id => vmId,
:vm_name => vm_name, :os_desc => os_desc, :networks => networks,
:guest_customizations => guest_customizations, :status => status
}
end | ruby | def get_vm(vmId)
params = {
'method' => :get,
'command' => "/vApp/vm-#{vmId}"
}
response, headers = send_request(params)
vm_name = response.css('Vm').attribute("name")
vm_name = vm_name.text unless vm_name.nil?
status = convert_vapp_status(response.css('Vm').attribute("status").text)
os_desc = response.css('ovf|OperatingSystemSection ovf|Description').first.text
networks = {}
response.css('NetworkConnection').each do |network|
ip = network.css('IpAddress').first
ip = ip.text if ip
external_ip = network.css('ExternalIpAddress').first
external_ip = external_ip.text if external_ip
# Append NetworkConnectionIndex to network name to generate a unique hash key,
# otherwise different interfaces on the same network would use the same hash key
key = "#{network['network']}_#{network.css('NetworkConnectionIndex').first.text}"
networks[key] = {
:index => network.css('NetworkConnectionIndex').first.text,
:ip => ip,
:external_ip => external_ip,
:is_connected => network.css('IsConnected').first.text,
:mac_address => network.css('MACAddress').first.text,
:ip_allocation_mode => network.css('IpAddressAllocationMode').first.text
}
end
admin_password = response.css('GuestCustomizationSection AdminPassword').first
admin_password = admin_password.text if admin_password
guest_customizations = {
:enabled => response.css('GuestCustomizationSection Enabled').first.text,
:admin_passwd_enabled => response.css('GuestCustomizationSection AdminPasswordEnabled').first.text,
:admin_passwd_auto => response.css('GuestCustomizationSection AdminPasswordAuto').first.text,
:admin_passwd => admin_password,
:reset_passwd_required => response.css('GuestCustomizationSection ResetPasswordRequired').first.text,
:computer_name => response.css('GuestCustomizationSection ComputerName').first.text
}
{ :id => vmId,
:vm_name => vm_name, :os_desc => os_desc, :networks => networks,
:guest_customizations => guest_customizations, :status => status
}
end | [
"def",
"get_vm",
"(",
"vmId",
")",
"params",
"=",
"{",
"'method'",
"=>",
":get",
",",
"'command'",
"=>",
"\"/vApp/vm-#{vmId}\"",
"}",
"response",
",",
"headers",
"=",
"send_request",
"(",
"params",
")",
"vm_name",
"=",
"response",
".",
"css",
"(",
"'Vm'",
... | Fetch details about a given VM | [
"Fetch",
"details",
"about",
"a",
"given",
"VM"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vm.rb#L330-L383 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vm.rb | VCloudClient.Connection.get_vm_by_name | def get_vm_by_name(organization, vdcName, vAppName, vmName)
result = nil
get_vapp_by_name(organization, vdcName, vAppName)[:vms_hash].each do |key, values|
if key.downcase == vmName.downcase
result = get_vm(values[:id])
end
end
result
end | ruby | def get_vm_by_name(organization, vdcName, vAppName, vmName)
result = nil
get_vapp_by_name(organization, vdcName, vAppName)[:vms_hash].each do |key, values|
if key.downcase == vmName.downcase
result = get_vm(values[:id])
end
end
result
end | [
"def",
"get_vm_by_name",
"(",
"organization",
",",
"vdcName",
",",
"vAppName",
",",
"vmName",
")",
"result",
"=",
"nil",
"get_vapp_by_name",
"(",
"organization",
",",
"vdcName",
",",
"vAppName",
")",
"[",
":vms_hash",
"]",
".",
"each",
"do",
"|",
"key",
",... | Friendly helper method to fetch a vApp by name
- Organization object
- Organization VDC Name
- vApp Name
- VM Name | [
"Friendly",
"helper",
"method",
"to",
"fetch",
"a",
"vApp",
"by",
"name",
"-",
"Organization",
"object",
"-",
"Organization",
"VDC",
"Name",
"-",
"vApp",
"Name",
"-",
"VM",
"Name"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vm.rb#L391-L401 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vm.rb | VCloudClient.Connection.poweroff_vm | def poweroff_vm(vmId)
builder = Nokogiri::XML::Builder.new do |xml|
xml.UndeployVAppParams(
"xmlns" => "http://www.vmware.com/vcloud/v1.5") {
xml.UndeployPowerAction 'powerOff'
}
end
params = {
'method' => :post,
'command' => "/vApp/vm-#{vmId}/action/undeploy"
}
response, headers = send_request(params, builder.to_xml,
"application/vnd.vmware.vcloud.undeployVAppParams+xml")
task_id = headers[:location].gsub(/.*\/task\//, "")
task_id
end | ruby | def poweroff_vm(vmId)
builder = Nokogiri::XML::Builder.new do |xml|
xml.UndeployVAppParams(
"xmlns" => "http://www.vmware.com/vcloud/v1.5") {
xml.UndeployPowerAction 'powerOff'
}
end
params = {
'method' => :post,
'command' => "/vApp/vm-#{vmId}/action/undeploy"
}
response, headers = send_request(params, builder.to_xml,
"application/vnd.vmware.vcloud.undeployVAppParams+xml")
task_id = headers[:location].gsub(/.*\/task\//, "")
task_id
end | [
"def",
"poweroff_vm",
"(",
"vmId",
")",
"builder",
"=",
"Nokogiri",
"::",
"XML",
"::",
"Builder",
".",
"new",
"do",
"|",
"xml",
"|",
"xml",
".",
"UndeployVAppParams",
"(",
"\"xmlns\"",
"=>",
"\"http://www.vmware.com/vcloud/v1.5\"",
")",
"{",
"xml",
".",
"Und... | Shutdown a given vm | [
"Shutdown",
"a",
"given",
"vm"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vm.rb#L405-L422 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vm.rb | VCloudClient.Connection.acquire_ticket_vm | def acquire_ticket_vm(vmId)
params = {
'method' => :post,
'command' => "/vApp/vm-#{vmId}/screen/action/acquireTicket"
}
response, headers = send_request(params)
screen_ticket = response.css("ScreenTicket").text
result = {}
if screen_ticket =~ /mks:\/\/([^\/]*)\/([^\?]*)\?ticket=(.*)/
result = { host: $1, moid: $2, token: $3 }
result[:token] = URI.unescape result[:token]
end
result
end | ruby | def acquire_ticket_vm(vmId)
params = {
'method' => :post,
'command' => "/vApp/vm-#{vmId}/screen/action/acquireTicket"
}
response, headers = send_request(params)
screen_ticket = response.css("ScreenTicket").text
result = {}
if screen_ticket =~ /mks:\/\/([^\/]*)\/([^\?]*)\?ticket=(.*)/
result = { host: $1, moid: $2, token: $3 }
result[:token] = URI.unescape result[:token]
end
result
end | [
"def",
"acquire_ticket_vm",
"(",
"vmId",
")",
"params",
"=",
"{",
"'method'",
"=>",
":post",
",",
"'command'",
"=>",
"\"/vApp/vm-#{vmId}/screen/action/acquireTicket\"",
"}",
"response",
",",
"headers",
"=",
"send_request",
"(",
"params",
")",
"screen_ticket",
"=",
... | Retrieve a screen ticket that you can use with the VMRC browser plug-in
to gain access to the console of a running VM. | [
"Retrieve",
"a",
"screen",
"ticket",
"that",
"you",
"can",
"use",
"with",
"the",
"VMRC",
"browser",
"plug",
"-",
"in",
"to",
"gain",
"access",
"to",
"the",
"console",
"of",
"a",
"running",
"VM",
"."
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vm.rb#L478-L496 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/network.rb | VCloudClient.Connection.get_network | def get_network(networkId)
response = get_base_network(networkId)
name = response.css('OrgVdcNetwork').attribute('name').text
description = response.css("Description").first
description = description.text unless description.nil?
gateway = response.css('Gateway')
gateway = gateway.text unless gateway.nil?
netmask = response.css('Netmask')
netmask = netmask.text unless netmask.nil?
fence_mode = response.css('FenceMode')
fence_mode = fence_mode.text unless fence_mode.nil?
start_address = response.css('StartAddress')
start_address = start_address.text unless start_address.nil?
end_address = response.css('EndAddress')
end_address = end_address.text unless end_address.nil?
{ :id => networkId, :name => name, :description => description,
:gateway => gateway, :netmask => netmask, :fence_mode => fence_mode,
:start_address => start_address, :end_address => end_address }
end | ruby | def get_network(networkId)
response = get_base_network(networkId)
name = response.css('OrgVdcNetwork').attribute('name').text
description = response.css("Description").first
description = description.text unless description.nil?
gateway = response.css('Gateway')
gateway = gateway.text unless gateway.nil?
netmask = response.css('Netmask')
netmask = netmask.text unless netmask.nil?
fence_mode = response.css('FenceMode')
fence_mode = fence_mode.text unless fence_mode.nil?
start_address = response.css('StartAddress')
start_address = start_address.text unless start_address.nil?
end_address = response.css('EndAddress')
end_address = end_address.text unless end_address.nil?
{ :id => networkId, :name => name, :description => description,
:gateway => gateway, :netmask => netmask, :fence_mode => fence_mode,
:start_address => start_address, :end_address => end_address }
end | [
"def",
"get_network",
"(",
"networkId",
")",
"response",
"=",
"get_base_network",
"(",
"networkId",
")",
"name",
"=",
"response",
".",
"css",
"(",
"'OrgVdcNetwork'",
")",
".",
"attribute",
"(",
"'name'",
")",
".",
"text",
"description",
"=",
"response",
".",... | Fetch details about a given Org VDC network | [
"Fetch",
"details",
"about",
"a",
"given",
"Org",
"VDC",
"network"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/network.rb#L5-L32 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/org.rb | VCloudClient.Connection.get_organizations | def get_organizations
params = {
'method' => :get,
'command' => '/org'
}
response, headers = send_request(params)
orgs = response.css('OrgList Org')
results = {}
orgs.each do |org|
results[org['name']] = org['href'].gsub(/.*\/org\//, "")
end
results
end | ruby | def get_organizations
params = {
'method' => :get,
'command' => '/org'
}
response, headers = send_request(params)
orgs = response.css('OrgList Org')
results = {}
orgs.each do |org|
results[org['name']] = org['href'].gsub(/.*\/org\//, "")
end
results
end | [
"def",
"get_organizations",
"params",
"=",
"{",
"'method'",
"=>",
":get",
",",
"'command'",
"=>",
"'/org'",
"}",
"response",
",",
"headers",
"=",
"send_request",
"(",
"params",
")",
"orgs",
"=",
"response",
".",
"css",
"(",
"'OrgList Org'",
")",
"results",
... | Fetch existing organizations and their IDs | [
"Fetch",
"existing",
"organizations",
"and",
"their",
"IDs"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/org.rb#L5-L19 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/org.rb | VCloudClient.Connection.get_tasks_list | def get_tasks_list(id)
params = {
'method' => :get,
'command' => "/tasksList/#{id}"
}
response, headers = send_request(params)
tasks = []
response.css('Task').each do |task|
id = task['href'].gsub(/.*\/task\//, "")
operation = task['operationName']
status = task['status']
error = nil
error = task.css('Error').first['message'] if task['status'] == 'error'
start_time = task['startTime']
end_time = task['endTime']
user_canceled = task['cancelRequested'] == 'true'
tasks << {
:id => id,
:operation => operation,
:status => status,
:error => error,
:start_time => start_time,
:end_time => end_time,
:user_canceled => user_canceled
}
end
tasks
end | ruby | def get_tasks_list(id)
params = {
'method' => :get,
'command' => "/tasksList/#{id}"
}
response, headers = send_request(params)
tasks = []
response.css('Task').each do |task|
id = task['href'].gsub(/.*\/task\//, "")
operation = task['operationName']
status = task['status']
error = nil
error = task.css('Error').first['message'] if task['status'] == 'error'
start_time = task['startTime']
end_time = task['endTime']
user_canceled = task['cancelRequested'] == 'true'
tasks << {
:id => id,
:operation => operation,
:status => status,
:error => error,
:start_time => start_time,
:end_time => end_time,
:user_canceled => user_canceled
}
end
tasks
end | [
"def",
"get_tasks_list",
"(",
"id",
")",
"params",
"=",
"{",
"'method'",
"=>",
":get",
",",
"'command'",
"=>",
"\"/tasksList/#{id}\"",
"}",
"response",
",",
"headers",
"=",
"send_request",
"(",
"params",
")",
"tasks",
"=",
"[",
"]",
"response",
".",
"css",... | Fetch tasks from a given task list
Note: id can be retrieved using get_organization | [
"Fetch",
"tasks",
"from",
"a",
"given",
"task",
"list"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/org.rb#L96-L127 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vdc.rb | VCloudClient.Connection.get_vdc_id_by_name | def get_vdc_id_by_name(organization, vdcName)
result = nil
organization[:vdcs].each do |vdc|
if vdc[0].downcase == vdcName.downcase
result = vdc[1]
end
end
result
end | ruby | def get_vdc_id_by_name(organization, vdcName)
result = nil
organization[:vdcs].each do |vdc|
if vdc[0].downcase == vdcName.downcase
result = vdc[1]
end
end
result
end | [
"def",
"get_vdc_id_by_name",
"(",
"organization",
",",
"vdcName",
")",
"result",
"=",
"nil",
"organization",
"[",
":vdcs",
"]",
".",
"each",
"do",
"|",
"vdc",
"|",
"if",
"vdc",
"[",
"0",
"]",
".",
"downcase",
"==",
"vdcName",
".",
"downcase",
"result",
... | Friendly helper method to fetch a Organization VDC Id by name
- Organization object
- Organization VDC Name | [
"Friendly",
"helper",
"method",
"to",
"fetch",
"a",
"Organization",
"VDC",
"Id",
"by",
"name",
"-",
"Organization",
"object",
"-",
"Organization",
"VDC",
"Name"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vdc.rb#L53-L63 | valid |
vmware/vcloud-rest | lib/vcloud-rest/vcloud/vdc.rb | VCloudClient.Connection.get_vdc_by_name | def get_vdc_by_name(organization, vdcName)
result = nil
organization[:vdcs].each do |vdc|
if vdc[0].downcase == vdcName.downcase
result = get_vdc(vdc[1])
end
end
result
end | ruby | def get_vdc_by_name(organization, vdcName)
result = nil
organization[:vdcs].each do |vdc|
if vdc[0].downcase == vdcName.downcase
result = get_vdc(vdc[1])
end
end
result
end | [
"def",
"get_vdc_by_name",
"(",
"organization",
",",
"vdcName",
")",
"result",
"=",
"nil",
"organization",
"[",
":vdcs",
"]",
".",
"each",
"do",
"|",
"vdc",
"|",
"if",
"vdc",
"[",
"0",
"]",
".",
"downcase",
"==",
"vdcName",
".",
"downcase",
"result",
"=... | Friendly helper method to fetch a Organization VDC by name
- Organization object
- Organization VDC Name | [
"Friendly",
"helper",
"method",
"to",
"fetch",
"a",
"Organization",
"VDC",
"by",
"name",
"-",
"Organization",
"object",
"-",
"Organization",
"VDC",
"Name"
] | 45425d93acf988946cac375b803100ad01206459 | https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vdc.rb#L69-L79 | valid |
markkorput/data-provider | lib/data_provider/container.rb | DataProvider.Container.add! | def add!(container)
### add container's providers ###
# internally providers are added in reverse order (last one first)
# so at runtime you it's easy and fast to grab the latest provider
# so when adding now, we have to reverse the providers to get them in the original order
container.providers.reverse.each do |definition|
add_provider(*definition)
end
### add container's provides (simple providers) ###
self.provides(container.provides)
### fallback provider ###
@fallback_provider = container.fallback_provider.block if container.fallback_provider
### add container's data ###
give!(container.data)
end | ruby | def add!(container)
### add container's providers ###
# internally providers are added in reverse order (last one first)
# so at runtime you it's easy and fast to grab the latest provider
# so when adding now, we have to reverse the providers to get them in the original order
container.providers.reverse.each do |definition|
add_provider(*definition)
end
### add container's provides (simple providers) ###
self.provides(container.provides)
### fallback provider ###
@fallback_provider = container.fallback_provider.block if container.fallback_provider
### add container's data ###
give!(container.data)
end | [
"def",
"add!",
"(",
"container",
")",
"container",
".",
"providers",
".",
"reverse",
".",
"each",
"do",
"|",
"definition",
"|",
"add_provider",
"(",
"*",
"definition",
")",
"end",
"self",
".",
"provides",
"(",
"container",
".",
"provides",
")",
"@fallback_... | "adding existing containers"-related methods
adds all the providers defined in the given module to this class | [
"adding",
"existing",
"containers",
"-",
"related",
"methods"
] | faf2d0e5bb88f31da8517974cd315dddb7ded80d | https://github.com/markkorput/data-provider/blob/faf2d0e5bb88f31da8517974cd315dddb7ded80d/lib/data_provider/container.rb#L149-L166 | valid |
markkorput/data-provider | lib/data_provider/container.rb | DataProvider.Container.get_provider | def get_provider(id, opts = {})
# get all matching providers
matching_provider_args = providers.find_all{|args| args.first == id}
# sort providers on priority, form high to low
matching_provider_args.sort! do |args_a, args_b|
# we want to sort from high priority to low, but providers with the same priority level
# should stay in the same order because among those, the last one added has the highest priority
# (last added means first in the array, since they are pushed into the beginning of the array)
(Provider.new(*args_b).priority || self.default_priority) <=> (Provider.new(*args_a).priority || self.default_priority)
end
# if no skip option is given, opts[:skip].to_i will result in zero, so it'll grab thefirst from the array
# if the array is empty, args will always turn out nil
args = matching_provider_args[opts[:skip].to_i]
return args.nil? ? nil : Provider.new(*args)
end | ruby | def get_provider(id, opts = {})
# get all matching providers
matching_provider_args = providers.find_all{|args| args.first == id}
# sort providers on priority, form high to low
matching_provider_args.sort! do |args_a, args_b|
# we want to sort from high priority to low, but providers with the same priority level
# should stay in the same order because among those, the last one added has the highest priority
# (last added means first in the array, since they are pushed into the beginning of the array)
(Provider.new(*args_b).priority || self.default_priority) <=> (Provider.new(*args_a).priority || self.default_priority)
end
# if no skip option is given, opts[:skip].to_i will result in zero, so it'll grab thefirst from the array
# if the array is empty, args will always turn out nil
args = matching_provider_args[opts[:skip].to_i]
return args.nil? ? nil : Provider.new(*args)
end | [
"def",
"get_provider",
"(",
"id",
",",
"opts",
"=",
"{",
"}",
")",
"matching_provider_args",
"=",
"providers",
".",
"find_all",
"{",
"|",
"args",
"|",
"args",
".",
"first",
"==",
"id",
"}",
"matching_provider_args",
".",
"sort!",
"do",
"|",
"args_a",
","... | returns the requested provider as a Provider object | [
"returns",
"the",
"requested",
"provider",
"as",
"a",
"Provider",
"object"
] | faf2d0e5bb88f31da8517974cd315dddb7ded80d | https://github.com/markkorput/data-provider/blob/faf2d0e5bb88f31da8517974cd315dddb7ded80d/lib/data_provider/container.rb#L296-L311 | valid |
rbialek/rack-tidy | lib/rack/tidy/cleaner.rb | Rack::Tidy.Cleaner.call! | def call!(env)
@env = env.dup
status, @headers, response = @app.call(@env)
if should_clean?
@headers.delete('Content-Length')
response = Rack::Response.new(
tidy_markup(response.respond_to?(:body) ? response.body : response),
status,
@headers
)
response.finish
response.to_a
else
[status, @headers, response]
end
end | ruby | def call!(env)
@env = env.dup
status, @headers, response = @app.call(@env)
if should_clean?
@headers.delete('Content-Length')
response = Rack::Response.new(
tidy_markup(response.respond_to?(:body) ? response.body : response),
status,
@headers
)
response.finish
response.to_a
else
[status, @headers, response]
end
end | [
"def",
"call!",
"(",
"env",
")",
"@env",
"=",
"env",
".",
"dup",
"status",
",",
"@headers",
",",
"response",
"=",
"@app",
".",
"call",
"(",
"@env",
")",
"if",
"should_clean?",
"@headers",
".",
"delete",
"(",
"'Content-Length'",
")",
"response",
"=",
"R... | thread safe version using shallow copy of env | [
"thread",
"safe",
"version",
"using",
"shallow",
"copy",
"of",
"env"
] | fb563cd33da97a3f852c1a7fa0a5fcb51ccbe2c5 | https://github.com/rbialek/rack-tidy/blob/fb563cd33da97a3f852c1a7fa0a5fcb51ccbe2c5/lib/rack/tidy/cleaner.rb#L34-L49 | valid |
stefankroes/scribble | lib/scribble/registry.rb | Scribble.Registry.for | def for *classes, &proc
classes.each { |receiver_class| ForClassContext.new(self, receiver_class).instance_eval &proc }
end | ruby | def for *classes, &proc
classes.each { |receiver_class| ForClassContext.new(self, receiver_class).instance_eval &proc }
end | [
"def",
"for",
"*",
"classes",
",",
"&",
"proc",
"classes",
".",
"each",
"{",
"|",
"receiver_class",
"|",
"ForClassContext",
".",
"new",
"(",
"self",
",",
"receiver_class",
")",
".",
"instance_eval",
"&",
"proc",
"}",
"end"
] | For class context | [
"For",
"class",
"context"
] | bd889cff108c1785cd28150763abd9b31782b44f | https://github.com/stefankroes/scribble/blob/bd889cff108c1785cd28150763abd9b31782b44f/lib/scribble/registry.rb#L16-L18 | valid |
stefankroes/scribble | lib/scribble/registry.rb | Scribble.Registry.evaluate | def evaluate name, receiver, args, call = nil, context = nil
matcher = Support::Matcher.new self, name, receiver, args
matcher.match.new(receiver, call, context).send name, *args
end | ruby | def evaluate name, receiver, args, call = nil, context = nil
matcher = Support::Matcher.new self, name, receiver, args
matcher.match.new(receiver, call, context).send name, *args
end | [
"def",
"evaluate",
"name",
",",
"receiver",
",",
"args",
",",
"call",
"=",
"nil",
",",
"context",
"=",
"nil",
"matcher",
"=",
"Support",
"::",
"Matcher",
".",
"new",
"self",
",",
"name",
",",
"receiver",
",",
"args",
"matcher",
".",
"match",
".",
"ne... | Evaluate or cast | [
"Evaluate",
"or",
"cast"
] | bd889cff108c1785cd28150763abd9b31782b44f | https://github.com/stefankroes/scribble/blob/bd889cff108c1785cd28150763abd9b31782b44f/lib/scribble/registry.rb#L65-L68 | valid |
mattbrictson/bundleup | lib/bundleup/console.rb | Bundleup.Console.progress | def progress(message, &block)
spinner = %w[/ - \\ |].cycle
print "\e[90m#{message}... \e[0m"
result = observing_thread(block, 0.5, 0.1) do
print "\r\e[90m#{message}... #{spinner.next} \e[0m"
end
puts "\r\e[90m#{message}... OK\e[0m"
result
rescue StandardError
puts "\r\e[90m#{message}...\e[0m \e[31mFAILED\e[0m"
raise
end | ruby | def progress(message, &block)
spinner = %w[/ - \\ |].cycle
print "\e[90m#{message}... \e[0m"
result = observing_thread(block, 0.5, 0.1) do
print "\r\e[90m#{message}... #{spinner.next} \e[0m"
end
puts "\r\e[90m#{message}... OK\e[0m"
result
rescue StandardError
puts "\r\e[90m#{message}...\e[0m \e[31mFAILED\e[0m"
raise
end | [
"def",
"progress",
"(",
"message",
",",
"&",
"block",
")",
"spinner",
"=",
"%w[",
"/",
" \\\\",
"|",
"]",
".",
"cycle",
"print",
"\"\\e[90m#{message}... \\e[0m\"",
"result",
"=",
"observing_thread",
"(",
"block",
",",
"0.5",
",",
"0.1",
")",
"do",
"print",... | Runs a block in the background and displays a spinner until it completes. | [
"Runs",
"a",
"block",
"in",
"the",
"background",
"and",
"displays",
"a",
"spinner",
"until",
"it",
"completes",
"."
] | 2d0c63fae76506a41af5827d5c7f6db570dfe473 | https://github.com/mattbrictson/bundleup/blob/2d0c63fae76506a41af5827d5c7f6db570dfe473/lib/bundleup/console.rb#L32-L43 | valid |
mattbrictson/bundleup | lib/bundleup/console.rb | Bundleup.Console.tableize | def tableize(rows, &block)
rows = rows.map(&block) if block
widths = max_length_of_each_column(rows)
rows.map do |row|
row.zip(widths).map { |value, width| value.ljust(width) }.join(" ")
end
end | ruby | def tableize(rows, &block)
rows = rows.map(&block) if block
widths = max_length_of_each_column(rows)
rows.map do |row|
row.zip(widths).map { |value, width| value.ljust(width) }.join(" ")
end
end | [
"def",
"tableize",
"(",
"rows",
",",
"&",
"block",
")",
"rows",
"=",
"rows",
".",
"map",
"(",
"&",
"block",
")",
"if",
"block",
"widths",
"=",
"max_length_of_each_column",
"(",
"rows",
")",
"rows",
".",
"map",
"do",
"|",
"row",
"|",
"row",
".",
"zi... | Given a two-dimensional Array of strings representing a table of data,
translate each row into a single string by joining the values with
whitespace such that all the columns are nicely aligned.
If a block is given, map the rows through the block first. These two
usages are equivalent:
tableize(rows.map(&something))
tableize(rows, &something)
Returns a one-dimensional Array of strings, each representing a formatted
row of the resulting table. | [
"Given",
"a",
"two",
"-",
"dimensional",
"Array",
"of",
"strings",
"representing",
"a",
"table",
"of",
"data",
"translate",
"each",
"row",
"into",
"a",
"single",
"string",
"by",
"joining",
"the",
"values",
"with",
"whitespace",
"such",
"that",
"all",
"the",
... | 2d0c63fae76506a41af5827d5c7f6db570dfe473 | https://github.com/mattbrictson/bundleup/blob/2d0c63fae76506a41af5827d5c7f6db570dfe473/lib/bundleup/console.rb#L58-L64 | valid |
mattbrictson/bundleup | lib/bundleup/console.rb | Bundleup.Console.observing_thread | def observing_thread(callable, initial_wait, periodic_wait)
thread = Thread.new(&callable)
wait_for_exit(thread, initial_wait)
loop do
break if wait_for_exit(thread, periodic_wait)
yield
end
thread.value
end | ruby | def observing_thread(callable, initial_wait, periodic_wait)
thread = Thread.new(&callable)
wait_for_exit(thread, initial_wait)
loop do
break if wait_for_exit(thread, periodic_wait)
yield
end
thread.value
end | [
"def",
"observing_thread",
"(",
"callable",
",",
"initial_wait",
",",
"periodic_wait",
")",
"thread",
"=",
"Thread",
".",
"new",
"(",
"&",
"callable",
")",
"wait_for_exit",
"(",
"thread",
",",
"initial_wait",
")",
"loop",
"do",
"break",
"if",
"wait_for_exit",
... | Starts the `callable` in a background thread and waits for it to complete.
If the callable fails with an exception, it will be raised here. Otherwise
the main thread is paused for an `initial_wait` time in seconds, and
subsequently for `periodic_wait` repeatedly until the thread completes.
After each wait, `yield` is called to allow a block to execute. | [
"Starts",
"the",
"callable",
"in",
"a",
"background",
"thread",
"and",
"waits",
"for",
"it",
"to",
"complete",
".",
"If",
"the",
"callable",
"fails",
"with",
"an",
"exception",
"it",
"will",
"be",
"raised",
"here",
".",
"Otherwise",
"the",
"main",
"thread"... | 2d0c63fae76506a41af5827d5c7f6db570dfe473 | https://github.com/mattbrictson/bundleup/blob/2d0c63fae76506a41af5827d5c7f6db570dfe473/lib/bundleup/console.rb#L79-L88 | valid |
leesharma/rescuetime | lib/rescuetime/collection.rb | Rescuetime.Collection.all | def all
requester = Rescuetime::Requester
host = HOST
parse_response requester.get(host, params)
end | ruby | def all
requester = Rescuetime::Requester
host = HOST
parse_response requester.get(host, params)
end | [
"def",
"all",
"requester",
"=",
"Rescuetime",
"::",
"Requester",
"host",
"=",
"HOST",
"parse_response",
"requester",
".",
"get",
"(",
"host",
",",
"params",
")",
"end"
] | Performs the rescuetime query and returns an array or csv response.
@return [Array, CSV]
@see Rescuetime::Requester#get | [
"Performs",
"the",
"rescuetime",
"query",
"and",
"returns",
"an",
"array",
"or",
"csv",
"response",
"."
] | c69e6d41f31dbaf5053be51a1e45293605612f1e | https://github.com/leesharma/rescuetime/blob/c69e6d41f31dbaf5053be51a1e45293605612f1e/lib/rescuetime/collection.rb#L41-L45 | valid |
leesharma/rescuetime | lib/rescuetime/collection.rb | Rescuetime.Collection.format | def format(format)
# Guard: fail if the passed format isn't on the whitelist
format = format.to_s
formatters.all.include?(format) || raise(Errors::InvalidFormatError)
@format = format
self
end | ruby | def format(format)
# Guard: fail if the passed format isn't on the whitelist
format = format.to_s
formatters.all.include?(format) || raise(Errors::InvalidFormatError)
@format = format
self
end | [
"def",
"format",
"(",
"format",
")",
"format",
"=",
"format",
".",
"to_s",
"formatters",
".",
"all",
".",
"include?",
"(",
"format",
")",
"||",
"raise",
"(",
"Errors",
"::",
"InvalidFormatError",
")",
"@format",
"=",
"format",
"self",
"end"
] | Sets the report format to a valid type
@param [#to_s] format desired report format (one of 'array' or 'csv')
@return [Rescuetime::Collection]
TODO: make chainable to the client | [
"Sets",
"the",
"report",
"format",
"to",
"a",
"valid",
"type"
] | c69e6d41f31dbaf5053be51a1e45293605612f1e | https://github.com/leesharma/rescuetime/blob/c69e6d41f31dbaf5053be51a1e45293605612f1e/lib/rescuetime/collection.rb#L64-L71 | valid |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.