Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
EvCell.get_min_height
(self)
Get the minimum possible height of cell, including at least one line for data. Returns: min_height (int): The mininum height of cell.
Get the minimum possible height of cell, including at least one line for data.
def get_min_height(self): """ Get the minimum possible height of cell, including at least one line for data. Returns: min_height (int): The mininum height of cell. """ return self.pad_top + self.pad_bottom + self.border_bottom + self.border_top + 1
[ "def", "get_min_height", "(", "self", ")", ":", "return", "self", ".", "pad_top", "+", "self", ".", "pad_bottom", "+", "self", ".", "border_bottom", "+", "self", ".", "border_top", "+", "1" ]
[ 682, 4 ]
[ 691, 88 ]
python
en
['en', 'error', 'th']
False
EvCell.get_min_width
(self)
Get the minimum possible width of cell, including at least one character-width for data. Returns: min_width (int): The minimum width of cell.
Get the minimum possible width of cell, including at least one character-width for data.
def get_min_width(self): """ Get the minimum possible width of cell, including at least one character-width for data. Returns: min_width (int): The minimum width of cell. """ return self.pad_left + self.pad_right + self.border_left + self.border_right + 1
[ "def", "get_min_width", "(", "self", ")", ":", "return", "self", ".", "pad_left", "+", "self", ".", "pad_right", "+", "self", ".", "border_left", "+", "self", ".", "border_right", "+", "1" ]
[ 693, 4 ]
[ 702, 88 ]
python
en
['en', 'error', 'th']
False
EvCell.get_height
(self)
Get natural height of cell, including padding. Returns: natural_height (int): Height of cell.
Get natural height of cell, including padding.
def get_height(self): """ Get natural height of cell, including padding. Returns: natural_height (int): Height of cell. """ return len(self.formatted)
[ "def", "get_height", "(", "self", ")", ":", "return", "len", "(", "self", ".", "formatted", ")" ]
[ 704, 4 ]
[ 712, 34 ]
python
en
['en', 'error', 'th']
False
EvCell.get_width
(self)
Get natural width of cell, including padding. Returns: natural_width (int): Width of cell.
Get natural width of cell, including padding.
def get_width(self): """ Get natural width of cell, including padding. Returns: natural_width (int): Width of cell. """ return m_len(self.formatted[0])
[ "def", "get_width", "(", "self", ")", ":", "return", "m_len", "(", "self", ".", "formatted", "[", "0", "]", ")" ]
[ 714, 4 ]
[ 722, 39 ]
python
en
['en', 'error', 'th']
False
EvCell.replace_data
(self, data, **kwargs)
Replace cell data. This causes a full reformat of the cell. Args: data (str): Cell data. Notes: The available keyword arguments are the same as for `EvCell.__init__`.
Replace cell data. This causes a full reformat of the cell.
def replace_data(self, data, **kwargs): """ Replace cell data. This causes a full reformat of the cell. Args: data (str): Cell data. Notes: The available keyword arguments are the same as for `EvCell.__init__`. """ # self.data = self._split_lines(unicode(data)) self.data = self._split_lines(_to_ansi(data)) self.raw_width = max(m_len(line) for line in self.data) self.raw_height = len(self.data) self.reformat(**kwargs)
[ "def", "replace_data", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "# self.data = self._split_lines(unicode(data))", "self", ".", "data", "=", "self", ".", "_split_lines", "(", "_to_ansi", "(", "data", ")", ")", "self", ".", "raw_width", "=", "max", "(", "m_len", "(", "line", ")", "for", "line", "in", "self", ".", "data", ")", "self", ".", "raw_height", "=", "len", "(", "self", ".", "data", ")", "self", ".", "reformat", "(", "*", "*", "kwargs", ")" ]
[ 724, 4 ]
[ 740, 31 ]
python
en
['en', 'error', 'th']
False
EvCell.reformat
(self, **kwargs)
Reformat the EvCell with new options Kwargs: The available keyword arguments are the same as for `EvCell.__init__`. Raises: Exception: If the cells cannot shrink enough to accomodate the options or the data given.
Reformat the EvCell with new options
def reformat(self, **kwargs): """ Reformat the EvCell with new options Kwargs: The available keyword arguments are the same as for `EvCell.__init__`. Raises: Exception: If the cells cannot shrink enough to accomodate the options or the data given. """ # keywords that require manipulation padwidth = kwargs.get("pad_width", None) padwidth = int(padwidth) if padwidth is not None else None self.pad_left = int(kwargs.pop("pad_left", padwidth if padwidth is not None else self.pad_left)) self.pad_right = int(kwargs.pop("pad_right", padwidth if padwidth is not None else self.pad_right)) self.pad_top = int(kwargs.pop("pad_top", padwidth if padwidth is not None else self.pad_top)) self.pad_bottom = int(kwargs.pop("pad_bottom", padwidth if padwidth is not None else self.pad_bottom)) self.enforce_size = kwargs.get("enforce_size", False) pad_char = kwargs.pop("pad_char", None) hpad_char = kwargs.pop("hpad_char", pad_char) self.hpad_char = hpad_char[0] if hpad_char else self.hpad_char vpad_char = kwargs.pop("vpad_char", pad_char) self.vpad_char = vpad_char[0] if vpad_char else self.vpad_char fillchar = kwargs.pop("fill_char", None) hfill_char = kwargs.pop("hfill_char", fillchar) self.hfill_char = hfill_char[0] if hfill_char else self.hfill_char vfill_char = kwargs.pop("vfill_char", fillchar) self.vfill_char = vfill_char[0] if vfill_char else self.vfill_char borderwidth = kwargs.get("border_width", None) self.border_left = kwargs.pop( "border_left", borderwidth if borderwidth is not None else self.border_left) self.border_right = kwargs.pop( "border_right", borderwidth if borderwidth is not None else self.border_right) self.border_top = kwargs.pop( "border_top", borderwidth if borderwidth is not None else self.border_top) self.border_bottom = kwargs.pop( "border_bottom", borderwidth if borderwidth is not None else self.border_bottom) borderchar = kwargs.get("border_char", None) self.border_left_char = kwargs.pop( "border_left_char", borderchar if borderchar else self.border_left_char) self.border_right_char = kwargs.pop( "border_right_char", borderchar if borderchar else self.border_right_char) self.border_top_char = kwargs.pop( "border_topchar", borderchar if borderchar else self.border_top_char) self.border_bottom_char = kwargs.pop( "border_bottom_char", borderchar if borderchar else self.border_bottom_char) corner_char = kwargs.get("corner_char", None) self.corner_top_left_char = kwargs.pop( "corner_top_left", corner_char if corner_char is not None else self.corner_top_left_char) self.corner_top_right_char = kwargs.pop( "corner_top_right", corner_char if corner_char is not None else self.corner_top_right_char) self.corner_bottom_left_char = kwargs.pop( "corner_bottom_left", corner_char if corner_char is not None else self.corner_bottom_left_char) self.corner_bottom_right_char = kwargs.pop( "corner_bottom_right", corner_char if corner_char is not None else self.corner_bottom_right_char) # this is used by the table to adjust size of cells with borders in the middle # of the table self.trim_horizontal = kwargs.pop("trim_horizontal", self.trim_horizontal) self.trim_vertical = kwargs.pop("trim_vertical", self.trim_vertical) # fill all other properties for key, value in kwargs.items(): setattr(self, key, value) # Handle sizes if "width" in kwargs: width = kwargs.pop("width") self.width = width - self.pad_left - self.pad_right\ - self.border_left - self.border_right + self.trim_horizontal # if self.width <= 0 and self.raw_width > 0: if self.width <= 0 < self.raw_width: raise Exception("Cell width too small, no room for data.") if "height" in kwargs: height = kwargs.pop("height") self.height = height - self.pad_top - self.pad_bottom\ - self.border_top - self.border_bottom + self.trim_vertical if self.height <= 0 < self.raw_height: raise Exception("Cell height too small, no room for data.") # reformat (to new sizes, padding, header and borders) self.formatted = self._reformat()
[ "def", "reformat", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# keywords that require manipulation", "padwidth", "=", "kwargs", ".", "get", "(", "\"pad_width\"", ",", "None", ")", "padwidth", "=", "int", "(", "padwidth", ")", "if", "padwidth", "is", "not", "None", "else", "None", "self", ".", "pad_left", "=", "int", "(", "kwargs", ".", "pop", "(", "\"pad_left\"", ",", "padwidth", "if", "padwidth", "is", "not", "None", "else", "self", ".", "pad_left", ")", ")", "self", ".", "pad_right", "=", "int", "(", "kwargs", ".", "pop", "(", "\"pad_right\"", ",", "padwidth", "if", "padwidth", "is", "not", "None", "else", "self", ".", "pad_right", ")", ")", "self", ".", "pad_top", "=", "int", "(", "kwargs", ".", "pop", "(", "\"pad_top\"", ",", "padwidth", "if", "padwidth", "is", "not", "None", "else", "self", ".", "pad_top", ")", ")", "self", ".", "pad_bottom", "=", "int", "(", "kwargs", ".", "pop", "(", "\"pad_bottom\"", ",", "padwidth", "if", "padwidth", "is", "not", "None", "else", "self", ".", "pad_bottom", ")", ")", "self", ".", "enforce_size", "=", "kwargs", ".", "get", "(", "\"enforce_size\"", ",", "False", ")", "pad_char", "=", "kwargs", ".", "pop", "(", "\"pad_char\"", ",", "None", ")", "hpad_char", "=", "kwargs", ".", "pop", "(", "\"hpad_char\"", ",", "pad_char", ")", "self", ".", "hpad_char", "=", "hpad_char", "[", "0", "]", "if", "hpad_char", "else", "self", ".", "hpad_char", "vpad_char", "=", "kwargs", ".", "pop", "(", "\"vpad_char\"", ",", "pad_char", ")", "self", ".", "vpad_char", "=", "vpad_char", "[", "0", "]", "if", "vpad_char", "else", "self", ".", "vpad_char", "fillchar", "=", "kwargs", ".", "pop", "(", "\"fill_char\"", ",", "None", ")", "hfill_char", "=", "kwargs", ".", "pop", "(", "\"hfill_char\"", ",", "fillchar", ")", "self", ".", "hfill_char", "=", "hfill_char", "[", "0", "]", "if", "hfill_char", "else", "self", ".", "hfill_char", "vfill_char", "=", "kwargs", ".", "pop", "(", "\"vfill_char\"", ",", "fillchar", ")", "self", ".", "vfill_char", "=", "vfill_char", "[", "0", "]", "if", "vfill_char", "else", "self", ".", "vfill_char", "borderwidth", "=", "kwargs", ".", "get", "(", "\"border_width\"", ",", "None", ")", "self", ".", "border_left", "=", "kwargs", ".", "pop", "(", "\"border_left\"", ",", "borderwidth", "if", "borderwidth", "is", "not", "None", "else", "self", ".", "border_left", ")", "self", ".", "border_right", "=", "kwargs", ".", "pop", "(", "\"border_right\"", ",", "borderwidth", "if", "borderwidth", "is", "not", "None", "else", "self", ".", "border_right", ")", "self", ".", "border_top", "=", "kwargs", ".", "pop", "(", "\"border_top\"", ",", "borderwidth", "if", "borderwidth", "is", "not", "None", "else", "self", ".", "border_top", ")", "self", ".", "border_bottom", "=", "kwargs", ".", "pop", "(", "\"border_bottom\"", ",", "borderwidth", "if", "borderwidth", "is", "not", "None", "else", "self", ".", "border_bottom", ")", "borderchar", "=", "kwargs", ".", "get", "(", "\"border_char\"", ",", "None", ")", "self", ".", "border_left_char", "=", "kwargs", ".", "pop", "(", "\"border_left_char\"", ",", "borderchar", "if", "borderchar", "else", "self", ".", "border_left_char", ")", "self", ".", "border_right_char", "=", "kwargs", ".", "pop", "(", "\"border_right_char\"", ",", "borderchar", "if", "borderchar", "else", "self", ".", "border_right_char", ")", "self", ".", "border_top_char", "=", "kwargs", ".", "pop", "(", "\"border_topchar\"", ",", "borderchar", "if", "borderchar", "else", "self", ".", "border_top_char", ")", "self", ".", "border_bottom_char", "=", "kwargs", ".", "pop", "(", "\"border_bottom_char\"", ",", "borderchar", "if", "borderchar", "else", "self", ".", "border_bottom_char", ")", "corner_char", "=", "kwargs", ".", "get", "(", "\"corner_char\"", ",", "None", ")", "self", ".", "corner_top_left_char", "=", "kwargs", ".", "pop", "(", "\"corner_top_left\"", ",", "corner_char", "if", "corner_char", "is", "not", "None", "else", "self", ".", "corner_top_left_char", ")", "self", ".", "corner_top_right_char", "=", "kwargs", ".", "pop", "(", "\"corner_top_right\"", ",", "corner_char", "if", "corner_char", "is", "not", "None", "else", "self", ".", "corner_top_right_char", ")", "self", ".", "corner_bottom_left_char", "=", "kwargs", ".", "pop", "(", "\"corner_bottom_left\"", ",", "corner_char", "if", "corner_char", "is", "not", "None", "else", "self", ".", "corner_bottom_left_char", ")", "self", ".", "corner_bottom_right_char", "=", "kwargs", ".", "pop", "(", "\"corner_bottom_right\"", ",", "corner_char", "if", "corner_char", "is", "not", "None", "else", "self", ".", "corner_bottom_right_char", ")", "# this is used by the table to adjust size of cells with borders in the middle", "# of the table", "self", ".", "trim_horizontal", "=", "kwargs", ".", "pop", "(", "\"trim_horizontal\"", ",", "self", ".", "trim_horizontal", ")", "self", ".", "trim_vertical", "=", "kwargs", ".", "pop", "(", "\"trim_vertical\"", ",", "self", ".", "trim_vertical", ")", "# fill all other properties", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "setattr", "(", "self", ",", "key", ",", "value", ")", "# Handle sizes", "if", "\"width\"", "in", "kwargs", ":", "width", "=", "kwargs", ".", "pop", "(", "\"width\"", ")", "self", ".", "width", "=", "width", "-", "self", ".", "pad_left", "-", "self", ".", "pad_right", "-", "self", ".", "border_left", "-", "self", ".", "border_right", "+", "self", ".", "trim_horizontal", "# if self.width <= 0 and self.raw_width > 0:", "if", "self", ".", "width", "<=", "0", "<", "self", ".", "raw_width", ":", "raise", "Exception", "(", "\"Cell width too small, no room for data.\"", ")", "if", "\"height\"", "in", "kwargs", ":", "height", "=", "kwargs", ".", "pop", "(", "\"height\"", ")", "self", ".", "height", "=", "height", "-", "self", ".", "pad_top", "-", "self", ".", "pad_bottom", "-", "self", ".", "border_top", "-", "self", ".", "border_bottom", "+", "self", ".", "trim_vertical", "if", "self", ".", "height", "<=", "0", "<", "self", ".", "raw_height", ":", "raise", "Exception", "(", "\"Cell height too small, no room for data.\"", ")", "# reformat (to new sizes, padding, header and borders)", "self", ".", "formatted", "=", "self", ".", "_reformat", "(", ")" ]
[ 742, 4 ]
[ 831, 41 ]
python
en
['en', 'error', 'th']
False
EvCell.get
(self)
Get data, padded and aligned in the form of a list of lines.
Get data, padded and aligned in the form of a list of lines.
def get(self): """ Get data, padded and aligned in the form of a list of lines. """ self.formatted = self._reformat() return self.formatted
[ "def", "get", "(", "self", ")", ":", "self", ".", "formatted", "=", "self", ".", "_reformat", "(", ")", "return", "self", ".", "formatted" ]
[ 833, 4 ]
[ 839, 29 ]
python
en
['en', 'error', 'th']
False
EvCell.__str__
(self)
returns cell contents on string form
returns cell contents on string form
def __str__(self): "returns cell contents on string form" self.formatted = self._reformat() return str(unicode(ANSIString("\n").join(self.formatted)))
[ "def", "__str__", "(", "self", ")", ":", "self", ".", "formatted", "=", "self", ".", "_reformat", "(", ")", "return", "str", "(", "unicode", "(", "ANSIString", "(", "\"\\n\"", ")", ".", "join", "(", "self", ".", "formatted", ")", ")", ")" ]
[ 845, 4 ]
[ 848, 66 ]
python
en
['en', 'en', 'en']
True
EvCell.__unicode__
(self)
returns cell contents
returns cell contents
def __unicode__(self): "returns cell contents" self.formatted = self._reformat() return unicode(ANSIString("\n").join(self.formatted))
[ "def", "__unicode__", "(", "self", ")", ":", "self", ".", "formatted", "=", "self", ".", "_reformat", "(", ")", "return", "unicode", "(", "ANSIString", "(", "\"\\n\"", ")", ".", "join", "(", "self", ".", "formatted", ")", ")" ]
[ 850, 4 ]
[ 853, 61 ]
python
en
['en', 'en', 'en']
True
EvColumn.__init__
(self, *args, **kwargs)
Args: Text for each row in the column Kwargs: All `EvCell.__init_` keywords are available, these settings will be persistently applied to every Cell in the column.
Args: Text for each row in the column
def __init__(self, *args, **kwargs): """ Args: Text for each row in the column Kwargs: All `EvCell.__init_` keywords are available, these settings will be persistently applied to every Cell in the column. """ self.options = kwargs # column-specific options self.column = [EvCell(data, **kwargs) for data in args]
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "options", "=", "kwargs", "# column-specific options", "self", ".", "column", "=", "[", "EvCell", "(", "data", ",", "*", "*", "kwargs", ")", "for", "data", "in", "args", "]" ]
[ 869, 4 ]
[ 881, 63 ]
python
en
['en', 'error', 'th']
False
EvColumn._balance
(self, **kwargs)
Make sure to adjust the width of all cells so we form a coherent and lined-up column. Will enforce column-specific options to cells. Kwargs: Extra keywords to modify the column setting. Same keywords as in `EvCell.__init__`.
Make sure to adjust the width of all cells so we form a coherent and lined-up column. Will enforce column-specific options to cells.
def _balance(self, **kwargs): """ Make sure to adjust the width of all cells so we form a coherent and lined-up column. Will enforce column-specific options to cells. Kwargs: Extra keywords to modify the column setting. Same keywords as in `EvCell.__init__`. """ col = self.column # fixed options for the column will override those requested in the call! # this is particularly relevant to things like width/height, to avoid # fixed-widths columns from being auto-balanced kwargs.update(self.options) # use fixed width or adjust to the largest cell if "width" not in kwargs: [cell.reformat() for cell in col] # this is necessary to get initial widths of all cells kwargs["width"] = max(cell.get_width() for cell in col) if col else 0 [cell.reformat(**kwargs) for cell in col]
[ "def", "_balance", "(", "self", ",", "*", "*", "kwargs", ")", ":", "col", "=", "self", ".", "column", "# fixed options for the column will override those requested in the call!", "# this is particularly relevant to things like width/height, to avoid", "# fixed-widths columns from being auto-balanced", "kwargs", ".", "update", "(", "self", ".", "options", ")", "# use fixed width or adjust to the largest cell", "if", "\"width\"", "not", "in", "kwargs", ":", "[", "cell", ".", "reformat", "(", ")", "for", "cell", "in", "col", "]", "# this is necessary to get initial widths of all cells", "kwargs", "[", "\"width\"", "]", "=", "max", "(", "cell", ".", "get_width", "(", ")", "for", "cell", "in", "col", ")", "if", "col", "else", "0", "[", "cell", ".", "reformat", "(", "*", "*", "kwargs", ")", "for", "cell", "in", "col", "]" ]
[ 883, 4 ]
[ 903, 49 ]
python
en
['en', 'error', 'th']
False
EvColumn.add_rows
(self, *args, **kwargs)
Add new cells to column. They will be inserted as a series of rows. It will inherit the options of the rest of the column's cells (use update to change options). Args: Texts for the new cells ypos (int, optional): Index position in table before which to insert the new column. Uses Python indexing, so to insert at the top, use `ypos=0`. If not given, data will be inserted at the end of the column. Kwargs: Available keywods as per `EvCell.__init__`.
Add new cells to column. They will be inserted as a series of rows. It will inherit the options of the rest of the column's cells (use update to change options).
def add_rows(self, *args, **kwargs): """ Add new cells to column. They will be inserted as a series of rows. It will inherit the options of the rest of the column's cells (use update to change options). Args: Texts for the new cells ypos (int, optional): Index position in table before which to insert the new column. Uses Python indexing, so to insert at the top, use `ypos=0`. If not given, data will be inserted at the end of the column. Kwargs: Available keywods as per `EvCell.__init__`. """ ypos = kwargs.get("ypos", None) if ypos is None or ypos > len(self.column): # add to the end self.column.extend([EvCell(data, **self.options) for data in args]) else: # insert cells before given index ypos = min(len(self.column) - 1, max(0, int(ypos))) new_cells = [EvCell(data, **self.options) for data in args] self.column = self.column[:ypos] + new_cells + self.column[ypos:]
[ "def", "add_rows", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ypos", "=", "kwargs", ".", "get", "(", "\"ypos\"", ",", "None", ")", "if", "ypos", "is", "None", "or", "ypos", ">", "len", "(", "self", ".", "column", ")", ":", "# add to the end", "self", ".", "column", ".", "extend", "(", "[", "EvCell", "(", "data", ",", "*", "*", "self", ".", "options", ")", "for", "data", "in", "args", "]", ")", "else", ":", "# insert cells before given index", "ypos", "=", "min", "(", "len", "(", "self", ".", "column", ")", "-", "1", ",", "max", "(", "0", ",", "int", "(", "ypos", ")", ")", ")", "new_cells", "=", "[", "EvCell", "(", "data", ",", "*", "*", "self", ".", "options", ")", "for", "data", "in", "args", "]", "self", ".", "column", "=", "self", ".", "column", "[", ":", "ypos", "]", "+", "new_cells", "+", "self", ".", "column", "[", "ypos", ":", "]" ]
[ 905, 4 ]
[ 931, 77 ]
python
en
['en', 'error', 'th']
False
EvColumn.reformat
(self, **kwargs)
Change the options for the column. Kwargs: Keywords as per `EvCell.__init__`.
Change the options for the column.
def reformat(self, **kwargs): """ Change the options for the column. Kwargs: Keywords as per `EvCell.__init__`. """ self._balance(**kwargs)
[ "def", "reformat", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_balance", "(", "*", "*", "kwargs", ")" ]
[ 934, 4 ]
[ 942, 31 ]
python
en
['en', 'error', 'th']
False
EvColumn.reformat_cell
(self, index, **kwargs)
reformat cell at given index, keeping column options if necessary. Args: index (int): Index location of the cell in the column, starting from 0 for the first row to Nrows-1. Kwargs: Keywords as per `EvCell.__init__`.
reformat cell at given index, keeping column options if necessary.
def reformat_cell(self, index, **kwargs): """ reformat cell at given index, keeping column options if necessary. Args: index (int): Index location of the cell in the column, starting from 0 for the first row to Nrows-1. Kwargs: Keywords as per `EvCell.__init__`. """ kwargs.update(self.options) self.column[index].reformat(**kwargs)
[ "def", "reformat_cell", "(", "self", ",", "index", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "self", ".", "options", ")", "self", ".", "column", "[", "index", "]", ".", "reformat", "(", "*", "*", "kwargs", ")" ]
[ 944, 4 ]
[ 958, 45 ]
python
en
['en', 'error', 'th']
False
EvTable.__init__
(self, *args, **kwargs)
Args: Header texts for the table. Kwargs: table (list of lists or list of `EvColumns`, optional): This is used to build the table in a quick way. If not given, the table will start out empty and `add_` methods need to be used to add rows/columns. header (bool, optional): `True`/`False` - turn off the header texts (`*args`) being treated as a header (such as not adding extra underlining) pad_width (int, optional): How much empty space to pad your cells with (default is 1) border (str, optional)): The border style to use. This is one of - `None` - No border drawing at all. - "table" - only a border around the whole table. - "tablecols" - table and column borders. (default) - "header" - only border under header. - "cols" - only vertical borders. - "incols" - vertical borders, no outer edges. - "rows" - only borders between rows. - "cells" - border around all cells. border_width (int, optional): Width of table borders, if border is active. Note that widths wider than 1 may give artifacts in the corners. Default is 1. corner_char (str, optional): Character to use in corners when border is active. Default is `+`. corner_top_left_char (str, optional): Character used for "nw" corner of table. Defaults to `corner_char`. corner_top_right_char (str, optional): Character used for "ne" corner of table. Defaults to `corner_char`. corner_bottom_left_char (str, optional): Character used for "sw" corner of table. Defaults to `corner_char`. corner_bottom_right_char (str, optional): Character used for "se" corner of table. Defaults to `corner_char`. pretty_corners (bool, optional): Use custom characters to make the table corners look "rounded". Uses UTF-8 characters. Defaults to `False` for maximum compatibility with various displays that may occationally have issues with UTF-8 characters. header_line_char (str, optional): Character to use for underlining the header row (default is '~'). Requires `border` to not be `None`. width (int, optional): Fixed width of table. If not set, width is set by the total width of each column. This will resize individual columns in the vertical direction to fit. height (int, optional): Fixed height of table. Defaults to being unset. Width is still given precedence. If given, table cells will crop text rather than expand vertically. evenwidth (bool, optional): Used with the `width` keyword. Adjusts columns to have as even width as possible. This often looks best also for mixed-length tables. Default is `False`. maxwidth (int, optional): This will set a maximum width of the table while allowing it to be smaller. Only if it grows wider than this size will it be resized by expanding horizontally (or crop `height` is given). This keyword has no meaning if `width` is set. Raises: Exception: If given erroneous input or width settings for the data. Notes: Beyond those table-specific keywords, the non-overlapping keywords of `EcCell.__init__` are also available. These will be passed down to every cell in the table.
Args: Header texts for the table.
def __init__(self, *args, **kwargs): """ Args: Header texts for the table. Kwargs: table (list of lists or list of `EvColumns`, optional): This is used to build the table in a quick way. If not given, the table will start out empty and `add_` methods need to be used to add rows/columns. header (bool, optional): `True`/`False` - turn off the header texts (`*args`) being treated as a header (such as not adding extra underlining) pad_width (int, optional): How much empty space to pad your cells with (default is 1) border (str, optional)): The border style to use. This is one of - `None` - No border drawing at all. - "table" - only a border around the whole table. - "tablecols" - table and column borders. (default) - "header" - only border under header. - "cols" - only vertical borders. - "incols" - vertical borders, no outer edges. - "rows" - only borders between rows. - "cells" - border around all cells. border_width (int, optional): Width of table borders, if border is active. Note that widths wider than 1 may give artifacts in the corners. Default is 1. corner_char (str, optional): Character to use in corners when border is active. Default is `+`. corner_top_left_char (str, optional): Character used for "nw" corner of table. Defaults to `corner_char`. corner_top_right_char (str, optional): Character used for "ne" corner of table. Defaults to `corner_char`. corner_bottom_left_char (str, optional): Character used for "sw" corner of table. Defaults to `corner_char`. corner_bottom_right_char (str, optional): Character used for "se" corner of table. Defaults to `corner_char`. pretty_corners (bool, optional): Use custom characters to make the table corners look "rounded". Uses UTF-8 characters. Defaults to `False` for maximum compatibility with various displays that may occationally have issues with UTF-8 characters. header_line_char (str, optional): Character to use for underlining the header row (default is '~'). Requires `border` to not be `None`. width (int, optional): Fixed width of table. If not set, width is set by the total width of each column. This will resize individual columns in the vertical direction to fit. height (int, optional): Fixed height of table. Defaults to being unset. Width is still given precedence. If given, table cells will crop text rather than expand vertically. evenwidth (bool, optional): Used with the `width` keyword. Adjusts columns to have as even width as possible. This often looks best also for mixed-length tables. Default is `False`. maxwidth (int, optional): This will set a maximum width of the table while allowing it to be smaller. Only if it grows wider than this size will it be resized by expanding horizontally (or crop `height` is given). This keyword has no meaning if `width` is set. Raises: Exception: If given erroneous input or width settings for the data. Notes: Beyond those table-specific keywords, the non-overlapping keywords of `EcCell.__init__` are also available. These will be passed down to every cell in the table. """ # at this point table is a 2D grid - a list of columns # x is the column position, y the row table = kwargs.pop("table", []) # header is a list of texts. We merge it to the table's top header = [_to_ansi(head) for head in args] self.header = header != [] if self.header: if table: excess = len(header) - len(table) if excess > 0: # header bigger than table table.extend([] for _ in range(excess)) elif excess < 0: # too short header header.extend(_to_ansi(["" for _ in range(abs(excess))])) for ix, heading in enumerate(header): table[ix].insert(0, heading) else: table = [[heading] for heading in header] # even though we inserted the header, we can still turn off # header border underling etc. We only allow this if a header # was actually set self.header = kwargs.pop("header", self.header) if self.header else False hchar = kwargs.pop("header_line_char", "~") self.header_line_char = hchar[0] if hchar else "~" border = kwargs.pop("border", "tablecols") if border is None: border = "none" if border not in ("none", "table", "tablecols", "header", "incols", "cols", "rows", "cells"): raise Exception("Unsupported border type: '%s'" % border) self.border = border # border settings are passed into Cell as well (so kwargs.get and not pop) self.border_width = kwargs.get("border_width", 1) self.corner_char = kwargs.get("corner_char", "+") pcorners = kwargs.pop("pretty_corners", False) self.corner_top_left_char = _to_ansi(kwargs.pop( "corner_top_left_char", '.' if pcorners else self.corner_char)) self.corner_top_right_char = _to_ansi(kwargs.pop( "corner_top_right_char", '.' if pcorners else self.corner_char)) self.corner_bottom_left_char = _to_ansi(kwargs.pop( "corner_bottom_left_char", ' ' if pcorners else self.corner_char)) self.corner_bottom_right_char = _to_ansi(kwargs.pop( "corner_bottom_right_char", ' ' if pcorners else self.corner_char)) self.width = kwargs.pop("width", None) self.height = kwargs.pop("height", None) self.evenwidth = kwargs.pop("evenwidth", False) self.maxwidth = kwargs.pop("maxwidth", None) if self.maxwidth and self.width and self.maxwidth < self.width: raise Exception("table maxwidth < table width!") # size in cell cols/rows self.ncols = len(table) self.nrows = max(len(col) for col in table) if table else 0 # size in characters (gets set when _balance is called) self.nwidth = 0 self.nheight = 0 # save options self.options = kwargs # use the temporary table to generate the table on the fly, as a list of EvColumns self.table = [EvColumn(*col, **kwargs) for col in table] # this is the actual working table self.worktable = None
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# at this point table is a 2D grid - a list of columns", "# x is the column position, y the row", "table", "=", "kwargs", ".", "pop", "(", "\"table\"", ",", "[", "]", ")", "# header is a list of texts. We merge it to the table's top", "header", "=", "[", "_to_ansi", "(", "head", ")", "for", "head", "in", "args", "]", "self", ".", "header", "=", "header", "!=", "[", "]", "if", "self", ".", "header", ":", "if", "table", ":", "excess", "=", "len", "(", "header", ")", "-", "len", "(", "table", ")", "if", "excess", ">", "0", ":", "# header bigger than table", "table", ".", "extend", "(", "[", "]", "for", "_", "in", "range", "(", "excess", ")", ")", "elif", "excess", "<", "0", ":", "# too short header", "header", ".", "extend", "(", "_to_ansi", "(", "[", "\"\"", "for", "_", "in", "range", "(", "abs", "(", "excess", ")", ")", "]", ")", ")", "for", "ix", ",", "heading", "in", "enumerate", "(", "header", ")", ":", "table", "[", "ix", "]", ".", "insert", "(", "0", ",", "heading", ")", "else", ":", "table", "=", "[", "[", "heading", "]", "for", "heading", "in", "header", "]", "# even though we inserted the header, we can still turn off", "# header border underling etc. We only allow this if a header", "# was actually set", "self", ".", "header", "=", "kwargs", ".", "pop", "(", "\"header\"", ",", "self", ".", "header", ")", "if", "self", ".", "header", "else", "False", "hchar", "=", "kwargs", ".", "pop", "(", "\"header_line_char\"", ",", "\"~\"", ")", "self", ".", "header_line_char", "=", "hchar", "[", "0", "]", "if", "hchar", "else", "\"~\"", "border", "=", "kwargs", ".", "pop", "(", "\"border\"", ",", "\"tablecols\"", ")", "if", "border", "is", "None", ":", "border", "=", "\"none\"", "if", "border", "not", "in", "(", "\"none\"", ",", "\"table\"", ",", "\"tablecols\"", ",", "\"header\"", ",", "\"incols\"", ",", "\"cols\"", ",", "\"rows\"", ",", "\"cells\"", ")", ":", "raise", "Exception", "(", "\"Unsupported border type: '%s'\"", "%", "border", ")", "self", ".", "border", "=", "border", "# border settings are passed into Cell as well (so kwargs.get and not pop)", "self", ".", "border_width", "=", "kwargs", ".", "get", "(", "\"border_width\"", ",", "1", ")", "self", ".", "corner_char", "=", "kwargs", ".", "get", "(", "\"corner_char\"", ",", "\"+\"", ")", "pcorners", "=", "kwargs", ".", "pop", "(", "\"pretty_corners\"", ",", "False", ")", "self", ".", "corner_top_left_char", "=", "_to_ansi", "(", "kwargs", ".", "pop", "(", "\"corner_top_left_char\"", ",", "'.'", "if", "pcorners", "else", "self", ".", "corner_char", ")", ")", "self", ".", "corner_top_right_char", "=", "_to_ansi", "(", "kwargs", ".", "pop", "(", "\"corner_top_right_char\"", ",", "'.'", "if", "pcorners", "else", "self", ".", "corner_char", ")", ")", "self", ".", "corner_bottom_left_char", "=", "_to_ansi", "(", "kwargs", ".", "pop", "(", "\"corner_bottom_left_char\"", ",", "' '", "if", "pcorners", "else", "self", ".", "corner_char", ")", ")", "self", ".", "corner_bottom_right_char", "=", "_to_ansi", "(", "kwargs", ".", "pop", "(", "\"corner_bottom_right_char\"", ",", "' '", "if", "pcorners", "else", "self", ".", "corner_char", ")", ")", "self", ".", "width", "=", "kwargs", ".", "pop", "(", "\"width\"", ",", "None", ")", "self", ".", "height", "=", "kwargs", ".", "pop", "(", "\"height\"", ",", "None", ")", "self", ".", "evenwidth", "=", "kwargs", ".", "pop", "(", "\"evenwidth\"", ",", "False", ")", "self", ".", "maxwidth", "=", "kwargs", ".", "pop", "(", "\"maxwidth\"", ",", "None", ")", "if", "self", ".", "maxwidth", "and", "self", ".", "width", "and", "self", ".", "maxwidth", "<", "self", ".", "width", ":", "raise", "Exception", "(", "\"table maxwidth < table width!\"", ")", "# size in cell cols/rows", "self", ".", "ncols", "=", "len", "(", "table", ")", "self", ".", "nrows", "=", "max", "(", "len", "(", "col", ")", "for", "col", "in", "table", ")", "if", "table", "else", "0", "# size in characters (gets set when _balance is called)", "self", ".", "nwidth", "=", "0", "self", ".", "nheight", "=", "0", "# save options", "self", ".", "options", "=", "kwargs", "# use the temporary table to generate the table on the fly, as a list of EvColumns", "self", ".", "table", "=", "[", "EvColumn", "(", "*", "col", ",", "*", "*", "kwargs", ")", "for", "col", "in", "table", "]", "# this is the actual working table", "self", ".", "worktable", "=", "None" ]
[ 987, 4 ]
[ 1117, 29 ]
python
en
['en', 'error', 'th']
False
EvTable._cellborders
(self, ix, iy, nx, ny, **kwargs)
Adds borders to the table by adjusting the input kwarg to instruct cells to build a border in the right positions. Args: ix (int): x index positions in table. iy (int): y index positions in table. nx (int): x size of table. ny (int): y size of table. Kwargs: Keywords as per `EvTable.__init__`. Returns: table (str): string with the correct borders. Notes: A copy of the kwarg is returned to the cell. This is method is called by self._borders.
Adds borders to the table by adjusting the input kwarg to instruct cells to build a border in the right positions.
def _cellborders(self, ix, iy, nx, ny, **kwargs): """ Adds borders to the table by adjusting the input kwarg to instruct cells to build a border in the right positions. Args: ix (int): x index positions in table. iy (int): y index positions in table. nx (int): x size of table. ny (int): y size of table. Kwargs: Keywords as per `EvTable.__init__`. Returns: table (str): string with the correct borders. Notes: A copy of the kwarg is returned to the cell. This is method is called by self._borders. """ ret = kwargs.copy() # handle the various border modes border = self.border header = self.header bwidth = self.border_width headchar = self.header_line_char def corners(ret): """Handle corners of table""" if ix == 0 and iy == 0: ret["corner_top_left_char"] = self.corner_top_left_char if ix == nx and iy == 0: ret["corner_top_right_char"] = self.corner_top_right_char if ix == 0 and iy == ny: ret["corner_bottom_left_char"] = self.corner_bottom_left_char if ix == nx and iy == ny: ret["corner_bottom_right_char"] = self.corner_bottom_right_char return ret def left_edge(ret): """add vertical border along left table edge""" if ix == 0: ret["border_left"] = bwidth # ret["trim_horizontal"] = bwidth return ret def top_edge(ret): """add border along top table edge""" if iy == 0: ret["border_top"] = bwidth # ret["trim_vertical"] = bwidth return ret def right_edge(ret): """add vertical border along right table edge""" if ix == nx: # and 0 < iy < ny: ret["border_right"] = bwidth # ret["trim_horizontal"] = 0 return ret def bottom_edge(ret): """add border along bottom table edge""" if iy == ny: ret["border_bottom"] = bwidth # ret["trim_vertical"] = bwidth return ret def cols(ret): """Adding vertical borders inside the table""" if 0 <= ix < nx: ret["border_right"] = bwidth return ret def rows(ret): """Adding horizontal borders inside the table""" if 0 <= iy < ny: ret["border_bottom"] = bwidth return ret def head(ret): """Add header underline""" if iy == 0: # put different bottom line for header ret["border_bottom"] = bwidth ret["border_bottom_char"] = headchar return ret # use the helper functions to define various # table "styles" if border in ("table", "tablecols", "cells"): ret = bottom_edge(right_edge(top_edge(left_edge(corners(ret))))) if border in ("cols", "tablecols", "cells"): ret = cols(right_edge(left_edge(ret))) if border in "incols": ret = cols(ret) if border in ("rows", "cells"): ret = rows(bottom_edge(top_edge(ret))) if header and border not in ("none", None): ret = head(ret) return ret
[ "def", "_cellborders", "(", "self", ",", "ix", ",", "iy", ",", "nx", ",", "ny", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "kwargs", ".", "copy", "(", ")", "# handle the various border modes", "border", "=", "self", ".", "border", "header", "=", "self", ".", "header", "bwidth", "=", "self", ".", "border_width", "headchar", "=", "self", ".", "header_line_char", "def", "corners", "(", "ret", ")", ":", "\"\"\"Handle corners of table\"\"\"", "if", "ix", "==", "0", "and", "iy", "==", "0", ":", "ret", "[", "\"corner_top_left_char\"", "]", "=", "self", ".", "corner_top_left_char", "if", "ix", "==", "nx", "and", "iy", "==", "0", ":", "ret", "[", "\"corner_top_right_char\"", "]", "=", "self", ".", "corner_top_right_char", "if", "ix", "==", "0", "and", "iy", "==", "ny", ":", "ret", "[", "\"corner_bottom_left_char\"", "]", "=", "self", ".", "corner_bottom_left_char", "if", "ix", "==", "nx", "and", "iy", "==", "ny", ":", "ret", "[", "\"corner_bottom_right_char\"", "]", "=", "self", ".", "corner_bottom_right_char", "return", "ret", "def", "left_edge", "(", "ret", ")", ":", "\"\"\"add vertical border along left table edge\"\"\"", "if", "ix", "==", "0", ":", "ret", "[", "\"border_left\"", "]", "=", "bwidth", "# ret[\"trim_horizontal\"] = bwidth", "return", "ret", "def", "top_edge", "(", "ret", ")", ":", "\"\"\"add border along top table edge\"\"\"", "if", "iy", "==", "0", ":", "ret", "[", "\"border_top\"", "]", "=", "bwidth", "# ret[\"trim_vertical\"] = bwidth", "return", "ret", "def", "right_edge", "(", "ret", ")", ":", "\"\"\"add vertical border along right table edge\"\"\"", "if", "ix", "==", "nx", ":", "# and 0 < iy < ny:", "ret", "[", "\"border_right\"", "]", "=", "bwidth", "# ret[\"trim_horizontal\"] = 0", "return", "ret", "def", "bottom_edge", "(", "ret", ")", ":", "\"\"\"add border along bottom table edge\"\"\"", "if", "iy", "==", "ny", ":", "ret", "[", "\"border_bottom\"", "]", "=", "bwidth", "# ret[\"trim_vertical\"] = bwidth", "return", "ret", "def", "cols", "(", "ret", ")", ":", "\"\"\"Adding vertical borders inside the table\"\"\"", "if", "0", "<=", "ix", "<", "nx", ":", "ret", "[", "\"border_right\"", "]", "=", "bwidth", "return", "ret", "def", "rows", "(", "ret", ")", ":", "\"\"\"Adding horizontal borders inside the table\"\"\"", "if", "0", "<=", "iy", "<", "ny", ":", "ret", "[", "\"border_bottom\"", "]", "=", "bwidth", "return", "ret", "def", "head", "(", "ret", ")", ":", "\"\"\"Add header underline\"\"\"", "if", "iy", "==", "0", ":", "# put different bottom line for header", "ret", "[", "\"border_bottom\"", "]", "=", "bwidth", "ret", "[", "\"border_bottom_char\"", "]", "=", "headchar", "return", "ret", "# use the helper functions to define various", "# table \"styles\"", "if", "border", "in", "(", "\"table\"", ",", "\"tablecols\"", ",", "\"cells\"", ")", ":", "ret", "=", "bottom_edge", "(", "right_edge", "(", "top_edge", "(", "left_edge", "(", "corners", "(", "ret", ")", ")", ")", ")", ")", "if", "border", "in", "(", "\"cols\"", ",", "\"tablecols\"", ",", "\"cells\"", ")", ":", "ret", "=", "cols", "(", "right_edge", "(", "left_edge", "(", "ret", ")", ")", ")", "if", "border", "in", "\"incols\"", ":", "ret", "=", "cols", "(", "ret", ")", "if", "border", "in", "(", "\"rows\"", ",", "\"cells\"", ")", ":", "ret", "=", "rows", "(", "bottom_edge", "(", "top_edge", "(", "ret", ")", ")", ")", "if", "header", "and", "border", "not", "in", "(", "\"none\"", ",", "None", ")", ":", "ret", "=", "head", "(", "ret", ")", "return", "ret" ]
[ 1122, 4 ]
[ 1228, 18 ]
python
en
['en', 'error', 'th']
False
EvTable._borders
(self)
Add borders to table. This is called from self._balance.
Add borders to table. This is called from self._balance.
def _borders(self): """ Add borders to table. This is called from self._balance. """ nx, ny = self.ncols - 1, self.nrows - 1 options = self.options for ix, col in enumerate(self.worktable): for iy, cell in enumerate(col): col.reformat_cell(iy, **self._cellborders(ix, iy, nx, ny, **options))
[ "def", "_borders", "(", "self", ")", ":", "nx", ",", "ny", "=", "self", ".", "ncols", "-", "1", ",", "self", ".", "nrows", "-", "1", "options", "=", "self", ".", "options", "for", "ix", ",", "col", "in", "enumerate", "(", "self", ".", "worktable", ")", ":", "for", "iy", ",", "cell", "in", "enumerate", "(", "col", ")", ":", "col", ".", "reformat_cell", "(", "iy", ",", "*", "*", "self", ".", "_cellborders", "(", "ix", ",", "iy", ",", "nx", ",", "ny", ",", "*", "*", "options", ")", ")" ]
[ 1230, 4 ]
[ 1238, 85 ]
python
en
['en', 'error', 'th']
False
EvTable._balance
(self)
Balance the table. This means to make sure all cells on the same row have the same height, that all columns have the same number of rows and that the table fits within the given width.
Balance the table. This means to make sure all cells on the same row have the same height, that all columns have the same number of rows and that the table fits within the given width.
def _balance(self): """ Balance the table. This means to make sure all cells on the same row have the same height, that all columns have the same number of rows and that the table fits within the given width. """ # we make all modifications on a working copy of the # actual table. This allows us to add columns/rows # and re-balance over and over without issue. self.worktable = deepcopy(self.table) # self._borders() # return options = copy(self.options) # balance number of rows to make a rectangular table # column by column ncols = len(self.worktable) nrows = [len(col) for col in self.worktable] nrowmax = max(nrows) if nrows else 0 for icol, nrow in enumerate(nrows): self.worktable[icol].reformat(**options) if nrow < nrowmax: # add more rows to too-short columns empty_rows = ["" for _ in range(nrowmax - nrow)] self.worktable[icol].add_rows(*empty_rows) self.ncols = ncols self.nrows = nrowmax # add borders - these add to the width/height, so we must do this before calculating width/height self._borders() # equalize widths within each column cwidths = [max(cell.get_width() for cell in col) for col in self.worktable] if self.width or self.maxwidth and self.maxwidth < sum(cwidths): # we set a table width. Horizontal cells will be evenly distributed and # expand vertically as needed (unless self.height is set, see below) # use fixed width, or set to maxwidth width = self.width if self.width else self.maxwidth if ncols: # get minimum possible cell widths for each row cwidths_min = [max(cell.get_min_width() for cell in col) for col in self.worktable] cwmin = sum(cwidths_min) # get which cols have separately set widths - these should be locked # note that we need to remove cwidths_min for each lock to avoid counting # it twice (in cwmin and in locked_cols) locked_cols = {icol: col.options['width'] - cwidths_min[icol] for icol, col in enumerate(self.worktable) if 'width' in col.options} locked_width = sum(locked_cols.values()) excess = width - cwmin - locked_width if len(locked_cols) >= ncols and excess: # we can't adjust the width at all - all columns are locked raise Exception("Cannot balance table to width %s - " "all columns have a set, fixed width summing to %s!" % ( self.width, sum(cwidths))) if excess < 0: # the locked cols makes it impossible raise Exception("Cannot shrink table width to %s. " "Minimum size (and/or fixed-width columns) " "sets minimum at %s." % (self.width, cwmin + locked_width)) if self.evenwidth: # make each column of equal width # use cwidths as a work-array to track weights cwidths = copy(cwidths_min) correction = 0 while correction < excess: # flood-fill the minimum table starting with the smallest columns ci = cwidths.index(min(cwidths)) if ci in locked_cols: # locked column, make sure it's not picked again cwidths[ci] += 9999 cwidths_min[ci] = locked_cols[ci] else: cwidths_min[ci] += 1 correction += 1 cwidths = cwidths_min else: # make each column expand more proportional to their data size # we use cwidth as a work-array to track weights correction = 0 while correction < excess: # fill wider columns first ci = cwidths.index(max(cwidths)) if ci in locked_cols: # locked column, make sure it's not picked again cwidths[ci] -= 9999 cwidths_min[ci] = locked_cols[ci] else: cwidths_min[ci] += 1 correction += 1 # give a just changed col less prio next run cwidths[ci] -= 3 cwidths = cwidths_min # reformat worktable (for width align) for ix, col in enumerate(self.worktable): try: col.reformat(width=cwidths[ix], **options) except Exception: raise # equalize heights for each row (we must do this here, since it may have changed to fit new widths) cheights = [max(cell.get_height() for cell in (col[iy] for col in self.worktable)) for iy in range(nrowmax)] if self.height: # if we are fixing the table height, it means cells must crop text instead of resizing. if nrowmax: # get minimum possible cell heights for each column cheights_min = [max(cell.get_min_height() for cell in (col[iy] for col in self.worktable)) for iy in range(nrowmax)] chmin = sum(cheights_min) # get which cols have separately set heights - these should be locked # note that we need to remove cheights_min for each lock to avoid counting # it twice (in chmin and in locked_cols) locked_cols = {icol: col.options['height'] - cheights_min[icol] for icol, col in enumerate(self.worktable) if 'height' in col.options} locked_height = sum(locked_cols.values()) excess = self.height - chmin - locked_height if chmin > self.height: # we cannot shrink any more raise Exception("Cannot shrink table height to %s. Minimum " "size (and/or fixed-height rows) sets minimum at %s." % ( self.height, chmin + locked_height)) # now we add all the extra height up to the desired table-height. # We do this so that the tallest cells gets expanded first (and # thus avoid getting cropped) even = self.height % 2 == 0 correction = 0 while correction < excess: # expand the cells with the most rows first if 0 <= correction < nrowmax and nrowmax > 1: # avoid adding to header first round (looks bad on very small tables) ci = cheights[1:].index(max(cheights[1:])) + 1 else: ci = cheights.index(max(cheights)) if ci in locked_cols: # locked row, make sure it's not picked again cheights[ci] -= 9999 cheights_min[ci] = locked_cols[ci] else: cheights_min[ci] += 1 # change balance if ci == 0 and self.header: # it doesn't look very good if header expands too fast cheights[ci] -= 2 if even else 3 cheights[ci] -= 2 if even else 1 correction += 1 cheights = cheights_min # we must tell cells to crop instead of expanding options["enforce_size"] = True # reformat table (for vertical align) for ix, col in enumerate(self.worktable): for iy, cell in enumerate(col): try: col.reformat_cell(iy, height=cheights[iy], **options) except Exception as e: msg = "ix=%s, iy=%s, height=%s: %s" % (ix, iy, cheights[iy], e.message) raise Exception("Error in vertical align:\n %s" % msg) # calculate actual table width/height in characters self.cwidth = sum(cwidths) self.cheight = sum(cheights)
[ "def", "_balance", "(", "self", ")", ":", "# we make all modifications on a working copy of the", "# actual table. This allows us to add columns/rows", "# and re-balance over and over without issue.", "self", ".", "worktable", "=", "deepcopy", "(", "self", ".", "table", ")", "# self._borders()", "# return", "options", "=", "copy", "(", "self", ".", "options", ")", "# balance number of rows to make a rectangular table", "# column by column", "ncols", "=", "len", "(", "self", ".", "worktable", ")", "nrows", "=", "[", "len", "(", "col", ")", "for", "col", "in", "self", ".", "worktable", "]", "nrowmax", "=", "max", "(", "nrows", ")", "if", "nrows", "else", "0", "for", "icol", ",", "nrow", "in", "enumerate", "(", "nrows", ")", ":", "self", ".", "worktable", "[", "icol", "]", ".", "reformat", "(", "*", "*", "options", ")", "if", "nrow", "<", "nrowmax", ":", "# add more rows to too-short columns", "empty_rows", "=", "[", "\"\"", "for", "_", "in", "range", "(", "nrowmax", "-", "nrow", ")", "]", "self", ".", "worktable", "[", "icol", "]", ".", "add_rows", "(", "*", "empty_rows", ")", "self", ".", "ncols", "=", "ncols", "self", ".", "nrows", "=", "nrowmax", "# add borders - these add to the width/height, so we must do this before calculating width/height", "self", ".", "_borders", "(", ")", "# equalize widths within each column", "cwidths", "=", "[", "max", "(", "cell", ".", "get_width", "(", ")", "for", "cell", "in", "col", ")", "for", "col", "in", "self", ".", "worktable", "]", "if", "self", ".", "width", "or", "self", ".", "maxwidth", "and", "self", ".", "maxwidth", "<", "sum", "(", "cwidths", ")", ":", "# we set a table width. Horizontal cells will be evenly distributed and", "# expand vertically as needed (unless self.height is set, see below)", "# use fixed width, or set to maxwidth", "width", "=", "self", ".", "width", "if", "self", ".", "width", "else", "self", ".", "maxwidth", "if", "ncols", ":", "# get minimum possible cell widths for each row", "cwidths_min", "=", "[", "max", "(", "cell", ".", "get_min_width", "(", ")", "for", "cell", "in", "col", ")", "for", "col", "in", "self", ".", "worktable", "]", "cwmin", "=", "sum", "(", "cwidths_min", ")", "# get which cols have separately set widths - these should be locked", "# note that we need to remove cwidths_min for each lock to avoid counting", "# it twice (in cwmin and in locked_cols)", "locked_cols", "=", "{", "icol", ":", "col", ".", "options", "[", "'width'", "]", "-", "cwidths_min", "[", "icol", "]", "for", "icol", ",", "col", "in", "enumerate", "(", "self", ".", "worktable", ")", "if", "'width'", "in", "col", ".", "options", "}", "locked_width", "=", "sum", "(", "locked_cols", ".", "values", "(", ")", ")", "excess", "=", "width", "-", "cwmin", "-", "locked_width", "if", "len", "(", "locked_cols", ")", ">=", "ncols", "and", "excess", ":", "# we can't adjust the width at all - all columns are locked", "raise", "Exception", "(", "\"Cannot balance table to width %s - \"", "\"all columns have a set, fixed width summing to %s!\"", "%", "(", "self", ".", "width", ",", "sum", "(", "cwidths", ")", ")", ")", "if", "excess", "<", "0", ":", "# the locked cols makes it impossible", "raise", "Exception", "(", "\"Cannot shrink table width to %s. \"", "\"Minimum size (and/or fixed-width columns) \"", "\"sets minimum at %s.\"", "%", "(", "self", ".", "width", ",", "cwmin", "+", "locked_width", ")", ")", "if", "self", ".", "evenwidth", ":", "# make each column of equal width", "# use cwidths as a work-array to track weights", "cwidths", "=", "copy", "(", "cwidths_min", ")", "correction", "=", "0", "while", "correction", "<", "excess", ":", "# flood-fill the minimum table starting with the smallest columns", "ci", "=", "cwidths", ".", "index", "(", "min", "(", "cwidths", ")", ")", "if", "ci", "in", "locked_cols", ":", "# locked column, make sure it's not picked again", "cwidths", "[", "ci", "]", "+=", "9999", "cwidths_min", "[", "ci", "]", "=", "locked_cols", "[", "ci", "]", "else", ":", "cwidths_min", "[", "ci", "]", "+=", "1", "correction", "+=", "1", "cwidths", "=", "cwidths_min", "else", ":", "# make each column expand more proportional to their data size", "# we use cwidth as a work-array to track weights", "correction", "=", "0", "while", "correction", "<", "excess", ":", "# fill wider columns first", "ci", "=", "cwidths", ".", "index", "(", "max", "(", "cwidths", ")", ")", "if", "ci", "in", "locked_cols", ":", "# locked column, make sure it's not picked again", "cwidths", "[", "ci", "]", "-=", "9999", "cwidths_min", "[", "ci", "]", "=", "locked_cols", "[", "ci", "]", "else", ":", "cwidths_min", "[", "ci", "]", "+=", "1", "correction", "+=", "1", "# give a just changed col less prio next run", "cwidths", "[", "ci", "]", "-=", "3", "cwidths", "=", "cwidths_min", "# reformat worktable (for width align)", "for", "ix", ",", "col", "in", "enumerate", "(", "self", ".", "worktable", ")", ":", "try", ":", "col", ".", "reformat", "(", "width", "=", "cwidths", "[", "ix", "]", ",", "*", "*", "options", ")", "except", "Exception", ":", "raise", "# equalize heights for each row (we must do this here, since it may have changed to fit new widths)", "cheights", "=", "[", "max", "(", "cell", ".", "get_height", "(", ")", "for", "cell", "in", "(", "col", "[", "iy", "]", "for", "col", "in", "self", ".", "worktable", ")", ")", "for", "iy", "in", "range", "(", "nrowmax", ")", "]", "if", "self", ".", "height", ":", "# if we are fixing the table height, it means cells must crop text instead of resizing.", "if", "nrowmax", ":", "# get minimum possible cell heights for each column", "cheights_min", "=", "[", "max", "(", "cell", ".", "get_min_height", "(", ")", "for", "cell", "in", "(", "col", "[", "iy", "]", "for", "col", "in", "self", ".", "worktable", ")", ")", "for", "iy", "in", "range", "(", "nrowmax", ")", "]", "chmin", "=", "sum", "(", "cheights_min", ")", "# get which cols have separately set heights - these should be locked", "# note that we need to remove cheights_min for each lock to avoid counting", "# it twice (in chmin and in locked_cols)", "locked_cols", "=", "{", "icol", ":", "col", ".", "options", "[", "'height'", "]", "-", "cheights_min", "[", "icol", "]", "for", "icol", ",", "col", "in", "enumerate", "(", "self", ".", "worktable", ")", "if", "'height'", "in", "col", ".", "options", "}", "locked_height", "=", "sum", "(", "locked_cols", ".", "values", "(", ")", ")", "excess", "=", "self", ".", "height", "-", "chmin", "-", "locked_height", "if", "chmin", ">", "self", ".", "height", ":", "# we cannot shrink any more", "raise", "Exception", "(", "\"Cannot shrink table height to %s. Minimum \"", "\"size (and/or fixed-height rows) sets minimum at %s.\"", "%", "(", "self", ".", "height", ",", "chmin", "+", "locked_height", ")", ")", "# now we add all the extra height up to the desired table-height.", "# We do this so that the tallest cells gets expanded first (and", "# thus avoid getting cropped)", "even", "=", "self", ".", "height", "%", "2", "==", "0", "correction", "=", "0", "while", "correction", "<", "excess", ":", "# expand the cells with the most rows first", "if", "0", "<=", "correction", "<", "nrowmax", "and", "nrowmax", ">", "1", ":", "# avoid adding to header first round (looks bad on very small tables)", "ci", "=", "cheights", "[", "1", ":", "]", ".", "index", "(", "max", "(", "cheights", "[", "1", ":", "]", ")", ")", "+", "1", "else", ":", "ci", "=", "cheights", ".", "index", "(", "max", "(", "cheights", ")", ")", "if", "ci", "in", "locked_cols", ":", "# locked row, make sure it's not picked again", "cheights", "[", "ci", "]", "-=", "9999", "cheights_min", "[", "ci", "]", "=", "locked_cols", "[", "ci", "]", "else", ":", "cheights_min", "[", "ci", "]", "+=", "1", "# change balance", "if", "ci", "==", "0", "and", "self", ".", "header", ":", "# it doesn't look very good if header expands too fast", "cheights", "[", "ci", "]", "-=", "2", "if", "even", "else", "3", "cheights", "[", "ci", "]", "-=", "2", "if", "even", "else", "1", "correction", "+=", "1", "cheights", "=", "cheights_min", "# we must tell cells to crop instead of expanding", "options", "[", "\"enforce_size\"", "]", "=", "True", "# reformat table (for vertical align)", "for", "ix", ",", "col", "in", "enumerate", "(", "self", ".", "worktable", ")", ":", "for", "iy", ",", "cell", "in", "enumerate", "(", "col", ")", ":", "try", ":", "col", ".", "reformat_cell", "(", "iy", ",", "height", "=", "cheights", "[", "iy", "]", ",", "*", "*", "options", ")", "except", "Exception", "as", "e", ":", "msg", "=", "\"ix=%s, iy=%s, height=%s: %s\"", "%", "(", "ix", ",", "iy", ",", "cheights", "[", "iy", "]", ",", "e", ".", "message", ")", "raise", "Exception", "(", "\"Error in vertical align:\\n %s\"", "%", "msg", ")", "# calculate actual table width/height in characters", "self", ".", "cwidth", "=", "sum", "(", "cwidths", ")", "self", ".", "cheight", "=", "sum", "(", "cheights", ")" ]
[ 1240, 4 ]
[ 1418, 36 ]
python
en
['en', 'error', 'th']
False
EvTable._generate_lines
(self)
Generates lines across all columns (each cell may contain multiple lines) This will also balance the table.
Generates lines across all columns (each cell may contain multiple lines) This will also balance the table.
def _generate_lines(self): """ Generates lines across all columns (each cell may contain multiple lines) This will also balance the table. """ self._balance() for iy in range(self.nrows): cell_row = [col[iy] for col in self.worktable] # this produces a list of lists, each of equal length cell_data = [cell.get() for cell in cell_row] cell_height = min(len(lines) for lines in cell_data) for iline in range(cell_height): yield ANSIString("").join(_to_ansi(celldata[iline] for celldata in cell_data))
[ "def", "_generate_lines", "(", "self", ")", ":", "self", ".", "_balance", "(", ")", "for", "iy", "in", "range", "(", "self", ".", "nrows", ")", ":", "cell_row", "=", "[", "col", "[", "iy", "]", "for", "col", "in", "self", ".", "worktable", "]", "# this produces a list of lists, each of equal length", "cell_data", "=", "[", "cell", ".", "get", "(", ")", "for", "cell", "in", "cell_row", "]", "cell_height", "=", "min", "(", "len", "(", "lines", ")", "for", "lines", "in", "cell_data", ")", "for", "iline", "in", "range", "(", "cell_height", ")", ":", "yield", "ANSIString", "(", "\"\"", ")", ".", "join", "(", "_to_ansi", "(", "celldata", "[", "iline", "]", "for", "celldata", "in", "cell_data", ")", ")" ]
[ 1420, 4 ]
[ 1433, 94 ]
python
en
['en', 'error', 'th']
False
EvTable.add_header
(self, *args, **kwargs)
Add header to table. This is a number of texts to be put at the top of the table. They will replace an existing header. Args: args (str): These strings will be used as the header texts. Kwargs: Same keywords as per `EvTable.__init__`. Will be applied to the new header's cells.
Add header to table. This is a number of texts to be put at the top of the table. They will replace an existing header.
def add_header(self, *args, **kwargs): """ Add header to table. This is a number of texts to be put at the top of the table. They will replace an existing header. Args: args (str): These strings will be used as the header texts. Kwargs: Same keywords as per `EvTable.__init__`. Will be applied to the new header's cells. """ self.header = True self.add_row(ypos=0, *args, **kwargs)
[ "def", "add_header", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "header", "=", "True", "self", ".", "add_row", "(", "ypos", "=", "0", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
[ 1435, 4 ]
[ 1449, 45 ]
python
en
['en', 'error', 'th']
False
EvTable.add_column
(self, *args, **kwargs)
Add a column to table. If there are more rows in new column than there are rows in the current table, the table will expand with empty rows in the other columns. If too few, the new column with get new empty rows. All filling rows are added to the end. Args: args (`EvColum` or multiple strings): Either a single EvColumn instance or a number of data string arguments to be used to create a new column. header (str, optional): The header text for the column xpos (int, optional): Index position in table *before* which to input new column. If not given, column will be added to the end of the table. Uses Python indexing (so first column is `xpos=0`) Kwargs: Other keywords as per `Cell.__init__`.
Add a column to table. If there are more rows in new column than there are rows in the current table, the table will expand with empty rows in the other columns. If too few, the new column with get new empty rows. All filling rows are added to the end.
def add_column(self, *args, **kwargs): """ Add a column to table. If there are more rows in new column than there are rows in the current table, the table will expand with empty rows in the other columns. If too few, the new column with get new empty rows. All filling rows are added to the end. Args: args (`EvColum` or multiple strings): Either a single EvColumn instance or a number of data string arguments to be used to create a new column. header (str, optional): The header text for the column xpos (int, optional): Index position in table *before* which to input new column. If not given, column will be added to the end of the table. Uses Python indexing (so first column is `xpos=0`) Kwargs: Other keywords as per `Cell.__init__`. """ # this will replace default options with new ones without changing default options = dict(listitems(self.options) + listitems(kwargs)) xpos = kwargs.get("xpos", None) column = EvColumn(*args, **options) wtable = self.ncols htable = self.nrows header = kwargs.get("header", None) if header: column.add_rows(unicode(header), ypos=0, **options) self.header = True elif self.header: # we have a header already. Offset column.add_rows("", ypos=0, **options) # Calculate whether the new column needs to expand to the # current table size, or if the table needs to expand to # the column size. # This needs to happen after the header rows have already been # added to the column in order for the size calculations to match. excess = len(column) - htable if excess > 0: # we need to add new rows to table for col in self.table: empty_rows = ["" for _ in range(excess)] col.add_rows(*empty_rows, **options) self.nrows += excess elif excess < 0: # we need to add new rows to new column empty_rows = ["" for _ in range(abs(excess))] column.add_rows(*empty_rows, **options) self.nrows -= excess if xpos is None or xpos > wtable - 1: # add to the end self.table.append(column) else: # insert column xpos = min(wtable - 1, max(0, int(xpos))) self.table.insert(xpos, column) self.ncols += 1
[ "def", "add_column", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# this will replace default options with new ones without changing default", "options", "=", "dict", "(", "listitems", "(", "self", ".", "options", ")", "+", "listitems", "(", "kwargs", ")", ")", "xpos", "=", "kwargs", ".", "get", "(", "\"xpos\"", ",", "None", ")", "column", "=", "EvColumn", "(", "*", "args", ",", "*", "*", "options", ")", "wtable", "=", "self", ".", "ncols", "htable", "=", "self", ".", "nrows", "header", "=", "kwargs", ".", "get", "(", "\"header\"", ",", "None", ")", "if", "header", ":", "column", ".", "add_rows", "(", "unicode", "(", "header", ")", ",", "ypos", "=", "0", ",", "*", "*", "options", ")", "self", ".", "header", "=", "True", "elif", "self", ".", "header", ":", "# we have a header already. Offset", "column", ".", "add_rows", "(", "\"\"", ",", "ypos", "=", "0", ",", "*", "*", "options", ")", "# Calculate whether the new column needs to expand to the", "# current table size, or if the table needs to expand to", "# the column size.", "# This needs to happen after the header rows have already been", "# added to the column in order for the size calculations to match.", "excess", "=", "len", "(", "column", ")", "-", "htable", "if", "excess", ">", "0", ":", "# we need to add new rows to table", "for", "col", "in", "self", ".", "table", ":", "empty_rows", "=", "[", "\"\"", "for", "_", "in", "range", "(", "excess", ")", "]", "col", ".", "add_rows", "(", "*", "empty_rows", ",", "*", "*", "options", ")", "self", ".", "nrows", "+=", "excess", "elif", "excess", "<", "0", ":", "# we need to add new rows to new column", "empty_rows", "=", "[", "\"\"", "for", "_", "in", "range", "(", "abs", "(", "excess", ")", ")", "]", "column", ".", "add_rows", "(", "*", "empty_rows", ",", "*", "*", "options", ")", "self", ".", "nrows", "-=", "excess", "if", "xpos", "is", "None", "or", "xpos", ">", "wtable", "-", "1", ":", "# add to the end", "self", ".", "table", ".", "append", "(", "column", ")", "else", ":", "# insert column", "xpos", "=", "min", "(", "wtable", "-", "1", ",", "max", "(", "0", ",", "int", "(", "xpos", ")", ")", ")", "self", ".", "table", ".", "insert", "(", "xpos", ",", "column", ")", "self", ".", "ncols", "+=", "1" ]
[ 1451, 4 ]
[ 1512, 23 ]
python
en
['en', 'error', 'th']
False
EvTable.add_row
(self, *args, **kwargs)
Add a row to table (not a header). If there are more cells in the given row than there are cells in the current table the table will be expanded with empty columns to match. These will be added to the end of the table. In the same way, adding a line with too few cells will lead to the last ones getting padded. Args: args (str): Any number of string argumnets to use as the data in the row (one cell per argument). ypos (int, optional): Index position in table before which to input new row. If not given, will be added to the end of the table. Uses Python indexing (so first row is `ypos=0`) Kwargs: Other keywords are as per `EvCell.__init__`.
Add a row to table (not a header). If there are more cells in the given row than there are cells in the current table the table will be expanded with empty columns to match. These will be added to the end of the table. In the same way, adding a line with too few cells will lead to the last ones getting padded.
def add_row(self, *args, **kwargs): """ Add a row to table (not a header). If there are more cells in the given row than there are cells in the current table the table will be expanded with empty columns to match. These will be added to the end of the table. In the same way, adding a line with too few cells will lead to the last ones getting padded. Args: args (str): Any number of string argumnets to use as the data in the row (one cell per argument). ypos (int, optional): Index position in table before which to input new row. If not given, will be added to the end of the table. Uses Python indexing (so first row is `ypos=0`) Kwargs: Other keywords are as per `EvCell.__init__`. """ # this will replace default options with new ones without changing default row = list(args) options = dict(listitems(self.options) + listitems(kwargs)) ypos = kwargs.get("ypos", None) wtable = self.ncols htable = self.nrows excess = len(row) - wtable if excess > 0: # we need to add new empty columns to table empty_rows = ["" for _ in range(htable)] self.table.extend([EvColumn(*empty_rows, **options) for _ in range(excess)]) self.ncols += excess elif excess < 0: # we need to add more cells to row row.extend(["" for _ in range(abs(excess))]) self.ncols -= excess if ypos is None or ypos > htable - 1: # add new row to the end for icol, col in enumerate(self.table): col.add_rows(row[icol], **options) else: # insert row elsewhere ypos = min(htable - 1, max(0, int(ypos))) for icol, col in enumerate(self.table): col.add_rows(row[icol], ypos=ypos, **options) self.nrows += 1
[ "def", "add_row", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# this will replace default options with new ones without changing default", "row", "=", "list", "(", "args", ")", "options", "=", "dict", "(", "listitems", "(", "self", ".", "options", ")", "+", "listitems", "(", "kwargs", ")", ")", "ypos", "=", "kwargs", ".", "get", "(", "\"ypos\"", ",", "None", ")", "wtable", "=", "self", ".", "ncols", "htable", "=", "self", ".", "nrows", "excess", "=", "len", "(", "row", ")", "-", "wtable", "if", "excess", ">", "0", ":", "# we need to add new empty columns to table", "empty_rows", "=", "[", "\"\"", "for", "_", "in", "range", "(", "htable", ")", "]", "self", ".", "table", ".", "extend", "(", "[", "EvColumn", "(", "*", "empty_rows", ",", "*", "*", "options", ")", "for", "_", "in", "range", "(", "excess", ")", "]", ")", "self", ".", "ncols", "+=", "excess", "elif", "excess", "<", "0", ":", "# we need to add more cells to row", "row", ".", "extend", "(", "[", "\"\"", "for", "_", "in", "range", "(", "abs", "(", "excess", ")", ")", "]", ")", "self", ".", "ncols", "-=", "excess", "if", "ypos", "is", "None", "or", "ypos", ">", "htable", "-", "1", ":", "# add new row to the end", "for", "icol", ",", "col", "in", "enumerate", "(", "self", ".", "table", ")", ":", "col", ".", "add_rows", "(", "row", "[", "icol", "]", ",", "*", "*", "options", ")", "else", ":", "# insert row elsewhere", "ypos", "=", "min", "(", "htable", "-", "1", ",", "max", "(", "0", ",", "int", "(", "ypos", ")", ")", ")", "for", "icol", ",", "col", "in", "enumerate", "(", "self", ".", "table", ")", ":", "col", ".", "add_rows", "(", "row", "[", "icol", "]", ",", "ypos", "=", "ypos", ",", "*", "*", "options", ")", "self", ".", "nrows", "+=", "1" ]
[ 1515, 4 ]
[ 1563, 23 ]
python
en
['en', 'error', 'th']
False
EvTable.reformat
(self, **kwargs)
Force a re-shape of the entire table. Kwargs: Table options as per `EvTable.__init__`.
Force a re-shape of the entire table.
def reformat(self, **kwargs): """ Force a re-shape of the entire table. Kwargs: Table options as per `EvTable.__init__`. """ self.width = kwargs.pop("width", self.width) self.height = kwargs.pop("height", self.height) for key, value in kwargs.items(): setattr(self, key, value) hchar = kwargs.pop("header_line_char", self.header_line_char) # border settings are also passed on into EvCells (so kwargs.get, not kwargs.pop) self.header_line_char = hchar[0] if hchar else self.header_line_char self.border_width = kwargs.get("border_width", self.border_width) self.corner_char = kwargs.get("corner_char", self.corner_char) self.header_line_char = kwargs.get("header_line_char", self.header_line_char) self.corner_top_left_char = _to_ansi(kwargs.pop("corner_top_left_char", self.corner_char)) self.corner_top_right_char = _to_ansi(kwargs.pop("corner_top_right_char", self.corner_char)) self.corner_bottom_left_char = _to_ansi(kwargs.pop("corner_bottom_left_char", self.corner_char)) self.corner_bottom_right_char = _to_ansi(kwargs.pop("corner_bottom_right_char", self.corner_char)) self.options.update(kwargs)
[ "def", "reformat", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "width", "=", "kwargs", ".", "pop", "(", "\"width\"", ",", "self", ".", "width", ")", "self", ".", "height", "=", "kwargs", ".", "pop", "(", "\"height\"", ",", "self", ".", "height", ")", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "setattr", "(", "self", ",", "key", ",", "value", ")", "hchar", "=", "kwargs", ".", "pop", "(", "\"header_line_char\"", ",", "self", ".", "header_line_char", ")", "# border settings are also passed on into EvCells (so kwargs.get, not kwargs.pop)", "self", ".", "header_line_char", "=", "hchar", "[", "0", "]", "if", "hchar", "else", "self", ".", "header_line_char", "self", ".", "border_width", "=", "kwargs", ".", "get", "(", "\"border_width\"", ",", "self", ".", "border_width", ")", "self", ".", "corner_char", "=", "kwargs", ".", "get", "(", "\"corner_char\"", ",", "self", ".", "corner_char", ")", "self", ".", "header_line_char", "=", "kwargs", ".", "get", "(", "\"header_line_char\"", ",", "self", ".", "header_line_char", ")", "self", ".", "corner_top_left_char", "=", "_to_ansi", "(", "kwargs", ".", "pop", "(", "\"corner_top_left_char\"", ",", "self", ".", "corner_char", ")", ")", "self", ".", "corner_top_right_char", "=", "_to_ansi", "(", "kwargs", ".", "pop", "(", "\"corner_top_right_char\"", ",", "self", ".", "corner_char", ")", ")", "self", ".", "corner_bottom_left_char", "=", "_to_ansi", "(", "kwargs", ".", "pop", "(", "\"corner_bottom_left_char\"", ",", "self", ".", "corner_char", ")", ")", "self", ".", "corner_bottom_right_char", "=", "_to_ansi", "(", "kwargs", ".", "pop", "(", "\"corner_bottom_right_char\"", ",", "self", ".", "corner_char", ")", ")", "self", ".", "options", ".", "update", "(", "kwargs", ")" ]
[ 1566, 4 ]
[ 1592, 35 ]
python
en
['en', 'error', 'th']
False
EvTable.reformat_column
(self, index, **kwargs)
Sends custom options to a specific column in the table. Args: index (int): Which column to reformat. The column index is given from 0 to Ncolumns-1. Kwargs: Column options as per `EvCell.__init__`. Raises: Exception: if an invalid index is found.
Sends custom options to a specific column in the table.
def reformat_column(self, index, **kwargs): """ Sends custom options to a specific column in the table. Args: index (int): Which column to reformat. The column index is given from 0 to Ncolumns-1. Kwargs: Column options as per `EvCell.__init__`. Raises: Exception: if an invalid index is found. """ if index > len(self.table): raise Exception("Not a valid column index") # we update the columns' options which means eventual width/height # will be 'locked in' and withstand auto-balancing width/height from the table later self.table[index].options.update(kwargs) self.table[index].reformat(**kwargs)
[ "def", "reformat_column", "(", "self", ",", "index", ",", "*", "*", "kwargs", ")", ":", "if", "index", ">", "len", "(", "self", ".", "table", ")", ":", "raise", "Exception", "(", "\"Not a valid column index\"", ")", "# we update the columns' options which means eventual width/height", "# will be 'locked in' and withstand auto-balancing width/height from the table later", "self", ".", "table", "[", "index", "]", ".", "options", ".", "update", "(", "kwargs", ")", "self", ".", "table", "[", "index", "]", ".", "reformat", "(", "*", "*", "kwargs", ")" ]
[ 1594, 4 ]
[ 1614, 44 ]
python
en
['en', 'error', 'th']
False
EvTable.get
(self)
Return lines of table as a list. Returns: table_lines (list): The lines of the table, in order.
Return lines of table as a list.
def get(self): """ Return lines of table as a list. Returns: table_lines (list): The lines of the table, in order. """ return [line for line in self._generate_lines()]
[ "def", "get", "(", "self", ")", ":", "return", "[", "line", "for", "line", "in", "self", ".", "_generate_lines", "(", ")", "]" ]
[ 1616, 4 ]
[ 1624, 56 ]
python
en
['en', 'error', 'th']
False
EvTable.__str__
(self)
print table (this also balances it)
print table (this also balances it)
def __str__(self): """print table (this also balances it)""" # h = "12345678901234567890123456789012345678901234567890123456789012345678901234567890" return str(unicode(ANSIString("\n").join([line for line in self._generate_lines()])))
[ "def", "__str__", "(", "self", ")", ":", "# h = \"12345678901234567890123456789012345678901234567890123456789012345678901234567890\"", "return", "str", "(", "unicode", "(", "ANSIString", "(", "\"\\n\"", ")", ".", "join", "(", "[", "line", "for", "line", "in", "self", ".", "_generate_lines", "(", ")", "]", ")", ")", ")" ]
[ 1626, 4 ]
[ 1629, 93 ]
python
en
['en', 'en', 'en']
True
QueuedMessage.__init__
(self, msg: OutboundMessage)
Create Wrapper for queued message. Automatically sets timestamp on create.
Create Wrapper for queued message.
def __init__(self, msg: OutboundMessage): """ Create Wrapper for queued message. Automatically sets timestamp on create. """ self.msg = msg self.timestamp = time.time()
[ "def", "__init__", "(", "self", ",", "msg", ":", "OutboundMessage", ")", ":", "self", ".", "msg", "=", "msg", "self", ".", "timestamp", "=", "time", ".", "time", "(", ")" ]
[ 19, 4 ]
[ 26, 36 ]
python
en
['en', 'error', 'th']
False
QueuedMessage.older_than
(self, compare_timestamp: float)
Age Comparison. Allows you to test age as compared to the provided timestamp. Args: compare_timestamp: The timestamp to compare
Age Comparison.
def older_than(self, compare_timestamp: float) -> bool: """ Age Comparison. Allows you to test age as compared to the provided timestamp. Args: compare_timestamp: The timestamp to compare """ return self.timestamp < compare_timestamp
[ "def", "older_than", "(", "self", ",", "compare_timestamp", ":", "float", ")", "->", "bool", ":", "return", "self", ".", "timestamp", "<", "compare_timestamp" ]
[ 28, 4 ]
[ 37, 49 ]
python
en
['en', 'error', 'th']
False
DeliveryQueue.__init__
(self)
Initialize an instance of DeliveryQueue. This uses an in memory structure to queue messages.
Initialize an instance of DeliveryQueue.
def __init__(self) -> None: """ Initialize an instance of DeliveryQueue. This uses an in memory structure to queue messages. """ self.queue_by_key = {} self.ttl_seconds = 604800
[ "def", "__init__", "(", "self", ")", "->", "None", ":", "self", ".", "queue_by_key", "=", "{", "}", "self", ".", "ttl_seconds", "=", "604800" ]
[ 47, 4 ]
[ 55, 33 ]
python
en
['en', 'error', 'th']
False
DeliveryQueue.expire_messages
(self, ttl=None)
Expire messages that are past the time limit. Args: ttl: Optional. Allows override of configured ttl
Expire messages that are past the time limit.
def expire_messages(self, ttl=None): """ Expire messages that are past the time limit. Args: ttl: Optional. Allows override of configured ttl """ ttl_seconds = ttl or self.ttl_seconds horizon = time.time() - ttl_seconds for key in self.queue_by_key.keys(): self.queue_by_key[key] = [ wm for wm in self.queue_by_key[key] if not wm.older_than(horizon) ]
[ "def", "expire_messages", "(", "self", ",", "ttl", "=", "None", ")", ":", "ttl_seconds", "=", "ttl", "or", "self", ".", "ttl_seconds", "horizon", "=", "time", ".", "time", "(", ")", "-", "ttl_seconds", "for", "key", "in", "self", ".", "queue_by_key", ".", "keys", "(", ")", ":", "self", ".", "queue_by_key", "[", "key", "]", "=", "[", "wm", "for", "wm", "in", "self", ".", "queue_by_key", "[", "key", "]", "if", "not", "wm", ".", "older_than", "(", "horizon", ")", "]" ]
[ 57, 4 ]
[ 70, 13 ]
python
en
['en', 'error', 'th']
False
DeliveryQueue.add_message
(self, msg: OutboundMessage)
Add an OutboundMessage to delivery queue. The message is added once per recipient key Args: msg: The OutboundMessage to add
Add an OutboundMessage to delivery queue.
def add_message(self, msg: OutboundMessage): """ Add an OutboundMessage to delivery queue. The message is added once per recipient key Args: msg: The OutboundMessage to add """ keys = set() if msg.target: keys.update(msg.target.recipient_keys) if msg.reply_to_verkey: keys.add(msg.reply_to_verkey) wrapped_msg = QueuedMessage(msg) for recipient_key in keys: if recipient_key not in self.queue_by_key: self.queue_by_key[recipient_key] = [] self.queue_by_key[recipient_key].append(wrapped_msg)
[ "def", "add_message", "(", "self", ",", "msg", ":", "OutboundMessage", ")", ":", "keys", "=", "set", "(", ")", "if", "msg", ".", "target", ":", "keys", ".", "update", "(", "msg", ".", "target", ".", "recipient_keys", ")", "if", "msg", ".", "reply_to_verkey", ":", "keys", ".", "add", "(", "msg", ".", "reply_to_verkey", ")", "wrapped_msg", "=", "QueuedMessage", "(", "msg", ")", "for", "recipient_key", "in", "keys", ":", "if", "recipient_key", "not", "in", "self", ".", "queue_by_key", ":", "self", ".", "queue_by_key", "[", "recipient_key", "]", "=", "[", "]", "self", ".", "queue_by_key", "[", "recipient_key", "]", ".", "append", "(", "wrapped_msg", ")" ]
[ 72, 4 ]
[ 90, 64 ]
python
en
['en', 'error', 'th']
False
DeliveryQueue.has_message_for_key
(self, key: str)
Check for queued messages by key. Args: key: The key to use for lookup
Check for queued messages by key.
def has_message_for_key(self, key: str): """ Check for queued messages by key. Args: key: The key to use for lookup """ if key in self.queue_by_key and len(self.queue_by_key[key]): return True return False
[ "def", "has_message_for_key", "(", "self", ",", "key", ":", "str", ")", ":", "if", "key", "in", "self", ".", "queue_by_key", "and", "len", "(", "self", ".", "queue_by_key", "[", "key", "]", ")", ":", "return", "True", "return", "False" ]
[ 92, 4 ]
[ 101, 20 ]
python
en
['en', 'error', 'th']
False
DeliveryQueue.message_count_for_key
(self, key: str)
Count of queued messages by key. Args: key: The key to use for lookup
Count of queued messages by key.
def message_count_for_key(self, key: str): """ Count of queued messages by key. Args: key: The key to use for lookup """ if key in self.queue_by_key: return len(self.queue_by_key[key]) else: return 0
[ "def", "message_count_for_key", "(", "self", ",", "key", ":", "str", ")", ":", "if", "key", "in", "self", ".", "queue_by_key", ":", "return", "len", "(", "self", ".", "queue_by_key", "[", "key", "]", ")", "else", ":", "return", "0" ]
[ 103, 4 ]
[ 113, 20 ]
python
en
['en', 'error', 'th']
False
DeliveryQueue.get_one_message_for_key
(self, key: str)
Remove and return a matching message. Args: key: The key to use for lookup
Remove and return a matching message.
def get_one_message_for_key(self, key: str): """ Remove and return a matching message. Args: key: The key to use for lookup """ if key in self.queue_by_key: return self.queue_by_key[key].pop(0).msg
[ "def", "get_one_message_for_key", "(", "self", ",", "key", ":", "str", ")", ":", "if", "key", "in", "self", ".", "queue_by_key", ":", "return", "self", ".", "queue_by_key", "[", "key", "]", ".", "pop", "(", "0", ")", ".", "msg" ]
[ 115, 4 ]
[ 123, 52 ]
python
en
['en', 'error', 'th']
False
DeliveryQueue.inspect_all_messages_for_key
(self, key: str)
Return all messages for key. Args: key: The key to use for lookup
Return all messages for key.
def inspect_all_messages_for_key(self, key: str): """ Return all messages for key. Args: key: The key to use for lookup """ if key in self.queue_by_key: for wrapped_msg in self.queue_by_key[key]: yield wrapped_msg.msg
[ "def", "inspect_all_messages_for_key", "(", "self", ",", "key", ":", "str", ")", ":", "if", "key", "in", "self", ".", "queue_by_key", ":", "for", "wrapped_msg", "in", "self", ".", "queue_by_key", "[", "key", "]", ":", "yield", "wrapped_msg", ".", "msg" ]
[ 125, 4 ]
[ 134, 37 ]
python
en
['en', 'error', 'th']
False
DeliveryQueue.remove_message_for_key
(self, key: str, msg: OutboundMessage)
Remove specified message from queue for key. Args: key: The key to use for lookup msg: The message to remove from the queue
Remove specified message from queue for key.
def remove_message_for_key(self, key: str, msg: OutboundMessage): """ Remove specified message from queue for key. Args: key: The key to use for lookup msg: The message to remove from the queue """ if key in self.queue_by_key: for wrapped_msg in self.queue_by_key[key]: if wrapped_msg.msg == msg: self.queue_by_key[key].remove(wrapped_msg) if not self.queue_by_key[key]: del self.queue_by_key[key] break
[ "def", "remove_message_for_key", "(", "self", ",", "key", ":", "str", ",", "msg", ":", "OutboundMessage", ")", ":", "if", "key", "in", "self", ".", "queue_by_key", ":", "for", "wrapped_msg", "in", "self", ".", "queue_by_key", "[", "key", "]", ":", "if", "wrapped_msg", ".", "msg", "==", "msg", ":", "self", ".", "queue_by_key", "[", "key", "]", ".", "remove", "(", "wrapped_msg", ")", "if", "not", "self", ".", "queue_by_key", "[", "key", "]", ":", "del", "self", ".", "queue_by_key", "[", "key", "]", "break" ]
[ 136, 4 ]
[ 150, 25 ]
python
en
['en', 'error', 'th']
False
PolicyLearner.__init__
( self, outcome_learner=GradientBoostingRegressor(), treatment_learner=GradientBoostingClassifier(), policy_learner=DecisionTreeClassifier(), clip_bounds=(1e-3, 1 - 1e-3), n_fold=5, random_state=None, calibration=False, )
Initialize a treatment assignment policy learner. Args: outcome_learner (optional): a regression model to estimate outcomes policy_learner (optional): a classification model to estimate treatment assignment. It needs to take `sample_weight` as an input argument for `fit()` clip_bounds (tuple, optional): lower and upper bounds for clipping propensity scores to avoid division by zero in PolicyLearner.fit() n_fold (int, optional): the number of cross validation folds for outcome_learner random_state (int or RandomState, optional): a seed (int) or random number generator (RandomState)
Initialize a treatment assignment policy learner.
def __init__( self, outcome_learner=GradientBoostingRegressor(), treatment_learner=GradientBoostingClassifier(), policy_learner=DecisionTreeClassifier(), clip_bounds=(1e-3, 1 - 1e-3), n_fold=5, random_state=None, calibration=False, ): """Initialize a treatment assignment policy learner. Args: outcome_learner (optional): a regression model to estimate outcomes policy_learner (optional): a classification model to estimate treatment assignment. It needs to take `sample_weight` as an input argument for `fit()` clip_bounds (tuple, optional): lower and upper bounds for clipping propensity scores to avoid division by zero in PolicyLearner.fit() n_fold (int, optional): the number of cross validation folds for outcome_learner random_state (int or RandomState, optional): a seed (int) or random number generator (RandomState) """ self.model_mu = outcome_learner self.model_w = treatment_learner self.model_pi = policy_learner self.clip_bounds = clip_bounds self.cv = KFold(n_splits=n_fold, shuffle=True, random_state=random_state) self.calibration = calibration self._y_pred, self._tau_pred, self._w_pred, self._dr_score = ( None, None, None, None, )
[ "def", "__init__", "(", "self", ",", "outcome_learner", "=", "GradientBoostingRegressor", "(", ")", ",", "treatment_learner", "=", "GradientBoostingClassifier", "(", ")", ",", "policy_learner", "=", "DecisionTreeClassifier", "(", ")", ",", "clip_bounds", "=", "(", "1e-3", ",", "1", "-", "1e-3", ")", ",", "n_fold", "=", "5", ",", "random_state", "=", "None", ",", "calibration", "=", "False", ",", ")", ":", "self", ".", "model_mu", "=", "outcome_learner", "self", ".", "model_w", "=", "treatment_learner", "self", ".", "model_pi", "=", "policy_learner", "self", ".", "clip_bounds", "=", "clip_bounds", "self", ".", "cv", "=", "KFold", "(", "n_splits", "=", "n_fold", ",", "shuffle", "=", "True", ",", "random_state", "=", "random_state", ")", "self", ".", "calibration", "=", "calibration", "self", ".", "_y_pred", ",", "self", ".", "_tau_pred", ",", "self", ".", "_w_pred", ",", "self", ".", "_dr_score", "=", "(", "None", ",", "None", ",", "None", ",", "None", ",", ")" ]
[ 21, 4 ]
[ 54, 9 ]
python
en
['en', 'en', 'en']
True
PolicyLearner.fit
(self, X, treatment, y, p=None, dhat=None)
Fit the treatment assignment policy learner. Args: X (np.matrix): a feature matrix treatment (np.array): a treatment vector (1 if treated, otherwise 0) y (np.array): an outcome vector p (optional, np.array): user provided propensity score vector between 0 and 1 dhat (optinal, np.array): user provided predicted treatment effect vector Returns: self: returns an instance of self.
Fit the treatment assignment policy learner.
def fit(self, X, treatment, y, p=None, dhat=None): """Fit the treatment assignment policy learner. Args: X (np.matrix): a feature matrix treatment (np.array): a treatment vector (1 if treated, otherwise 0) y (np.array): an outcome vector p (optional, np.array): user provided propensity score vector between 0 and 1 dhat (optinal, np.array): user provided predicted treatment effect vector Returns: self: returns an instance of self. """ logger.info( "generating out-of-fold CV outcome estimates with {}".format(self.model_mu) ) self._outcome_estimate(X, treatment, y) if dhat is not None: self._tau_pred = dhat if p is None: self._treatment_estimate(X, treatment) else: self._w_pred = np.clip(p, self.clip_bounds[0], self.clip_bounds[1]) # Doubly Robust Modification self._dr_score = self._tau_pred + (treatment - self._w_pred) / self._w_pred / ( 1 - self._w_pred ) * (y - self._y_pred) target = self._dr_score.copy() target = np.sign(target) logger.info("training the treatment assignment model, {}".format(self.model_pi)) self.model_pi.fit(X, target, sample_weight=abs(self._dr_score)) return self
[ "def", "fit", "(", "self", ",", "X", ",", "treatment", ",", "y", ",", "p", "=", "None", ",", "dhat", "=", "None", ")", ":", "logger", ".", "info", "(", "\"generating out-of-fold CV outcome estimates with {}\"", ".", "format", "(", "self", ".", "model_mu", ")", ")", "self", ".", "_outcome_estimate", "(", "X", ",", "treatment", ",", "y", ")", "if", "dhat", "is", "not", "None", ":", "self", ".", "_tau_pred", "=", "dhat", "if", "p", "is", "None", ":", "self", ".", "_treatment_estimate", "(", "X", ",", "treatment", ")", "else", ":", "self", ".", "_w_pred", "=", "np", ".", "clip", "(", "p", ",", "self", ".", "clip_bounds", "[", "0", "]", ",", "self", ".", "clip_bounds", "[", "1", "]", ")", "# Doubly Robust Modification", "self", ".", "_dr_score", "=", "self", ".", "_tau_pred", "+", "(", "treatment", "-", "self", ".", "_w_pred", ")", "/", "self", ".", "_w_pred", "/", "(", "1", "-", "self", ".", "_w_pred", ")", "*", "(", "y", "-", "self", ".", "_y_pred", ")", "target", "=", "self", ".", "_dr_score", ".", "copy", "(", ")", "target", "=", "np", ".", "sign", "(", "target", ")", "logger", ".", "info", "(", "\"training the treatment assignment model, {}\"", ".", "format", "(", "self", ".", "model_pi", ")", ")", "self", ".", "model_pi", ".", "fit", "(", "X", ",", "target", ",", "sample_weight", "=", "abs", "(", "self", ".", "_dr_score", ")", ")", "return", "self" ]
[ 108, 4 ]
[ 146, 19 ]
python
en
['en', 'en', 'en']
True
PolicyLearner.predict
(self, X)
Predict treatment assignment that optimizes the outcome. Args: X (np.matrix): a feature matrix Returns: (numpy.ndarray): predictions of treatment assignment.
Predict treatment assignment that optimizes the outcome.
def predict(self, X): """Predict treatment assignment that optimizes the outcome. Args: X (np.matrix): a feature matrix Returns: (numpy.ndarray): predictions of treatment assignment. """ return self.model_pi.predict(X)
[ "def", "predict", "(", "self", ",", "X", ")", ":", "return", "self", ".", "model_pi", ".", "predict", "(", "X", ")" ]
[ 148, 4 ]
[ 158, 39 ]
python
en
['en', 'en', 'en']
True
PolicyLearner.predict_proba
(self, X)
Predict treatment assignment score that optimizes the outcome. Args: X (np.matrix): a feature matrix Returns: (numpy.ndarray): predictions of treatment assignment score.
Predict treatment assignment score that optimizes the outcome.
def predict_proba(self, X): """Predict treatment assignment score that optimizes the outcome. Args: X (np.matrix): a feature matrix Returns: (numpy.ndarray): predictions of treatment assignment score. """ pi_hat = self.model_pi.predict_proba(X)[:, 1] return pi_hat
[ "def", "predict_proba", "(", "self", ",", "X", ")", ":", "pi_hat", "=", "self", ".", "model_pi", ".", "predict_proba", "(", "X", ")", "[", ":", ",", "1", "]", "return", "pi_hat" ]
[ 160, 4 ]
[ 172, 21 ]
python
en
['en', 'en', 'en']
True
main
(args=sys.argv)
Main command line entry point.
Main command line entry point.
def main(args=sys.argv): """ Main command line entry point. """ usage = USAGE % ((args[0],) * 6) try: popts, args = getopt.getopt(args[1:], "l:f:F:o:O:P:LS:a:N:vhVHgs") except getopt.GetoptError: print(usage, file=sys.stderr) return 2 try: return main_inner(popts, args, usage) except Exception: if '-v' in dict(popts): print(file=sys.stderr) print('*' * 65, file=sys.stderr) print('An unhandled exception occurred while highlighting.', file=sys.stderr) print('Please report the whole traceback to the issue tracker at', file=sys.stderr) print('<https://bitbucket.org/birkenfeld/pygments-main/issues>.', file=sys.stderr) print('*' * 65, file=sys.stderr) print(file=sys.stderr) raise import traceback info = traceback.format_exception(*sys.exc_info()) msg = info[-1].strip() if len(info) >= 3: # extract relevant file and position info msg += '\n (f%s)' % info[-2].split('\n')[0].strip()[1:] print(file=sys.stderr) print('*** Error while highlighting:', file=sys.stderr) print(msg, file=sys.stderr) print('*** If this is a bug you want to report, please rerun with -v.', file=sys.stderr) return 1
[ "def", "main", "(", "args", "=", "sys", ".", "argv", ")", ":", "usage", "=", "USAGE", "%", "(", "(", "args", "[", "0", "]", ",", ")", "*", "6", ")", "try", ":", "popts", ",", "args", "=", "getopt", ".", "getopt", "(", "args", "[", "1", ":", "]", ",", "\"l:f:F:o:O:P:LS:a:N:vhVHgs\"", ")", "except", "getopt", ".", "GetoptError", ":", "print", "(", "usage", ",", "file", "=", "sys", ".", "stderr", ")", "return", "2", "try", ":", "return", "main_inner", "(", "popts", ",", "args", ",", "usage", ")", "except", "Exception", ":", "if", "'-v'", "in", "dict", "(", "popts", ")", ":", "print", "(", "file", "=", "sys", ".", "stderr", ")", "print", "(", "'*'", "*", "65", ",", "file", "=", "sys", ".", "stderr", ")", "print", "(", "'An unhandled exception occurred while highlighting.'", ",", "file", "=", "sys", ".", "stderr", ")", "print", "(", "'Please report the whole traceback to the issue tracker at'", ",", "file", "=", "sys", ".", "stderr", ")", "print", "(", "'<https://bitbucket.org/birkenfeld/pygments-main/issues>.'", ",", "file", "=", "sys", ".", "stderr", ")", "print", "(", "'*'", "*", "65", ",", "file", "=", "sys", ".", "stderr", ")", "print", "(", "file", "=", "sys", ".", "stderr", ")", "raise", "import", "traceback", "info", "=", "traceback", ".", "format_exception", "(", "*", "sys", ".", "exc_info", "(", ")", ")", "msg", "=", "info", "[", "-", "1", "]", ".", "strip", "(", ")", "if", "len", "(", "info", ")", ">=", "3", ":", "# extract relevant file and position info", "msg", "+=", "'\\n (f%s)'", "%", "info", "[", "-", "2", "]", ".", "split", "(", "'\\n'", ")", "[", "0", "]", ".", "strip", "(", ")", "[", "1", ":", "]", "print", "(", "file", "=", "sys", ".", "stderr", ")", "print", "(", "'*** Error while highlighting:'", ",", "file", "=", "sys", ".", "stderr", ")", "print", "(", "msg", ",", "file", "=", "sys", ".", "stderr", ")", "print", "(", "'*** If this is a bug you want to report, please rerun with -v.'", ",", "file", "=", "sys", ".", "stderr", ")", "return", "1" ]
[ 490, 0 ]
[ 528, 16 ]
python
en
['en', 'error', 'th']
False
NumbersTest.test_even
(self)
Test that numbers between 0 and 5 are all even.
Test that numbers between 0 and 5 are all even.
def test_even(self): """Test that numbers between 0 and 5 are all even. """ for i in range(0, 2): with self.subTest(i=i): self.assertEqual(i % 2, 0)
[ "def", "test_even", "(", "self", ")", ":", "for", "i", "in", "range", "(", "0", ",", "2", ")", ":", "with", "self", ".", "subTest", "(", "i", "=", "i", ")", ":", "self", ".", "assertEqual", "(", "i", "%", "2", ",", "0", ")" ]
[ 10, 4 ]
[ 15, 42 ]
python
en
['en', 'en', 'en']
True
Resource.from_resource
(cls: Type[R], other: R, rkey: Optional[str]=None, location: Optional[str]=None, kind: Optional[str]=None, serialization: Optional[str]=None, **kwargs)
Create a Resource by copying another Resource, possibly overriding elements along the way. NOTE WELL: if you pass in kwargs, we assume that any values are safe to use as-is and DO NOT COPY THEM. Otherwise, we SHALLOW COPY other.attrs for the new Resource. :param other: the base Resource we're copying :param rkey: optional new rkey :param location: optional new location :param kind: optional new kind :param serialization: optional new original input serialization :param kwargs: optional new key-value pairs -- see discussion about copying above!
Create a Resource by copying another Resource, possibly overriding elements along the way.
def from_resource(cls: Type[R], other: R, rkey: Optional[str]=None, location: Optional[str]=None, kind: Optional[str]=None, serialization: Optional[str]=None, **kwargs) -> R: """ Create a Resource by copying another Resource, possibly overriding elements along the way. NOTE WELL: if you pass in kwargs, we assume that any values are safe to use as-is and DO NOT COPY THEM. Otherwise, we SHALLOW COPY other.attrs for the new Resource. :param other: the base Resource we're copying :param rkey: optional new rkey :param location: optional new location :param kind: optional new kind :param serialization: optional new original input serialization :param kwargs: optional new key-value pairs -- see discussion about copying above! """ # rkey and location are required positional arguments. Fine. new_rkey = rkey or other.rkey new_location = location or other.location # Make a shallow-copied dict that we can muck with... new_attrs = dict(kwargs) if kwargs else dict(other) # Don't include kind unless it comes in on this call. if kind: new_attrs['kind'] = kind else: new_attrs.pop('kind', None) # Don't include serialization at all if we don't have one. if serialization: new_attrs['serialization'] = serialization elif other.serialization: new_attrs['serialization'] = other.serialization # Make sure that things that shouldn't propagate are gone... new_attrs.pop('rkey', None) new_attrs.pop('location', None) new_attrs.pop('_errors', None) new_attrs.pop('_errored', None) new_attrs.pop('_referenced_by', None) # ...and finally, use new_attrs for all the keyword args when we set up # the new instance. return cls(new_rkey, new_location, **new_attrs)
[ "def", "from_resource", "(", "cls", ":", "Type", "[", "R", "]", ",", "other", ":", "R", ",", "rkey", ":", "Optional", "[", "str", "]", "=", "None", ",", "location", ":", "Optional", "[", "str", "]", "=", "None", ",", "kind", ":", "Optional", "[", "str", "]", "=", "None", ",", "serialization", ":", "Optional", "[", "str", "]", "=", "None", ",", "*", "*", "kwargs", ")", "->", "R", ":", "# rkey and location are required positional arguments. Fine.", "new_rkey", "=", "rkey", "or", "other", ".", "rkey", "new_location", "=", "location", "or", "other", ".", "location", "# Make a shallow-copied dict that we can muck with...", "new_attrs", "=", "dict", "(", "kwargs", ")", "if", "kwargs", "else", "dict", "(", "other", ")", "# Don't include kind unless it comes in on this call.", "if", "kind", ":", "new_attrs", "[", "'kind'", "]", "=", "kind", "else", ":", "new_attrs", ".", "pop", "(", "'kind'", ",", "None", ")", "# Don't include serialization at all if we don't have one.", "if", "serialization", ":", "new_attrs", "[", "'serialization'", "]", "=", "serialization", "elif", "other", ".", "serialization", ":", "new_attrs", "[", "'serialization'", "]", "=", "other", ".", "serialization", "# Make sure that things that shouldn't propagate are gone...", "new_attrs", ".", "pop", "(", "'rkey'", ",", "None", ")", "new_attrs", ".", "pop", "(", "'location'", ",", "None", ")", "new_attrs", ".", "pop", "(", "'_errors'", ",", "None", ")", "new_attrs", ".", "pop", "(", "'_errored'", ",", "None", ")", "new_attrs", ".", "pop", "(", "'_referenced_by'", ",", "None", ")", "# ...and finally, use new_attrs for all the keyword args when we set up", "# the new instance.", "return", "cls", "(", "new_rkey", ",", "new_location", ",", "*", "*", "new_attrs", ")" ]
[ 111, 4 ]
[ 160, 55 ]
python
en
['en', 'error', 'th']
False
Resource.from_dict
(cls: Type[R], rkey: str, location: str, serialization: Optional[str], attrs: Dict)
Create a Resource or subclass thereof from a dictionary. The new Resource's rkey and location must be handed in explicitly. The difference between this and simply intializing a Resource object is that from_dict will introspect the attrs passed in and create whatever kind of Resource matches attrs['kind'] -- so for example, if kind is "Mapping", this method will return a Mapping rather than a Resource. :param rkey: unique identifier for this source, should be short :param location: where should a human go to find the source of this resource? :param serialization: original input serialization of obj :param attrs: dictionary from which to initialize the new object
Create a Resource or subclass thereof from a dictionary. The new Resource's rkey and location must be handed in explicitly.
def from_dict(cls: Type[R], rkey: str, location: str, serialization: Optional[str], attrs: Dict) -> R: """ Create a Resource or subclass thereof from a dictionary. The new Resource's rkey and location must be handed in explicitly. The difference between this and simply intializing a Resource object is that from_dict will introspect the attrs passed in and create whatever kind of Resource matches attrs['kind'] -- so for example, if kind is "Mapping", this method will return a Mapping rather than a Resource. :param rkey: unique identifier for this source, should be short :param location: where should a human go to find the source of this resource? :param serialization: original input serialization of obj :param attrs: dictionary from which to initialize the new object """ # So this is a touch odd but here we go. We want to use the Kind here to find # the correct type. ambassador = sys.modules['ambassador'] resource_class: Type[R] = getattr(ambassador, attrs['kind'], None) if not resource_class: resource_class = getattr(ambassador, 'AC' + attrs[ 'kind' ], cls) # print("%s.from_dict: %s => %s" % (cls, attrs['kind'], resource_class)) return resource_class(rkey, location=location, serialization=serialization, **attrs)
[ "def", "from_dict", "(", "cls", ":", "Type", "[", "R", "]", ",", "rkey", ":", "str", ",", "location", ":", "str", ",", "serialization", ":", "Optional", "[", "str", "]", ",", "attrs", ":", "Dict", ")", "->", "R", ":", "# So this is a touch odd but here we go. We want to use the Kind here to find", "# the correct type.", "ambassador", "=", "sys", ".", "modules", "[", "'ambassador'", "]", "resource_class", ":", "Type", "[", "R", "]", "=", "getattr", "(", "ambassador", ",", "attrs", "[", "'kind'", "]", ",", "None", ")", "if", "not", "resource_class", ":", "resource_class", "=", "getattr", "(", "ambassador", ",", "'AC'", "+", "attrs", "[", "'kind'", "]", ",", "cls", ")", "# print(\"%s.from_dict: %s => %s\" % (cls, attrs['kind'], resource_class))", "return", "resource_class", "(", "rkey", ",", "location", "=", "location", ",", "serialization", "=", "serialization", ",", "*", "*", "attrs", ")" ]
[ 163, 4 ]
[ 190, 92 ]
python
en
['en', 'error', 'th']
False
Resource.from_yaml
(cls: Type[R], rkey: str, location: str, serialization: str)
Create a Resource from a YAML serialization. The new Resource's rkey and location must be handed in explicitly, and of course in this case the serialization is mandatory. Raises an exception if the serialization is not parseable. :param rkey: unique identifier for this source, should be short :param location: where should a human go to find the source of this resource? :param serialization: original input serialization of obj
Create a Resource from a YAML serialization. The new Resource's rkey and location must be handed in explicitly, and of course in this case the serialization is mandatory.
def from_yaml(cls: Type[R], rkey: str, location: str, serialization: str) -> R: """ Create a Resource from a YAML serialization. The new Resource's rkey and location must be handed in explicitly, and of course in this case the serialization is mandatory. Raises an exception if the serialization is not parseable. :param rkey: unique identifier for this source, should be short :param location: where should a human go to find the source of this resource? :param serialization: original input serialization of obj """ attrs = parse_yaml(serialization) return cls.from_dict(rkey, location, serialization, attrs)
[ "def", "from_yaml", "(", "cls", ":", "Type", "[", "R", "]", ",", "rkey", ":", "str", ",", "location", ":", "str", ",", "serialization", ":", "str", ")", "->", "R", ":", "attrs", "=", "parse_yaml", "(", "serialization", ")", "return", "cls", ".", "from_dict", "(", "rkey", ",", "location", ",", "serialization", ",", "attrs", ")" ]
[ 193, 4 ]
[ 208, 66 ]
python
en
['en', 'error', 'th']
False
Monitor.__init__
(self)
Creates a Web server on a background thread.
Creates a Web server on a background thread.
def __init__(self): """Creates a Web server on a background thread.""" self.server = HTTPServer((MONITOR_HOST, MONITOR_PORT), self.MonitorHandler) self.thread = Thread(target=self.server.serve_forever) self.thread.daemon = True
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "server", "=", "HTTPServer", "(", "(", "MONITOR_HOST", ",", "MONITOR_PORT", ")", ",", "self", ".", "MonitorHandler", ")", "self", ".", "thread", "=", "Thread", "(", "target", "=", "self", ".", "server", ".", "serve_forever", ")", "self", ".", "thread", ".", "daemon", "=", "True" ]
[ 41, 4 ]
[ 47, 33 ]
python
en
['en', 'ga', 'en']
True
Monitor.start
(self)
Starts the Web server background thread.
Starts the Web server background thread.
def start(self): """Starts the Web server background thread.""" self.thread.start()
[ "def", "start", "(", "self", ")", ":", "self", ".", "thread", ".", "start", "(", ")" ]
[ 49, 4 ]
[ 52, 27 ]
python
en
['en', 'en', 'en']
True
Monitor.stop
(self)
Stops the Web server and background thread.
Stops the Web server and background thread.
def stop(self): """Stops the Web server and background thread.""" self.server.shutdown() self.server.server_close()
[ "def", "stop", "(", "self", ")", ":", "self", ".", "server", ".", "shutdown", "(", ")", "self", ".", "server", ".", "server_close", "(", ")" ]
[ 54, 4 ]
[ 58, 34 ]
python
en
['en', 'en', 'en']
True
Main.twitter_callback
(self, tweet)
Analyzes Trump tweets, trades stocks, and tweets about it.
Analyzes Trump tweets, trades stocks, and tweets about it.
def twitter_callback(self, tweet): """Analyzes Trump tweets, trades stocks, and tweets about it.""" # Initialize the Analysis, Logs, Trading, and Twitter instances inside # the callback to create separate httplib2 instances per thread. analysis = Analysis(logs_to_cloud=LOGS_TO_CLOUD) logs = Logs(name='main-callback', to_cloud=LOGS_TO_CLOUD) # Analyze the tweet. companies = analysis.find_companies(tweet) logs.info('Using companies: %s' % companies) if not companies: return # Trade stocks. # trading = Trading(logs_to_cloud=LOGS_TO_CLOUD) # trading.make_trades(companies) # Tweet about it. twitter = Twitter(logs_to_cloud=LOGS_TO_CLOUD) twitter.tweet(companies, tweet)
[ "def", "twitter_callback", "(", "self", ",", "tweet", ")", ":", "# Initialize the Analysis, Logs, Trading, and Twitter instances inside", "# the callback to create separate httplib2 instances per thread.", "analysis", "=", "Analysis", "(", "logs_to_cloud", "=", "LOGS_TO_CLOUD", ")", "logs", "=", "Logs", "(", "name", "=", "'main-callback'", ",", "to_cloud", "=", "LOGS_TO_CLOUD", ")", "# Analyze the tweet.", "companies", "=", "analysis", ".", "find_companies", "(", "tweet", ")", "logs", ".", "info", "(", "'Using companies: %s'", "%", "companies", ")", "if", "not", "companies", ":", "return", "# Trade stocks.", "# trading = Trading(logs_to_cloud=LOGS_TO_CLOUD)", "# trading.make_trades(companies)", "# Tweet about it.", "twitter", "=", "Twitter", "(", "logs_to_cloud", "=", "LOGS_TO_CLOUD", ")", "twitter", ".", "tweet", "(", "companies", ",", "tweet", ")" ]
[ 83, 4 ]
[ 103, 39 ]
python
en
['en', 'en', 'en']
True
Main.run_session
(self)
Runs a single streaming session. Logs and cleans up after exceptions.
Runs a single streaming session. Logs and cleans up after exceptions.
def run_session(self): """Runs a single streaming session. Logs and cleans up after exceptions. """ self.logs.info('Starting new session.') try: self.twitter.start_streaming(self.twitter_callback) except: self.logs.catch() finally: self.twitter.stop_streaming() self.logs.info('Ending session.')
[ "def", "run_session", "(", "self", ")", ":", "self", ".", "logs", ".", "info", "(", "'Starting new session.'", ")", "try", ":", "self", ".", "twitter", ".", "start_streaming", "(", "self", ".", "twitter_callback", ")", "except", ":", "self", ".", "logs", ".", "catch", "(", ")", "finally", ":", "self", ".", "twitter", ".", "stop_streaming", "(", ")", "self", ".", "logs", ".", "info", "(", "'Ending session.'", ")" ]
[ 105, 4 ]
[ 117, 45 ]
python
en
['en', 'en', 'en']
True
Main.backoff
(self, tries)
Sleeps an exponential number of seconds based on the number of tries.
Sleeps an exponential number of seconds based on the number of tries.
def backoff(self, tries): """Sleeps an exponential number of seconds based on the number of tries. """ delay = BACKOFF_STEP_S * pow(2, tries) self.logs.warn('Waiting for %.1f seconds.' % delay) sleep(delay)
[ "def", "backoff", "(", "self", ",", "tries", ")", ":", "delay", "=", "BACKOFF_STEP_S", "*", "pow", "(", "2", ",", "tries", ")", "self", ".", "logs", ".", "warn", "(", "'Waiting for %.1f seconds.'", "%", "delay", ")", "sleep", "(", "delay", ")" ]
[ 119, 4 ]
[ 126, 20 ]
python
en
['en', 'en', 'en']
True
Main.run
(self)
Runs the main retry loop with exponential backoff.
Runs the main retry loop with exponential backoff.
def run(self): """Runs the main retry loop with exponential backoff.""" tries = 0 while True: # The session blocks until an error occurs. self.run_session() # Remember the first time a backoff sequence starts. now = datetime.now() if tries == 0: self.logs.debug('Starting first backoff sequence.') backoff_start = now # Reset the backoff sequence if the last error was long ago. if (now - backoff_start).total_seconds() > BACKOFF_RESET_S: self.logs.debug('Starting new backoff sequence.') tries = 0 backoff_start = now # Give up after the maximum number of tries. if tries >= MAX_TRIES: self.logs.warn('Exceeded maximum retry count.') break # Wait according to the progression of the backoff sequence. self.backoff(tries) # Increment the number of tries for the next error. tries += 1
[ "def", "run", "(", "self", ")", ":", "tries", "=", "0", "while", "True", ":", "# The session blocks until an error occurs.", "self", ".", "run_session", "(", ")", "# Remember the first time a backoff sequence starts.", "now", "=", "datetime", ".", "now", "(", ")", "if", "tries", "==", "0", ":", "self", ".", "logs", ".", "debug", "(", "'Starting first backoff sequence.'", ")", "backoff_start", "=", "now", "# Reset the backoff sequence if the last error was long ago.", "if", "(", "now", "-", "backoff_start", ")", ".", "total_seconds", "(", ")", ">", "BACKOFF_RESET_S", ":", "self", ".", "logs", ".", "debug", "(", "'Starting new backoff sequence.'", ")", "tries", "=", "0", "backoff_start", "=", "now", "# Give up after the maximum number of tries.", "if", "tries", ">=", "MAX_TRIES", ":", "self", ".", "logs", ".", "warn", "(", "'Exceeded maximum retry count.'", ")", "break", "# Wait according to the progression of the backoff sequence.", "self", ".", "backoff", "(", "tries", ")", "# Increment the number of tries for the next error.", "tries", "+=", "1" ]
[ 128, 4 ]
[ 158, 22 ]
python
en
['en', 'en', 'en']
True
quote
(arg)
r""" >>> quote('\t') '\\\t' >>> quote('foo bar') 'foo\\ bar'
r""" >>> quote('\t') '\\\t' >>> quote('foo bar') 'foo\\ bar'
def quote(arg): r""" >>> quote('\t') '\\\t' >>> quote('foo bar') 'foo\\ bar' """ # This is the logic emacs uses if arg: return _quote_pos.sub('\\\\', arg).replace('\n', "'\n'") else: return "''"
[ "def", "quote", "(", "arg", ")", ":", "# This is the logic emacs uses", "if", "arg", ":", "return", "_quote_pos", ".", "sub", "(", "'\\\\\\\\'", ",", "arg", ")", ".", "replace", "(", "'\\n'", ",", "\"'\\n'\"", ")", "else", ":", "return", "\"''\"" ]
[ 10, 0 ]
[ 22, 19 ]
python
cy
['en', 'cy', 'hi']
False
SiteBuilder.build
(self, resource_identifiers=None, build_index: bool = True)
:param resource_identifiers: a list of resource identifiers (ExpectationSuiteIdentifier, ValidationResultIdentifier). If specified, rebuild HTML(or other views the data docs site renders) only for the resources in this list. This supports incremental build of data docs sites (e.g., when a new validation result is created) and avoids full rebuild. :param build_index: a flag if False, skips building the index page :return:
def build(self, resource_identifiers=None, build_index: bool = True): """ :param resource_identifiers: a list of resource identifiers (ExpectationSuiteIdentifier, ValidationResultIdentifier). If specified, rebuild HTML(or other views the data docs site renders) only for the resources in this list. This supports incremental build of data docs sites (e.g., when a new validation result is created) and avoids full rebuild. :param build_index: a flag if False, skips building the index page :return: """ # copy static assets self.target_store.copy_static_assets() for site_section, site_section_builder in self.site_section_builders.items(): site_section_builder.build(resource_identifiers=resource_identifiers) index_page_url, index_links_dict = self.site_index_builder.build( build_index=build_index ) return ( self.get_resource_url(only_if_exists=False), index_links_dict, )
[ "def", "build", "(", "self", ",", "resource_identifiers", "=", "None", ",", "build_index", ":", "bool", "=", "True", ")", ":", "# copy static assets", "self", ".", "target_store", ".", "copy_static_assets", "(", ")", "for", "site_section", ",", "site_section_builder", "in", "self", ".", "site_section_builders", ".", "items", "(", ")", ":", "site_section_builder", ".", "build", "(", "resource_identifiers", "=", "resource_identifiers", ")", "index_page_url", ",", "index_links_dict", "=", "self", ".", "site_index_builder", ".", "build", "(", "build_index", "=", "build_index", ")", "return", "(", "self", ".", "get_resource_url", "(", "only_if_exists", "=", "False", ")", ",", "index_links_dict", ",", ")" ]
[ 271, 4 ]
[ 300, 9 ]
python
en
['en', 'error', 'th']
False
SiteBuilder.get_resource_url
(self, resource_identifier=None, only_if_exists=True)
Return the URL of the HTML document that renders a resource (e.g., an expectation suite or a validation result). :param resource_identifier: ExpectationSuiteIdentifier, ValidationResultIdentifier or any other type's identifier. The argument is optional - when not supplied, the method returns the URL of the index page. :return: URL (string)
Return the URL of the HTML document that renders a resource (e.g., an expectation suite or a validation result).
def get_resource_url(self, resource_identifier=None, only_if_exists=True): """ Return the URL of the HTML document that renders a resource (e.g., an expectation suite or a validation result). :param resource_identifier: ExpectationSuiteIdentifier, ValidationResultIdentifier or any other type's identifier. The argument is optional - when not supplied, the method returns the URL of the index page. :return: URL (string) """ return self.target_store.get_url_for_resource( resource_identifier=resource_identifier, only_if_exists=only_if_exists )
[ "def", "get_resource_url", "(", "self", ",", "resource_identifier", "=", "None", ",", "only_if_exists", "=", "True", ")", ":", "return", "self", ".", "target_store", ".", "get_url_for_resource", "(", "resource_identifier", "=", "resource_identifier", ",", "only_if_exists", "=", "only_if_exists", ")" ]
[ 302, 4 ]
[ 316, 9 ]
python
en
['en', 'error', 'th']
False
DefaultSiteIndexBuilder._get_call_to_action_buttons
(self, usage_statistics)
Build project and user specific calls to action buttons. This can become progressively smarter about project and user specific calls to action.
Build project and user specific calls to action buttons.
def _get_call_to_action_buttons(self, usage_statistics): """ Build project and user specific calls to action buttons. This can become progressively smarter about project and user specific calls to action. """ create_expectations = CallToActionButton( "How to Create Expectations", # TODO update this link to a proper tutorial "https://docs.greatexpectations.io/en/latest/guides/how_to_guides/creating_and_editing_expectations.html", ) see_glossary = CallToActionButton( "See More Kinds of Expectations", "https://docs.greatexpectations.io/en/latest/reference/glossary_of_expectations.html", ) validation_playground = CallToActionButton( "How to Validate Data", # TODO update this link to a proper tutorial "https://docs.greatexpectations.io/en/latest/guides/how_to_guides/validation.html", ) customize_data_docs = CallToActionButton( "How to Customize Data Docs", "https://docs.greatexpectations.io/en/latest/reference/core_concepts.html#data-docs", ) team_site = CallToActionButton( "How to Set Up a Team Site", "https://docs.greatexpectations.io/en/latest/guides/how_to_guides/configuring_data_docs.html", ) # TODO gallery does not yet exist # gallery = CallToActionButton( # "Great Expectations Gallery", # "https://greatexpectations.io/gallery" # ) results = [] results.append(create_expectations) # Show these no matter what results.append(validation_playground) results.append(team_site) if usage_statistics: for button in results: button.link = button.link + usage_statistics return results
[ "def", "_get_call_to_action_buttons", "(", "self", ",", "usage_statistics", ")", ":", "create_expectations", "=", "CallToActionButton", "(", "\"How to Create Expectations\"", ",", "# TODO update this link to a proper tutorial", "\"https://docs.greatexpectations.io/en/latest/guides/how_to_guides/creating_and_editing_expectations.html\"", ",", ")", "see_glossary", "=", "CallToActionButton", "(", "\"See More Kinds of Expectations\"", ",", "\"https://docs.greatexpectations.io/en/latest/reference/glossary_of_expectations.html\"", ",", ")", "validation_playground", "=", "CallToActionButton", "(", "\"How to Validate Data\"", ",", "# TODO update this link to a proper tutorial", "\"https://docs.greatexpectations.io/en/latest/guides/how_to_guides/validation.html\"", ",", ")", "customize_data_docs", "=", "CallToActionButton", "(", "\"How to Customize Data Docs\"", ",", "\"https://docs.greatexpectations.io/en/latest/reference/core_concepts.html#data-docs\"", ",", ")", "team_site", "=", "CallToActionButton", "(", "\"How to Set Up a Team Site\"", ",", "\"https://docs.greatexpectations.io/en/latest/guides/how_to_guides/configuring_data_docs.html\"", ",", ")", "# TODO gallery does not yet exist", "# gallery = CallToActionButton(", "# \"Great Expectations Gallery\",", "# \"https://greatexpectations.io/gallery\"", "# )", "results", "=", "[", "]", "results", ".", "append", "(", "create_expectations", ")", "# Show these no matter what", "results", ".", "append", "(", "validation_playground", ")", "results", ".", "append", "(", "team_site", ")", "if", "usage_statistics", ":", "for", "button", "in", "results", ":", "button", ".", "link", "=", "button", ".", "link", "+", "usage_statistics", "return", "results" ]
[ 642, 4 ]
[ 688, 22 ]
python
en
['en', 'error', 'th']
False
DefaultSiteIndexBuilder.build
(self, skip_and_clean_missing=True, build_index: bool = True)
:param skip_and_clean_missing: if True, target html store keys without corresponding source store keys will be skipped and removed from the target store :param build_index: a flag if False, skips building the index page :return: tuple(index_page_url, index_links_dict)
:param skip_and_clean_missing: if True, target html store keys without corresponding source store keys will be skipped and removed from the target store :param build_index: a flag if False, skips building the index page :return: tuple(index_page_url, index_links_dict)
def build(self, skip_and_clean_missing=True, build_index: bool = True): """ :param skip_and_clean_missing: if True, target html store keys without corresponding source store keys will be skipped and removed from the target store :param build_index: a flag if False, skips building the index page :return: tuple(index_page_url, index_links_dict) """ # Loop over sections in the HtmlStore logger.debug("DefaultSiteIndexBuilder.build") if not build_index: logger.debug("Skipping index rendering") return None, None index_links_dict = OrderedDict() index_links_dict["site_name"] = self.site_name if self.show_how_to_buttons: index_links_dict["cta_object"] = self.get_calls_to_action() if ( # TODO why is this duplicated? self.site_section_builders_config.get("expectations", "None") and self.site_section_builders_config.get("expectations", "None") not in FALSEY_YAML_STRINGS ): expectation_suite_source_keys = self.data_context.stores[ self.site_section_builders_config["expectations"].get( "source_store_name" ) ].list_keys() expectation_suite_site_keys = [ ExpectationSuiteIdentifier.from_tuple(expectation_suite_tuple) for expectation_suite_tuple in self.target_store.store_backends[ ExpectationSuiteIdentifier ].list_keys() ] if skip_and_clean_missing: cleaned_keys = [] for expectation_suite_site_key in expectation_suite_site_keys: if expectation_suite_site_key not in expectation_suite_source_keys: self.target_store.store_backends[ ExpectationSuiteIdentifier ].remove_key(expectation_suite_site_key) else: cleaned_keys.append(expectation_suite_site_key) expectation_suite_site_keys = cleaned_keys for expectation_suite_key in expectation_suite_site_keys: self.add_resource_info_to_index_links_dict( index_links_dict=index_links_dict, expectation_suite_name=expectation_suite_key.expectation_suite_name, section_name="expectations", ) validation_and_profiling_result_site_keys = [] if ( # TODO why is this duplicated? self.site_section_builders_config.get("validations", "None") and self.site_section_builders_config.get("validations", "None") not in FALSEY_YAML_STRINGS or self.site_section_builders_config.get("profiling", "None") and self.site_section_builders_config.get("profiling", "None") not in FALSEY_YAML_STRINGS ): source_store = ( "validations" # TODO why is this duplicated? if self.site_section_builders_config.get("validations", "None") and self.site_section_builders_config.get("validations", "None") not in FALSEY_YAML_STRINGS else "profiling" ) validation_and_profiling_result_source_keys = self.data_context.stores[ self.site_section_builders_config[source_store].get("source_store_name") ].list_keys() validation_and_profiling_result_site_keys = [ ValidationResultIdentifier.from_tuple(validation_result_tuple) for validation_result_tuple in self.target_store.store_backends[ ValidationResultIdentifier ].list_keys() ] if skip_and_clean_missing: cleaned_keys = [] for ( validation_result_site_key ) in validation_and_profiling_result_site_keys: if ( validation_result_site_key not in validation_and_profiling_result_source_keys ): self.target_store.store_backends[ ValidationResultIdentifier ].remove_key(validation_result_site_key) else: cleaned_keys.append(validation_result_site_key) validation_and_profiling_result_site_keys = cleaned_keys if ( # TODO why is this duplicated? self.site_section_builders_config.get("profiling", "None") and self.site_section_builders_config.get("profiling", "None") not in FALSEY_YAML_STRINGS ): profiling_run_name_filter = self.site_section_builders_config["profiling"][ "run_name_filter" ] profiling_result_site_keys = [ validation_result_key for validation_result_key in validation_and_profiling_result_site_keys if resource_key_passes_run_name_filter( validation_result_key, profiling_run_name_filter ) ] for profiling_result_key in profiling_result_site_keys: try: validation = self.data_context.get_validation_result( batch_identifier=profiling_result_key.batch_identifier, expectation_suite_name=profiling_result_key.expectation_suite_identifier.expectation_suite_name, run_id=profiling_result_key.run_id, validations_store_name=self.source_stores.get("profiling"), ) batch_kwargs = validation.meta.get("batch_kwargs", {}) batch_spec = validation.meta.get("batch_spec", {}) self.add_resource_info_to_index_links_dict( index_links_dict=index_links_dict, expectation_suite_name=profiling_result_key.expectation_suite_identifier.expectation_suite_name, section_name="profiling", batch_identifier=profiling_result_key.batch_identifier, run_id=profiling_result_key.run_id, run_time=profiling_result_key.run_id.run_time, run_name=profiling_result_key.run_id.run_name, asset_name=batch_kwargs.get("data_asset_name") or batch_spec.get("data_asset_name"), batch_kwargs=batch_kwargs, batch_spec=batch_spec, ) except Exception: error_msg = "Profiling result not found: {:s} - skipping".format( str(profiling_result_key.to_tuple()) ) logger.warning(error_msg) if ( # TODO why is this duplicated? self.site_section_builders_config.get("validations", "None") and self.site_section_builders_config.get("validations", "None") not in FALSEY_YAML_STRINGS ): validations_run_name_filter = self.site_section_builders_config[ "validations" ]["run_name_filter"] validation_result_site_keys = [ validation_result_key for validation_result_key in validation_and_profiling_result_site_keys if resource_key_passes_run_name_filter( validation_result_key, validations_run_name_filter ) ] validation_result_site_keys = sorted( validation_result_site_keys, key=lambda x: x.run_id.run_time, reverse=True, ) if self.validation_results_limit: validation_result_site_keys = validation_result_site_keys[ : self.validation_results_limit ] for validation_result_key in validation_result_site_keys: try: validation = self.data_context.get_validation_result( batch_identifier=validation_result_key.batch_identifier, expectation_suite_name=validation_result_key.expectation_suite_identifier.expectation_suite_name, run_id=validation_result_key.run_id, validations_store_name=self.source_stores.get("validations"), ) validation_success = validation.success batch_kwargs = validation.meta.get("batch_kwargs", {}) batch_spec = validation.meta.get("batch_spec", {}) self.add_resource_info_to_index_links_dict( index_links_dict=index_links_dict, expectation_suite_name=validation_result_key.expectation_suite_identifier.expectation_suite_name, section_name="validations", batch_identifier=validation_result_key.batch_identifier, run_id=validation_result_key.run_id, validation_success=validation_success, run_time=validation_result_key.run_id.run_time, run_name=validation_result_key.run_id.run_name, asset_name=batch_kwargs.get("data_asset_name") or batch_spec.get("data_asset_name"), batch_kwargs=batch_kwargs, batch_spec=batch_spec, ) except Exception: error_msg = "Validation result not found: {:s} - skipping".format( str(validation_result_key.to_tuple()) ) logger.warning(error_msg) try: rendered_content = self.renderer_class.render(index_links_dict) viewable_content = self.view_class.render( rendered_content, data_context_id=self.data_context_id, show_how_to_buttons=self.show_how_to_buttons, ) except Exception as e: exception_message = f"""\ An unexpected Exception occurred during data docs rendering. Because of this error, certain parts of data docs will \ not be rendered properly and/or may not appear altogether. Please use the trace, included in this message, to \ diagnose and repair the underlying issue. Detailed information follows: """ exception_traceback = traceback.format_exc() exception_message += ( f'{type(e).__name__}: "{str(e)}". Traceback: "{exception_traceback}".' ) logger.error(exception_message) return (self.target_store.write_index_page(viewable_content), index_links_dict)
[ "def", "build", "(", "self", ",", "skip_and_clean_missing", "=", "True", ",", "build_index", ":", "bool", "=", "True", ")", ":", "# Loop over sections in the HtmlStore", "logger", ".", "debug", "(", "\"DefaultSiteIndexBuilder.build\"", ")", "if", "not", "build_index", ":", "logger", ".", "debug", "(", "\"Skipping index rendering\"", ")", "return", "None", ",", "None", "index_links_dict", "=", "OrderedDict", "(", ")", "index_links_dict", "[", "\"site_name\"", "]", "=", "self", ".", "site_name", "if", "self", ".", "show_how_to_buttons", ":", "index_links_dict", "[", "\"cta_object\"", "]", "=", "self", ".", "get_calls_to_action", "(", ")", "if", "(", "# TODO why is this duplicated?", "self", ".", "site_section_builders_config", ".", "get", "(", "\"expectations\"", ",", "\"None\"", ")", "and", "self", ".", "site_section_builders_config", ".", "get", "(", "\"expectations\"", ",", "\"None\"", ")", "not", "in", "FALSEY_YAML_STRINGS", ")", ":", "expectation_suite_source_keys", "=", "self", ".", "data_context", ".", "stores", "[", "self", ".", "site_section_builders_config", "[", "\"expectations\"", "]", ".", "get", "(", "\"source_store_name\"", ")", "]", ".", "list_keys", "(", ")", "expectation_suite_site_keys", "=", "[", "ExpectationSuiteIdentifier", ".", "from_tuple", "(", "expectation_suite_tuple", ")", "for", "expectation_suite_tuple", "in", "self", ".", "target_store", ".", "store_backends", "[", "ExpectationSuiteIdentifier", "]", ".", "list_keys", "(", ")", "]", "if", "skip_and_clean_missing", ":", "cleaned_keys", "=", "[", "]", "for", "expectation_suite_site_key", "in", "expectation_suite_site_keys", ":", "if", "expectation_suite_site_key", "not", "in", "expectation_suite_source_keys", ":", "self", ".", "target_store", ".", "store_backends", "[", "ExpectationSuiteIdentifier", "]", ".", "remove_key", "(", "expectation_suite_site_key", ")", "else", ":", "cleaned_keys", ".", "append", "(", "expectation_suite_site_key", ")", "expectation_suite_site_keys", "=", "cleaned_keys", "for", "expectation_suite_key", "in", "expectation_suite_site_keys", ":", "self", ".", "add_resource_info_to_index_links_dict", "(", "index_links_dict", "=", "index_links_dict", ",", "expectation_suite_name", "=", "expectation_suite_key", ".", "expectation_suite_name", ",", "section_name", "=", "\"expectations\"", ",", ")", "validation_and_profiling_result_site_keys", "=", "[", "]", "if", "(", "# TODO why is this duplicated?", "self", ".", "site_section_builders_config", ".", "get", "(", "\"validations\"", ",", "\"None\"", ")", "and", "self", ".", "site_section_builders_config", ".", "get", "(", "\"validations\"", ",", "\"None\"", ")", "not", "in", "FALSEY_YAML_STRINGS", "or", "self", ".", "site_section_builders_config", ".", "get", "(", "\"profiling\"", ",", "\"None\"", ")", "and", "self", ".", "site_section_builders_config", ".", "get", "(", "\"profiling\"", ",", "\"None\"", ")", "not", "in", "FALSEY_YAML_STRINGS", ")", ":", "source_store", "=", "(", "\"validations\"", "# TODO why is this duplicated?", "if", "self", ".", "site_section_builders_config", ".", "get", "(", "\"validations\"", ",", "\"None\"", ")", "and", "self", ".", "site_section_builders_config", ".", "get", "(", "\"validations\"", ",", "\"None\"", ")", "not", "in", "FALSEY_YAML_STRINGS", "else", "\"profiling\"", ")", "validation_and_profiling_result_source_keys", "=", "self", ".", "data_context", ".", "stores", "[", "self", ".", "site_section_builders_config", "[", "source_store", "]", ".", "get", "(", "\"source_store_name\"", ")", "]", ".", "list_keys", "(", ")", "validation_and_profiling_result_site_keys", "=", "[", "ValidationResultIdentifier", ".", "from_tuple", "(", "validation_result_tuple", ")", "for", "validation_result_tuple", "in", "self", ".", "target_store", ".", "store_backends", "[", "ValidationResultIdentifier", "]", ".", "list_keys", "(", ")", "]", "if", "skip_and_clean_missing", ":", "cleaned_keys", "=", "[", "]", "for", "(", "validation_result_site_key", ")", "in", "validation_and_profiling_result_site_keys", ":", "if", "(", "validation_result_site_key", "not", "in", "validation_and_profiling_result_source_keys", ")", ":", "self", ".", "target_store", ".", "store_backends", "[", "ValidationResultIdentifier", "]", ".", "remove_key", "(", "validation_result_site_key", ")", "else", ":", "cleaned_keys", ".", "append", "(", "validation_result_site_key", ")", "validation_and_profiling_result_site_keys", "=", "cleaned_keys", "if", "(", "# TODO why is this duplicated?", "self", ".", "site_section_builders_config", ".", "get", "(", "\"profiling\"", ",", "\"None\"", ")", "and", "self", ".", "site_section_builders_config", ".", "get", "(", "\"profiling\"", ",", "\"None\"", ")", "not", "in", "FALSEY_YAML_STRINGS", ")", ":", "profiling_run_name_filter", "=", "self", ".", "site_section_builders_config", "[", "\"profiling\"", "]", "[", "\"run_name_filter\"", "]", "profiling_result_site_keys", "=", "[", "validation_result_key", "for", "validation_result_key", "in", "validation_and_profiling_result_site_keys", "if", "resource_key_passes_run_name_filter", "(", "validation_result_key", ",", "profiling_run_name_filter", ")", "]", "for", "profiling_result_key", "in", "profiling_result_site_keys", ":", "try", ":", "validation", "=", "self", ".", "data_context", ".", "get_validation_result", "(", "batch_identifier", "=", "profiling_result_key", ".", "batch_identifier", ",", "expectation_suite_name", "=", "profiling_result_key", ".", "expectation_suite_identifier", ".", "expectation_suite_name", ",", "run_id", "=", "profiling_result_key", ".", "run_id", ",", "validations_store_name", "=", "self", ".", "source_stores", ".", "get", "(", "\"profiling\"", ")", ",", ")", "batch_kwargs", "=", "validation", ".", "meta", ".", "get", "(", "\"batch_kwargs\"", ",", "{", "}", ")", "batch_spec", "=", "validation", ".", "meta", ".", "get", "(", "\"batch_spec\"", ",", "{", "}", ")", "self", ".", "add_resource_info_to_index_links_dict", "(", "index_links_dict", "=", "index_links_dict", ",", "expectation_suite_name", "=", "profiling_result_key", ".", "expectation_suite_identifier", ".", "expectation_suite_name", ",", "section_name", "=", "\"profiling\"", ",", "batch_identifier", "=", "profiling_result_key", ".", "batch_identifier", ",", "run_id", "=", "profiling_result_key", ".", "run_id", ",", "run_time", "=", "profiling_result_key", ".", "run_id", ".", "run_time", ",", "run_name", "=", "profiling_result_key", ".", "run_id", ".", "run_name", ",", "asset_name", "=", "batch_kwargs", ".", "get", "(", "\"data_asset_name\"", ")", "or", "batch_spec", ".", "get", "(", "\"data_asset_name\"", ")", ",", "batch_kwargs", "=", "batch_kwargs", ",", "batch_spec", "=", "batch_spec", ",", ")", "except", "Exception", ":", "error_msg", "=", "\"Profiling result not found: {:s} - skipping\"", ".", "format", "(", "str", "(", "profiling_result_key", ".", "to_tuple", "(", ")", ")", ")", "logger", ".", "warning", "(", "error_msg", ")", "if", "(", "# TODO why is this duplicated?", "self", ".", "site_section_builders_config", ".", "get", "(", "\"validations\"", ",", "\"None\"", ")", "and", "self", ".", "site_section_builders_config", ".", "get", "(", "\"validations\"", ",", "\"None\"", ")", "not", "in", "FALSEY_YAML_STRINGS", ")", ":", "validations_run_name_filter", "=", "self", ".", "site_section_builders_config", "[", "\"validations\"", "]", "[", "\"run_name_filter\"", "]", "validation_result_site_keys", "=", "[", "validation_result_key", "for", "validation_result_key", "in", "validation_and_profiling_result_site_keys", "if", "resource_key_passes_run_name_filter", "(", "validation_result_key", ",", "validations_run_name_filter", ")", "]", "validation_result_site_keys", "=", "sorted", "(", "validation_result_site_keys", ",", "key", "=", "lambda", "x", ":", "x", ".", "run_id", ".", "run_time", ",", "reverse", "=", "True", ",", ")", "if", "self", ".", "validation_results_limit", ":", "validation_result_site_keys", "=", "validation_result_site_keys", "[", ":", "self", ".", "validation_results_limit", "]", "for", "validation_result_key", "in", "validation_result_site_keys", ":", "try", ":", "validation", "=", "self", ".", "data_context", ".", "get_validation_result", "(", "batch_identifier", "=", "validation_result_key", ".", "batch_identifier", ",", "expectation_suite_name", "=", "validation_result_key", ".", "expectation_suite_identifier", ".", "expectation_suite_name", ",", "run_id", "=", "validation_result_key", ".", "run_id", ",", "validations_store_name", "=", "self", ".", "source_stores", ".", "get", "(", "\"validations\"", ")", ",", ")", "validation_success", "=", "validation", ".", "success", "batch_kwargs", "=", "validation", ".", "meta", ".", "get", "(", "\"batch_kwargs\"", ",", "{", "}", ")", "batch_spec", "=", "validation", ".", "meta", ".", "get", "(", "\"batch_spec\"", ",", "{", "}", ")", "self", ".", "add_resource_info_to_index_links_dict", "(", "index_links_dict", "=", "index_links_dict", ",", "expectation_suite_name", "=", "validation_result_key", ".", "expectation_suite_identifier", ".", "expectation_suite_name", ",", "section_name", "=", "\"validations\"", ",", "batch_identifier", "=", "validation_result_key", ".", "batch_identifier", ",", "run_id", "=", "validation_result_key", ".", "run_id", ",", "validation_success", "=", "validation_success", ",", "run_time", "=", "validation_result_key", ".", "run_id", ".", "run_time", ",", "run_name", "=", "validation_result_key", ".", "run_id", ".", "run_name", ",", "asset_name", "=", "batch_kwargs", ".", "get", "(", "\"data_asset_name\"", ")", "or", "batch_spec", ".", "get", "(", "\"data_asset_name\"", ")", ",", "batch_kwargs", "=", "batch_kwargs", ",", "batch_spec", "=", "batch_spec", ",", ")", "except", "Exception", ":", "error_msg", "=", "\"Validation result not found: {:s} - skipping\"", ".", "format", "(", "str", "(", "validation_result_key", ".", "to_tuple", "(", ")", ")", ")", "logger", ".", "warning", "(", "error_msg", ")", "try", ":", "rendered_content", "=", "self", ".", "renderer_class", ".", "render", "(", "index_links_dict", ")", "viewable_content", "=", "self", ".", "view_class", ".", "render", "(", "rendered_content", ",", "data_context_id", "=", "self", ".", "data_context_id", ",", "show_how_to_buttons", "=", "self", ".", "show_how_to_buttons", ",", ")", "except", "Exception", "as", "e", ":", "exception_message", "=", "f\"\"\"\\\nAn unexpected Exception occurred during data docs rendering. Because of this error, certain parts of data docs will \\\nnot be rendered properly and/or may not appear altogether. Please use the trace, included in this message, to \\\ndiagnose and repair the underlying issue. Detailed information follows:\n \"\"\"", "exception_traceback", "=", "traceback", ".", "format_exc", "(", ")", "exception_message", "+=", "(", "f'{type(e).__name__}: \"{str(e)}\". Traceback: \"{exception_traceback}\".'", ")", "logger", ".", "error", "(", "exception_message", ")", "return", "(", "self", ".", "target_store", ".", "write_index_page", "(", "viewable_content", ")", ",", "index_links_dict", ")" ]
[ 691, 4 ]
[ 913, 87 ]
python
en
['en', 'error', 'th']
False
gather_3d_metrics
(expected, actual)
:param expected: Predicted pose :param actual: Ground Truth :return: evaluation results
def gather_3d_metrics(expected, actual): """ :param expected: Predicted pose :param actual: Ground Truth :return: evaluation results """ unaligned_pck = pck(actual, expected) unaligned_auc = auc(actual, expected) expect_np = expected.cpu().numpy().reshape(-1, expected.shape[-2], expected.shape[-1]) actual_np = actual.cpu().numpy().reshape(-1, expected.shape[-2], expected.shape[-1]) aligned_mpjpe, aligned = p_mpjpe(expect_np, actual_np) #plot17j(np.concatenate((actual_np[100:104],expect_np[100:104],aligned[0,100:104].cpu().numpy()),axis=0),'aa','aa') aligned_pck = pck(aligned, actual) aligned_auc = auc(aligned, actual) return dict( pck=unaligned_pck, auc=unaligned_auc, aligned_mpjpe=aligned_mpjpe, aligned_pck=aligned_pck, aligned_auc=aligned_auc, )
[ "def", "gather_3d_metrics", "(", "expected", ",", "actual", ")", ":", "unaligned_pck", "=", "pck", "(", "actual", ",", "expected", ")", "unaligned_auc", "=", "auc", "(", "actual", ",", "expected", ")", "expect_np", "=", "expected", ".", "cpu", "(", ")", ".", "numpy", "(", ")", ".", "reshape", "(", "-", "1", ",", "expected", ".", "shape", "[", "-", "2", "]", ",", "expected", ".", "shape", "[", "-", "1", "]", ")", "actual_np", "=", "actual", ".", "cpu", "(", ")", ".", "numpy", "(", ")", ".", "reshape", "(", "-", "1", ",", "expected", ".", "shape", "[", "-", "2", "]", ",", "expected", ".", "shape", "[", "-", "1", "]", ")", "aligned_mpjpe", ",", "aligned", "=", "p_mpjpe", "(", "expect_np", ",", "actual_np", ")", "#plot17j(np.concatenate((actual_np[100:104],expect_np[100:104],aligned[0,100:104].cpu().numpy()),axis=0),'aa','aa')", "aligned_pck", "=", "pck", "(", "aligned", ",", "actual", ")", "aligned_auc", "=", "auc", "(", "aligned", ",", "actual", ")", "return", "dict", "(", "pck", "=", "unaligned_pck", ",", "auc", "=", "unaligned_auc", ",", "aligned_mpjpe", "=", "aligned_mpjpe", ",", "aligned_pck", "=", "aligned_pck", ",", "aligned_auc", "=", "aligned_auc", ",", ")" ]
[ 6, 0 ]
[ 27, 5 ]
python
en
['en', 'error', 'th']
False
is_str
(string)
Python 2 and 3 compatible string checker. Args: string (str | basestring): the string to check Returns: bool: True or False
Python 2 and 3 compatible string checker.
def is_str(string): """ Python 2 and 3 compatible string checker. Args: string (str | basestring): the string to check Returns: bool: True or False """ if sys.version_info >= (3, 0): return isinstance(string, str) else: return isinstance(string, basestring)
[ "def", "is_str", "(", "string", ")", ":", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "0", ")", ":", "return", "isinstance", "(", "string", ",", "str", ")", "else", ":", "return", "isinstance", "(", "string", ",", "basestring", ")" ]
[ 16, 0 ]
[ 30, 45 ]
python
en
['en', 'error', 'th']
False
find_xml_generator
(name=None)
Try to find a c++ parser. Returns path and name. :param name: name of the c++ parser: castxml or gccxml :type name: str If no name is given the function first looks for castxml, then for gccxml. If no c++ parser is found the function raises an exception.
Try to find a c++ parser. Returns path and name.
def find_xml_generator(name=None): """ Try to find a c++ parser. Returns path and name. :param name: name of the c++ parser: castxml or gccxml :type name: str If no name is given the function first looks for castxml, then for gccxml. If no c++ parser is found the function raises an exception. """ if platform.system() == "Windows": command = "where" else: command = "which" if name is None: name = "castxml" p = subprocess.Popen([command, name], stdout=subprocess.PIPE, stderr=subprocess.PIPE) path = p.stdout.read().decode("utf-8") p.wait() p.stdout.close() p.stderr.close() if path == "": name = "gccxml" p = subprocess.Popen([command, name], stdout=subprocess.PIPE, stderr=subprocess.PIPE) path = p.stdout.read().decode("utf-8") p.wait() p.stdout.close() p.stderr.close() else: p = subprocess.Popen([command, name], stdout=subprocess.PIPE, stderr=subprocess.PIPE) path = p.stdout.read().decode("utf-8") p.wait() p.stdout.close() p.stderr.close() if path == "": raise(Exception( "No c++ parser found. Please install castxml or gccxml.")) else: return path.rstrip(), name
[ "def", "find_xml_generator", "(", "name", "=", "None", ")", ":", "if", "platform", ".", "system", "(", ")", "==", "\"Windows\"", ":", "command", "=", "\"where\"", "else", ":", "command", "=", "\"which\"", "if", "name", "is", "None", ":", "name", "=", "\"castxml\"", "p", "=", "subprocess", ".", "Popen", "(", "[", "command", ",", "name", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "path", "=", "p", ".", "stdout", ".", "read", "(", ")", ".", "decode", "(", "\"utf-8\"", ")", "p", ".", "wait", "(", ")", "p", ".", "stdout", ".", "close", "(", ")", "p", ".", "stderr", ".", "close", "(", ")", "if", "path", "==", "\"\"", ":", "name", "=", "\"gccxml\"", "p", "=", "subprocess", ".", "Popen", "(", "[", "command", ",", "name", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "path", "=", "p", ".", "stdout", ".", "read", "(", ")", ".", "decode", "(", "\"utf-8\"", ")", "p", ".", "wait", "(", ")", "p", ".", "stdout", ".", "close", "(", ")", "p", ".", "stderr", ".", "close", "(", ")", "else", ":", "p", "=", "subprocess", ".", "Popen", "(", "[", "command", ",", "name", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "path", "=", "p", ".", "stdout", ".", "read", "(", ")", ".", "decode", "(", "\"utf-8\"", ")", "p", ".", "wait", "(", ")", "p", ".", "stdout", ".", "close", "(", ")", "p", ".", "stderr", ".", "close", "(", ")", "if", "path", "==", "\"\"", ":", "raise", "(", "Exception", "(", "\"No c++ parser found. Please install castxml or gccxml.\"", ")", ")", "else", ":", "return", "path", ".", "rstrip", "(", ")", ",", "name" ]
[ 33, 0 ]
[ 77, 34 ]
python
en
['en', 'error', 'th']
False
_create_logger_
(name)
Implementation detail, creates a logger.
Implementation detail, creates a logger.
def _create_logger_(name): """Implementation detail, creates a logger.""" logger = logging.getLogger(name) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter('%(levelname)s %(message)s')) logger.addHandler(handler) logger.setLevel(logging.INFO) return logger
[ "def", "_create_logger_", "(", "name", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "name", ")", "handler", "=", "logging", ".", "StreamHandler", "(", ")", "handler", ".", "setFormatter", "(", "logging", ".", "Formatter", "(", "'%(levelname)s %(message)s'", ")", ")", "logger", ".", "addHandler", "(", "handler", ")", "logger", ".", "setLevel", "(", "logging", ".", "INFO", ")", "return", "logger" ]
[ 80, 0 ]
[ 87, 17 ]
python
en
['es', 'en', 'en']
True
remove_file_no_raise
(file_name, config)
Removes file from disk if exception is raised.
Removes file from disk if exception is raised.
def remove_file_no_raise(file_name, config): """Removes file from disk if exception is raised.""" # The removal can be disabled by the config for debugging purposes. if config.keep_xml: return True try: if os.path.exists(file_name): os.remove(file_name) except IOError as error: loggers.root.error( "Error occurred while removing temporary created file('%s'): %s", file_name, str(error))
[ "def", "remove_file_no_raise", "(", "file_name", ",", "config", ")", ":", "# The removal can be disabled by the config for debugging purposes.", "if", "config", ".", "keep_xml", ":", "return", "True", "try", ":", "if", "os", ".", "path", ".", "exists", "(", "file_name", ")", ":", "os", ".", "remove", "(", "file_name", ")", "except", "IOError", "as", "error", ":", "loggers", ".", "root", ".", "error", "(", "\"Error occurred while removing temporary created file('%s'): %s\"", ",", "file_name", ",", "str", "(", "error", ")", ")" ]
[ 151, 0 ]
[ 163, 34 ]
python
en
['en', 'en', 'en']
True
create_temp_file_name
(suffix, prefix=None, dir=None, directory=None)
Small convenience function that creates temporary files. This function is a wrapper around the Python built-in function tempfile.mkstemp.
Small convenience function that creates temporary files.
def create_temp_file_name(suffix, prefix=None, dir=None, directory=None): """ Small convenience function that creates temporary files. This function is a wrapper around the Python built-in function tempfile.mkstemp. """ if dir is not None: warnings.warn( "The dir argument is deprecated.\n" + "Please use the directory argument instead.", DeprecationWarning) # Deprecated since 1.9.0, will be removed in 2.0.0 directory = dir if not prefix: prefix = tempfile.gettempprefix() fd, name = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=directory) file_obj = os.fdopen(fd) file_obj.close() return name
[ "def", "create_temp_file_name", "(", "suffix", ",", "prefix", "=", "None", ",", "dir", "=", "None", ",", "directory", "=", "None", ")", ":", "if", "dir", "is", "not", "None", ":", "warnings", ".", "warn", "(", "\"The dir argument is deprecated.\\n\"", "+", "\"Please use the directory argument instead.\"", ",", "DeprecationWarning", ")", "# Deprecated since 1.9.0, will be removed in 2.0.0", "directory", "=", "dir", "if", "not", "prefix", ":", "prefix", "=", "tempfile", ".", "gettempprefix", "(", ")", "fd", ",", "name", "=", "tempfile", ".", "mkstemp", "(", "suffix", "=", "suffix", ",", "prefix", "=", "prefix", ",", "dir", "=", "directory", ")", "file_obj", "=", "os", ".", "fdopen", "(", "fd", ")", "file_obj", ".", "close", "(", ")", "return", "name" ]
[ 167, 0 ]
[ 187, 15 ]
python
en
['en', 'error', 'th']
False
normalize_path
(some_path)
Return os.path.normpath(os.path.normcase(some_path)).
Return os.path.normpath(os.path.normcase(some_path)).
def normalize_path(some_path): """Return os.path.normpath(os.path.normcase(some_path)).""" return os.path.normpath(os.path.normcase(some_path))
[ "def", "normalize_path", "(", "some_path", ")", ":", "return", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "normcase", "(", "some_path", ")", ")" ]
[ 190, 0 ]
[ 192, 56 ]
python
en
['en', 'en', 'en']
False
contains_parent_dir
(fpath, dirs)
Returns true if paths in dirs start with fpath. Precondition: dirs and fpath should be normalized before calling this function.
Returns true if paths in dirs start with fpath.
def contains_parent_dir(fpath, dirs): """ Returns true if paths in dirs start with fpath. Precondition: dirs and fpath should be normalized before calling this function. """ # Note: this function is used nowhere in pygccxml but is used # at least by pypluplus; so it should stay here. return bool([x for x in dirs if _f(fpath, x)])
[ "def", "contains_parent_dir", "(", "fpath", ",", "dirs", ")", ":", "# Note: this function is used nowhere in pygccxml but is used", "# at least by pypluplus; so it should stay here.", "return", "bool", "(", "[", "x", "for", "x", "in", "dirs", "if", "_f", "(", "fpath", ",", "x", ")", "]", ")" ]
[ 195, 0 ]
[ 206, 50 ]
python
en
['en', 'error', 'th']
False
_f
(fpath, dir_)
Helper function for contains_parent_dir function.
Helper function for contains_parent_dir function.
def _f(fpath, dir_): """Helper function for contains_parent_dir function.""" return fpath.startswith(dir_)
[ "def", "_f", "(", "fpath", ",", "dir_", ")", ":", "return", "fpath", ".", "startswith", "(", "dir_", ")" ]
[ 209, 0 ]
[ 211, 33 ]
python
en
['en', 'fr', 'en']
True
get_architecture
()
Returns computer architecture: 32 or 64. The guess is based on maxint.
Returns computer architecture: 32 or 64.
def get_architecture(): """ Returns computer architecture: 32 or 64. The guess is based on maxint. """ if sys.maxsize == 2147483647: return 32 elif sys.maxsize == 9223372036854775807: return 64 else: raise RuntimeError("Unknown architecture")
[ "def", "get_architecture", "(", ")", ":", "if", "sys", ".", "maxsize", "==", "2147483647", ":", "return", "32", "elif", "sys", ".", "maxsize", "==", "9223372036854775807", ":", "return", "64", "else", ":", "raise", "RuntimeError", "(", "\"Unknown architecture\"", ")" ]
[ 214, 0 ]
[ 226, 50 ]
python
en
['en', 'error', 'th']
False
get_tr1
(name)
In libstd++ the tr1 namespace needs special care. Return either an empty string or tr1::, useful for appending to search patterns. Args: name (str): the name of the declaration Returns: str: an empty string or "tr1::"
In libstd++ the tr1 namespace needs special care.
def get_tr1(name): """In libstd++ the tr1 namespace needs special care. Return either an empty string or tr1::, useful for appending to search patterns. Args: name (str): the name of the declaration Returns: str: an empty string or "tr1::" """ tr1 = "" if "tr1" in name: tr1 = "tr1::" return tr1
[ "def", "get_tr1", "(", "name", ")", ":", "tr1", "=", "\"\"", "if", "\"tr1\"", "in", "name", ":", "tr1", "=", "\"tr1::\"", "return", "tr1" ]
[ 260, 0 ]
[ 275, 14 ]
python
en
['en', 'en', 'en']
True
loggers.set_level
(level)
Set the same logging level for all the loggers at once.
Set the same logging level for all the loggers at once.
def set_level(level): """Set the same logging level for all the loggers at once.""" for logger in loggers.all_loggers: logger.setLevel(level)
[ "def", "set_level", "(", "level", ")", ":", "for", "logger", "in", "loggers", ".", "all_loggers", ":", "logger", ".", "setLevel", "(", "level", ")" ]
[ 145, 4 ]
[ 148, 34 ]
python
en
['en', 'en', 'en']
True
cxx_standard.__init__
(self, cflags)
Class constructor that parses the XML generator's command line Args: cflags (str): cflags command line arguments passed to the XML generator
Class constructor that parses the XML generator's command line
def __init__(self, cflags): """Class constructor that parses the XML generator's command line Args: cflags (str): cflags command line arguments passed to the XML generator """ super(cxx_standard, self).__init__() self._stdcxx = None self._is_implicit = False for key in cxx_standard.__STD_CXX: if key in cflags: self._stdcxx = key self._cplusplus = cxx_standard.__STD_CXX[key] if not self._stdcxx: if '-std=' in cflags: raise RuntimeError('Unknown -std=c++xx flag used') # Assume c++03 by default self._stdcxx = '-std=c++03' self._cplusplus = cxx_standard.__STD_CXX['-std=c++03'] self._is_implicit = True
[ "def", "__init__", "(", "self", ",", "cflags", ")", ":", "super", "(", "cxx_standard", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "_stdcxx", "=", "None", "self", ".", "_is_implicit", "=", "False", "for", "key", "in", "cxx_standard", ".", "__STD_CXX", ":", "if", "key", "in", "cflags", ":", "self", ".", "_stdcxx", "=", "key", "self", ".", "_cplusplus", "=", "cxx_standard", ".", "__STD_CXX", "[", "key", "]", "if", "not", "self", ".", "_stdcxx", ":", "if", "'-std='", "in", "cflags", ":", "raise", "RuntimeError", "(", "'Unknown -std=c++xx flag used'", ")", "# Assume c++03 by default", "self", ".", "_stdcxx", "=", "'-std=c++03'", "self", ".", "_cplusplus", "=", "cxx_standard", ".", "__STD_CXX", "[", "'-std=c++03'", "]", "self", ".", "_is_implicit", "=", "True" ]
[ 303, 4 ]
[ 326, 36 ]
python
en
['en', 'en', 'en']
True
cxx_standard.stdcxx
(self)
Returns the -std=c++xx option passed to the constructor
Returns the -std=c++xx option passed to the constructor
def stdcxx(self): """Returns the -std=c++xx option passed to the constructor""" return self._stdcxx
[ "def", "stdcxx", "(", "self", ")", ":", "return", "self", ".", "_stdcxx" ]
[ 329, 4 ]
[ 331, 27 ]
python
en
['en', 'en', 'en']
True
cxx_standard.is_implicit
(self)
Indicates whether a -std=c++xx was specified
Indicates whether a -std=c++xx was specified
def is_implicit(self): """Indicates whether a -std=c++xx was specified""" return self._is_implicit
[ "def", "is_implicit", "(", "self", ")", ":", "return", "self", ".", "_is_implicit" ]
[ 334, 4 ]
[ 336, 32 ]
python
en
['en', 'en', 'en']
True
cxx_standard.is_cxx03
(self)
Returns true if -std=c++03 is being used
Returns true if -std=c++03 is being used
def is_cxx03(self): """Returns true if -std=c++03 is being used""" return self._cplusplus == cxx_standard.__STD_CXX['-std=c++03']
[ "def", "is_cxx03", "(", "self", ")", ":", "return", "self", ".", "_cplusplus", "==", "cxx_standard", ".", "__STD_CXX", "[", "'-std=c++03'", "]" ]
[ 339, 4 ]
[ 341, 70 ]
python
en
['en', 'en', 'en']
True
cxx_standard.is_cxx11
(self)
Returns true if -std=c++11 is being used
Returns true if -std=c++11 is being used
def is_cxx11(self): """Returns true if -std=c++11 is being used""" return self._cplusplus == cxx_standard.__STD_CXX['-std=c++11']
[ "def", "is_cxx11", "(", "self", ")", ":", "return", "self", ".", "_cplusplus", "==", "cxx_standard", ".", "__STD_CXX", "[", "'-std=c++11'", "]" ]
[ 344, 4 ]
[ 346, 70 ]
python
en
['en', 'en', 'en']
True
cxx_standard.is_cxx11_or_greater
(self)
Returns true if -std=c++11 or a newer standard is being used
Returns true if -std=c++11 or a newer standard is being used
def is_cxx11_or_greater(self): """Returns true if -std=c++11 or a newer standard is being used""" return self._cplusplus >= cxx_standard.__STD_CXX['-std=c++11']
[ "def", "is_cxx11_or_greater", "(", "self", ")", ":", "return", "self", ".", "_cplusplus", ">=", "cxx_standard", ".", "__STD_CXX", "[", "'-std=c++11'", "]" ]
[ 349, 4 ]
[ 351, 70 ]
python
en
['en', 'en', 'en']
True
cxx_standard.is_cxx14
(self)
Returns true if -std=c++14 is being used
Returns true if -std=c++14 is being used
def is_cxx14(self): """Returns true if -std=c++14 is being used""" return self._cplusplus == cxx_standard.__STD_CXX['-std=c++14']
[ "def", "is_cxx14", "(", "self", ")", ":", "return", "self", ".", "_cplusplus", "==", "cxx_standard", ".", "__STD_CXX", "[", "'-std=c++14'", "]" ]
[ 354, 4 ]
[ 356, 70 ]
python
en
['en', 'en', 'en']
True
cxx_standard.is_cxx14_or_greater
(self)
Returns true if -std=c++14 or a newer standard is being used
Returns true if -std=c++14 or a newer standard is being used
def is_cxx14_or_greater(self): """Returns true if -std=c++14 or a newer standard is being used""" return self._cplusplus >= cxx_standard.__STD_CXX['-std=c++14']
[ "def", "is_cxx14_or_greater", "(", "self", ")", ":", "return", "self", ".", "_cplusplus", ">=", "cxx_standard", ".", "__STD_CXX", "[", "'-std=c++14'", "]" ]
[ 359, 4 ]
[ 361, 70 ]
python
en
['en', 'en', 'en']
True
cxx_standard.is_cxx1z
(self)
Returns true if -std=c++1z is being used
Returns true if -std=c++1z is being used
def is_cxx1z(self): """Returns true if -std=c++1z is being used""" return self._cplusplus == cxx_standard.__STD_CXX['-std=c++1z']
[ "def", "is_cxx1z", "(", "self", ")", ":", "return", "self", ".", "_cplusplus", "==", "cxx_standard", ".", "__STD_CXX", "[", "'-std=c++1z'", "]" ]
[ 364, 4 ]
[ 366, 70 ]
python
en
['de', 'en', 'en']
True
UserProfileManager.create_user
(self, email, name, password=None)
Create a new user profile
Create a new user profile
def create_user(self, email, name, password=None): """Create a new user profile""" if not email: raise ValueError("User must have an email address!") email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) user.save(using=self._db) return user
[ "def", "create_user", "(", "self", ",", "email", ",", "name", ",", "password", "=", "None", ")", ":", "if", "not", "email", ":", "raise", "ValueError", "(", "\"User must have an email address!\"", ")", "email", "=", "self", ".", "normalize_email", "(", "email", ")", "user", "=", "self", ".", "model", "(", "email", "=", "email", ",", "name", "=", "name", ")", "user", ".", "set_password", "(", "password", ")", "user", ".", "save", "(", "using", "=", "self", ".", "_db", ")", "return", "user" ]
[ 11, 4 ]
[ 23, 19 ]
python
en
['en', 'it', 'en']
True
UserProfileManager.create_superuser
(self, email, name, password)
Create and save superuser with given details
Create and save superuser with given details
def create_superuser(self, email, name, password): """Create and save superuser with given details""" user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user
[ "def", "create_superuser", "(", "self", ",", "email", ",", "name", ",", "password", ")", ":", "user", "=", "self", ".", "create_user", "(", "email", ",", "name", ",", "password", ")", "user", ".", "is_superuser", "=", "True", "user", ".", "is_staff", "=", "True", "user", ".", "save", "(", "using", "=", "self", ".", "_db", ")", "return", "user" ]
[ 25, 4 ]
[ 35, 19 ]
python
en
['en', 'en', 'en']
True
UserProfile.get_full_name
(self)
Retrieve full name of the user
Retrieve full name of the user
def get_full_name(self): """Retrieve full name of the user""" return self.name
[ "def", "get_full_name", "(", "self", ")", ":", "return", "self", ".", "name" ]
[ 50, 4 ]
[ 53, 24 ]
python
en
['en', 'no', 'en']
True
UserProfile.get_short_name
(self)
Retrieve short name of the user
Retrieve short name of the user
def get_short_name(self): """Retrieve short name of the user""" return self.name
[ "def", "get_short_name", "(", "self", ")", ":", "return", "self", ".", "name" ]
[ 55, 4 ]
[ 58, 24 ]
python
en
['en', 'pt', 'en']
True
UserProfile.__str__
(self)
Return string representation of the user's email.
Return string representation of the user's email.
def __str__(self): """Return string representation of the user's email.""" return self.email
[ "def", "__str__", "(", "self", ")", ":", "return", "self", ".", "email" ]
[ 60, 4 ]
[ 62, 25 ]
python
en
['en', 'en', 'en']
True
ProfileFeedItem.__str__
(self)
Return the model as a string.
Return the model as a string.
def __str__(self): """Return the model as a string.""" return self.status_text
[ "def", "__str__", "(", "self", ")", ":", "return", "self", ".", "status_text" ]
[ 75, 4 ]
[ 78, 31 ]
python
en
['en', 'en', 'en']
True
ExecutionEngine.configure_validator
(self, validator)
Optionally configure the validator as appropriate for the execution engine.
Optionally configure the validator as appropriate for the execution engine.
def configure_validator(self, validator): """Optionally configure the validator as appropriate for the execution engine.""" pass
[ "def", "configure_validator", "(", "self", ",", "validator", ")", ":", "pass" ]
[ 116, 4 ]
[ 118, 12 ]
python
en
['en', 'en', 'en']
True
ExecutionEngine.active_batch_data_id
(self)
The batch id for the default batch data. When an execution engine is asked to process a compute domain that does not include a specific batch_id, then the data associated with the active_batch_data_id will be used as the default.
The batch id for the default batch data.
def active_batch_data_id(self): """The batch id for the default batch data. When an execution engine is asked to process a compute domain that does not include a specific batch_id, then the data associated with the active_batch_data_id will be used as the default. """ if self._active_batch_data_id is not None: return self._active_batch_data_id elif len(self.loaded_batch_data_dict) == 1: return list(self.loaded_batch_data_dict.keys())[0] else: return None
[ "def", "active_batch_data_id", "(", "self", ")", ":", "if", "self", ".", "_active_batch_data_id", "is", "not", "None", ":", "return", "self", ".", "_active_batch_data_id", "elif", "len", "(", "self", ".", "loaded_batch_data_dict", ")", "==", "1", ":", "return", "list", "(", "self", ".", "loaded_batch_data_dict", ".", "keys", "(", ")", ")", "[", "0", "]", "else", ":", "return", "None" ]
[ 121, 4 ]
[ 133, 23 ]
python
en
['en', 'en', 'en']
True
ExecutionEngine.active_batch_data
(self)
The data from the currently-active batch.
The data from the currently-active batch.
def active_batch_data(self): """The data from the currently-active batch.""" if self.active_batch_data_id is None: return None else: return self.loaded_batch_data_dict.get(self.active_batch_data_id)
[ "def", "active_batch_data", "(", "self", ")", ":", "if", "self", ".", "active_batch_data_id", "is", "None", ":", "return", "None", "else", ":", "return", "self", ".", "loaded_batch_data_dict", ".", "get", "(", "self", ".", "active_batch_data_id", ")" ]
[ 145, 4 ]
[ 150, 77 ]
python
en
['en', 'en', 'en']
True
ExecutionEngine.loaded_batch_data_dict
(self)
The current dictionary of batches.
The current dictionary of batches.
def loaded_batch_data_dict(self): """The current dictionary of batches.""" return self._batch_data_dict
[ "def", "loaded_batch_data_dict", "(", "self", ")", ":", "return", "self", ".", "_batch_data_dict" ]
[ 153, 4 ]
[ 155, 36 ]
python
en
['en', 'en', 'en']
True
ExecutionEngine.get_batch_data
( self, batch_spec: BatchSpec, )
Interprets batch_data and returns the appropriate data. This method is primarily useful for utility cases (e.g. testing) where data is being fetched without a DataConnector and metadata like batch_markers is unwanted Note: this method is currently a thin wrapper for get_batch_data_and_markers. It simply suppresses the batch_markers.
Interprets batch_data and returns the appropriate data.
def get_batch_data( self, batch_spec: BatchSpec, ) -> Any: """Interprets batch_data and returns the appropriate data. This method is primarily useful for utility cases (e.g. testing) where data is being fetched without a DataConnector and metadata like batch_markers is unwanted Note: this method is currently a thin wrapper for get_batch_data_and_markers. It simply suppresses the batch_markers. """ batch_data, _ = self.get_batch_data_and_markers(batch_spec) return batch_data
[ "def", "get_batch_data", "(", "self", ",", "batch_spec", ":", "BatchSpec", ",", ")", "->", "Any", ":", "batch_data", ",", "_", "=", "self", ".", "get_batch_data_and_markers", "(", "batch_spec", ")", "return", "batch_data" ]
[ 169, 4 ]
[ 183, 25 ]
python
en
['en', 'co', 'en']
True
ExecutionEngine.load_batch_data
(self, batch_id: str, batch_data: Any)
Loads the specified batch_data into the execution engine
Loads the specified batch_data into the execution engine
def load_batch_data(self, batch_id: str, batch_data: Any) -> None: """ Loads the specified batch_data into the execution engine """ self._batch_data_dict[batch_id] = batch_data self._active_batch_data_id = batch_id
[ "def", "load_batch_data", "(", "self", ",", "batch_id", ":", "str", ",", "batch_data", ":", "Any", ")", "->", "None", ":", "self", ".", "_batch_data_dict", "[", "batch_id", "]", "=", "batch_data", "self", ".", "_active_batch_data_id", "=", "batch_id" ]
[ 189, 4 ]
[ 194, 45 ]
python
en
['en', 'error', 'th']
False
ExecutionEngine._load_batch_data_from_dict
(self, batch_data_dict)
Loads all data in batch_data_dict into load_batch_data
Loads all data in batch_data_dict into load_batch_data
def _load_batch_data_from_dict(self, batch_data_dict): """ Loads all data in batch_data_dict into load_batch_data """ for batch_id, batch_data in batch_data_dict.items(): self.load_batch_data(batch_id, batch_data)
[ "def", "_load_batch_data_from_dict", "(", "self", ",", "batch_data_dict", ")", ":", "for", "batch_id", ",", "batch_data", "in", "batch_data_dict", ".", "items", "(", ")", ":", "self", ".", "load_batch_data", "(", "batch_id", ",", "batch_data", ")" ]
[ 196, 4 ]
[ 201, 54 ]
python
en
['en', 'error', 'th']
False
ExecutionEngine.resolve_metrics
( self, metrics_to_resolve: Iterable[MetricConfiguration], metrics: Dict[Tuple, Any] = None, runtime_configuration: dict = None, )
resolve_metrics is the main entrypoint for an execution engine. The execution engine will compute the value of the provided metrics. Args: metrics_to_resolve: the metrics to evaluate metrics: already-computed metrics currently available to the engine runtime_configuration: runtime configuration information Returns: resolved_metrics (Dict): a dictionary with the values for the metrics that have just been resolved.
resolve_metrics is the main entrypoint for an execution engine. The execution engine will compute the value of the provided metrics.
def resolve_metrics( self, metrics_to_resolve: Iterable[MetricConfiguration], metrics: Dict[Tuple, Any] = None, runtime_configuration: dict = None, ) -> dict: """resolve_metrics is the main entrypoint for an execution engine. The execution engine will compute the value of the provided metrics. Args: metrics_to_resolve: the metrics to evaluate metrics: already-computed metrics currently available to the engine runtime_configuration: runtime configuration information Returns: resolved_metrics (Dict): a dictionary with the values for the metrics that have just been resolved. """ if metrics is None: metrics = dict() resolved_metrics = dict() metric_fn_bundle = [] for metric_to_resolve in metrics_to_resolve: metric_class, metric_fn = get_metric_provider( metric_name=metric_to_resolve.metric_name, execution_engine=self ) try: metric_dependencies = { k: metrics[v.id] for k, v in metric_to_resolve.metric_dependencies.items() } except KeyError as e: raise GreatExpectationsError(f"Missing metric dependency: {str(e)}") metric_provider_kwargs = { "cls": metric_class, "execution_engine": self, "metric_domain_kwargs": metric_to_resolve.metric_domain_kwargs, "metric_value_kwargs": metric_to_resolve.metric_value_kwargs, "metrics": metric_dependencies, "runtime_configuration": runtime_configuration, } if metric_fn is None: try: ( metric_fn, compute_domain_kwargs, accessor_domain_kwargs, ) = metric_dependencies.pop("metric_partial_fn") except KeyError as e: raise GreatExpectationsError( f"Missing metric dependency: {str(e)} for metric {metric_to_resolve.metric_name}" ) metric_fn_bundle.append( ( metric_to_resolve, metric_fn, compute_domain_kwargs, accessor_domain_kwargs, metric_provider_kwargs, ) ) continue metric_fn_type = getattr( metric_fn, "metric_fn_type", MetricFunctionTypes.VALUE ) if metric_fn_type in [ MetricPartialFunctionTypes.MAP_SERIES, MetricPartialFunctionTypes.MAP_FN, MetricPartialFunctionTypes.MAP_CONDITION_FN, MetricPartialFunctionTypes.MAP_CONDITION_SERIES, MetricPartialFunctionTypes.WINDOW_FN, MetricPartialFunctionTypes.WINDOW_CONDITION_FN, MetricPartialFunctionTypes.AGGREGATE_FN, ]: # NOTE: 20201026 - JPC - we could use the fact that these metric functions return functions rather # than data to optimize compute in the future resolved_metrics[metric_to_resolve.id] = metric_fn( **metric_provider_kwargs ) elif metric_fn_type == MetricFunctionTypes.VALUE: resolved_metrics[metric_to_resolve.id] = metric_fn( **metric_provider_kwargs ) else: logger.warning( f"Unrecognized metric function type while trying to resolve {str(metric_to_resolve.id)}" ) resolved_metrics[metric_to_resolve.id] = metric_fn( **metric_provider_kwargs ) if len(metric_fn_bundle) > 0: resolved_metrics.update(self.resolve_metric_bundle(metric_fn_bundle)) return resolved_metrics
[ "def", "resolve_metrics", "(", "self", ",", "metrics_to_resolve", ":", "Iterable", "[", "MetricConfiguration", "]", ",", "metrics", ":", "Dict", "[", "Tuple", ",", "Any", "]", "=", "None", ",", "runtime_configuration", ":", "dict", "=", "None", ",", ")", "->", "dict", ":", "if", "metrics", "is", "None", ":", "metrics", "=", "dict", "(", ")", "resolved_metrics", "=", "dict", "(", ")", "metric_fn_bundle", "=", "[", "]", "for", "metric_to_resolve", "in", "metrics_to_resolve", ":", "metric_class", ",", "metric_fn", "=", "get_metric_provider", "(", "metric_name", "=", "metric_to_resolve", ".", "metric_name", ",", "execution_engine", "=", "self", ")", "try", ":", "metric_dependencies", "=", "{", "k", ":", "metrics", "[", "v", ".", "id", "]", "for", "k", ",", "v", "in", "metric_to_resolve", ".", "metric_dependencies", ".", "items", "(", ")", "}", "except", "KeyError", "as", "e", ":", "raise", "GreatExpectationsError", "(", "f\"Missing metric dependency: {str(e)}\"", ")", "metric_provider_kwargs", "=", "{", "\"cls\"", ":", "metric_class", ",", "\"execution_engine\"", ":", "self", ",", "\"metric_domain_kwargs\"", ":", "metric_to_resolve", ".", "metric_domain_kwargs", ",", "\"metric_value_kwargs\"", ":", "metric_to_resolve", ".", "metric_value_kwargs", ",", "\"metrics\"", ":", "metric_dependencies", ",", "\"runtime_configuration\"", ":", "runtime_configuration", ",", "}", "if", "metric_fn", "is", "None", ":", "try", ":", "(", "metric_fn", ",", "compute_domain_kwargs", ",", "accessor_domain_kwargs", ",", ")", "=", "metric_dependencies", ".", "pop", "(", "\"metric_partial_fn\"", ")", "except", "KeyError", "as", "e", ":", "raise", "GreatExpectationsError", "(", "f\"Missing metric dependency: {str(e)} for metric {metric_to_resolve.metric_name}\"", ")", "metric_fn_bundle", ".", "append", "(", "(", "metric_to_resolve", ",", "metric_fn", ",", "compute_domain_kwargs", ",", "accessor_domain_kwargs", ",", "metric_provider_kwargs", ",", ")", ")", "continue", "metric_fn_type", "=", "getattr", "(", "metric_fn", ",", "\"metric_fn_type\"", ",", "MetricFunctionTypes", ".", "VALUE", ")", "if", "metric_fn_type", "in", "[", "MetricPartialFunctionTypes", ".", "MAP_SERIES", ",", "MetricPartialFunctionTypes", ".", "MAP_FN", ",", "MetricPartialFunctionTypes", ".", "MAP_CONDITION_FN", ",", "MetricPartialFunctionTypes", ".", "MAP_CONDITION_SERIES", ",", "MetricPartialFunctionTypes", ".", "WINDOW_FN", ",", "MetricPartialFunctionTypes", ".", "WINDOW_CONDITION_FN", ",", "MetricPartialFunctionTypes", ".", "AGGREGATE_FN", ",", "]", ":", "# NOTE: 20201026 - JPC - we could use the fact that these metric functions return functions rather", "# than data to optimize compute in the future", "resolved_metrics", "[", "metric_to_resolve", ".", "id", "]", "=", "metric_fn", "(", "*", "*", "metric_provider_kwargs", ")", "elif", "metric_fn_type", "==", "MetricFunctionTypes", ".", "VALUE", ":", "resolved_metrics", "[", "metric_to_resolve", ".", "id", "]", "=", "metric_fn", "(", "*", "*", "metric_provider_kwargs", ")", "else", ":", "logger", ".", "warning", "(", "f\"Unrecognized metric function type while trying to resolve {str(metric_to_resolve.id)}\"", ")", "resolved_metrics", "[", "metric_to_resolve", ".", "id", "]", "=", "metric_fn", "(", "*", "*", "metric_provider_kwargs", ")", "if", "len", "(", "metric_fn_bundle", ")", ">", "0", ":", "resolved_metrics", ".", "update", "(", "self", ".", "resolve_metric_bundle", "(", "metric_fn_bundle", ")", ")", "return", "resolved_metrics" ]
[ 203, 4 ]
[ 297, 31 ]
python
en
['en', 'en', 'en']
True
ExecutionEngine.resolve_metric_bundle
(self, metric_fn_bundle)
Resolve a bundle of metrics with the same compute domain as part of a single trip to the compute engine.
Resolve a bundle of metrics with the same compute domain as part of a single trip to the compute engine.
def resolve_metric_bundle(self, metric_fn_bundle): """Resolve a bundle of metrics with the same compute domain as part of a single trip to the compute engine.""" raise NotImplementedError
[ "def", "resolve_metric_bundle", "(", "self", ",", "metric_fn_bundle", ")", ":", "raise", "NotImplementedError" ]
[ 299, 4 ]
[ 301, 33 ]
python
en
['en', 'en', 'en']
True
ExecutionEngine.get_compute_domain
( self, domain_kwargs: dict, domain_type: Union[str, MetricDomainTypes], )
get_compute_domain computes the optimal domain_kwargs for computing metrics based on the given domain_kwargs and specific engine semantics. Returns: A tuple consisting of three elements: 1. data corresponding to the compute domain; 2. a modified copy of domain_kwargs describing the domain of the data returned in (1); 3. a dictionary describing the access instructions for data elements included in the compute domain (e.g. specific column name). In general, the union of the compute_domain_kwargs and accessor_domain_kwargs will be the same as the domain_kwargs provided to this method.
get_compute_domain computes the optimal domain_kwargs for computing metrics based on the given domain_kwargs and specific engine semantics.
def get_compute_domain( self, domain_kwargs: dict, domain_type: Union[str, MetricDomainTypes], ) -> Tuple[Any, dict, dict]: """get_compute_domain computes the optimal domain_kwargs for computing metrics based on the given domain_kwargs and specific engine semantics. Returns: A tuple consisting of three elements: 1. data corresponding to the compute domain; 2. a modified copy of domain_kwargs describing the domain of the data returned in (1); 3. a dictionary describing the access instructions for data elements included in the compute domain (e.g. specific column name). In general, the union of the compute_domain_kwargs and accessor_domain_kwargs will be the same as the domain_kwargs provided to this method. """ raise NotImplementedError
[ "def", "get_compute_domain", "(", "self", ",", "domain_kwargs", ":", "dict", ",", "domain_type", ":", "Union", "[", "str", ",", "MetricDomainTypes", "]", ",", ")", "->", "Tuple", "[", "Any", ",", "dict", ",", "dict", "]", ":", "raise", "NotImplementedError" ]
[ 303, 4 ]
[ 323, 33 ]
python
en
['en', 'en', 'en']
True
ExecutionEngine.add_column_row_condition
( self, domain_kwargs, column_name=None, filter_null=True, filter_nan=False )
EXPERIMENTAL Add a row condition for handling null filter. Args: domain_kwargs: the domain kwargs to use as the base and to which to add the condition column_name: if provided, use this name to add the condition; otherwise, will use "column" key from table_domain_kwargs filter_null: if true, add a filter for null values filter_nan: if true, add a filter for nan values
EXPERIMENTAL
def add_column_row_condition( self, domain_kwargs, column_name=None, filter_null=True, filter_nan=False ): """EXPERIMENTAL Add a row condition for handling null filter. Args: domain_kwargs: the domain kwargs to use as the base and to which to add the condition column_name: if provided, use this name to add the condition; otherwise, will use "column" key from table_domain_kwargs filter_null: if true, add a filter for null values filter_nan: if true, add a filter for nan values """ if filter_null is False and filter_nan is False: logger.warning( "add_column_row_condition called with no filter condition requested" ) return domain_kwargs if filter_nan: raise GreatExpectationsError( "Base ExecutionEngine does not support adding nan condition filters" ) if "row_condition" in domain_kwargs and domain_kwargs["row_condition"]: raise GreatExpectationsError( "ExecutionEngine does not support updating existing row_conditions." ) new_domain_kwargs = copy.deepcopy(domain_kwargs) assert "column" in domain_kwargs or column_name is not None if column_name is not None: column = column_name else: column = domain_kwargs["column"] new_domain_kwargs["condition_parser"] = "great_expectations__experimental__" new_domain_kwargs["row_condition"] = f'col("{column}").notnull()' return new_domain_kwargs
[ "def", "add_column_row_condition", "(", "self", ",", "domain_kwargs", ",", "column_name", "=", "None", ",", "filter_null", "=", "True", ",", "filter_nan", "=", "False", ")", ":", "if", "filter_null", "is", "False", "and", "filter_nan", "is", "False", ":", "logger", ".", "warning", "(", "\"add_column_row_condition called with no filter condition requested\"", ")", "return", "domain_kwargs", "if", "filter_nan", ":", "raise", "GreatExpectationsError", "(", "\"Base ExecutionEngine does not support adding nan condition filters\"", ")", "if", "\"row_condition\"", "in", "domain_kwargs", "and", "domain_kwargs", "[", "\"row_condition\"", "]", ":", "raise", "GreatExpectationsError", "(", "\"ExecutionEngine does not support updating existing row_conditions.\"", ")", "new_domain_kwargs", "=", "copy", ".", "deepcopy", "(", "domain_kwargs", ")", "assert", "\"column\"", "in", "domain_kwargs", "or", "column_name", "is", "not", "None", "if", "column_name", "is", "not", "None", ":", "column", "=", "column_name", "else", ":", "column", "=", "domain_kwargs", "[", "\"column\"", "]", "new_domain_kwargs", "[", "\"condition_parser\"", "]", "=", "\"great_expectations__experimental__\"", "new_domain_kwargs", "[", "\"row_condition\"", "]", "=", "f'col(\"{column}\").notnull()'", "return", "new_domain_kwargs" ]
[ 325, 4 ]
[ 362, 32 ]
python
ca
['en', 'ca', 'pt']
False
instantiate_class_from_config
(config, runtime_environment, config_defaults=None)
Build a GE class from configuration dictionaries.
Build a GE class from configuration dictionaries.
def instantiate_class_from_config(config, runtime_environment, config_defaults=None): """Build a GE class from configuration dictionaries.""" if config_defaults is None: config_defaults = {} config = copy.deepcopy(config) module_name = config.pop("module_name", None) if module_name is None: try: module_name = config_defaults.pop("module_name") except KeyError: raise KeyError( "Neither config : {} nor config_defaults : {} contains a module_name key.".format( config, config_defaults, ) ) else: # Pop the value without using it, to avoid sending an unwanted value to the config_class config_defaults.pop("module_name", None) verify_dynamic_loading_support(module_name=module_name) class_name = config.pop("class_name", None) if class_name is None: logger.warning( "Instantiating class from config without an explicit class_name is dangerous. Consider adding " "an explicit class_name for %s" % config.get("name") ) try: class_name = config_defaults.pop("class_name") except KeyError: raise KeyError( "Neither config : {} nor config_defaults : {} contains a class_name key.".format( config, config_defaults, ) ) else: # Pop the value without using it, to avoid sending an unwanted value to the config_class config_defaults.pop("class_name", None) class_ = load_class(class_name=class_name, module_name=module_name) config_with_defaults = copy.deepcopy(config_defaults) config_with_defaults.update(config) if runtime_environment is not None: # If there are additional kwargs available in the runtime_environment requested by a # class to be instantiated, provide them argspec = inspect.getfullargspec(class_.__init__)[0][1:] missing_args = set(argspec) - set(config_with_defaults.keys()) config_with_defaults.update( { missing_arg: runtime_environment[missing_arg] for missing_arg in missing_args if missing_arg in runtime_environment } ) # Add the entire runtime_environment as well if it's requested if "runtime_environment" in missing_args: config_with_defaults.update({"runtime_environment": runtime_environment}) try: class_instance = class_(**config_with_defaults) except TypeError as e: raise TypeError( "Couldn't instantiate class: {} with config: \n\t{}\n \n".format( class_name, format_dict_for_error_message(config_with_defaults) ) + str(e) ) return class_instance
[ "def", "instantiate_class_from_config", "(", "config", ",", "runtime_environment", ",", "config_defaults", "=", "None", ")", ":", "if", "config_defaults", "is", "None", ":", "config_defaults", "=", "{", "}", "config", "=", "copy", ".", "deepcopy", "(", "config", ")", "module_name", "=", "config", ".", "pop", "(", "\"module_name\"", ",", "None", ")", "if", "module_name", "is", "None", ":", "try", ":", "module_name", "=", "config_defaults", ".", "pop", "(", "\"module_name\"", ")", "except", "KeyError", ":", "raise", "KeyError", "(", "\"Neither config : {} nor config_defaults : {} contains a module_name key.\"", ".", "format", "(", "config", ",", "config_defaults", ",", ")", ")", "else", ":", "# Pop the value without using it, to avoid sending an unwanted value to the config_class", "config_defaults", ".", "pop", "(", "\"module_name\"", ",", "None", ")", "verify_dynamic_loading_support", "(", "module_name", "=", "module_name", ")", "class_name", "=", "config", ".", "pop", "(", "\"class_name\"", ",", "None", ")", "if", "class_name", "is", "None", ":", "logger", ".", "warning", "(", "\"Instantiating class from config without an explicit class_name is dangerous. Consider adding \"", "\"an explicit class_name for %s\"", "%", "config", ".", "get", "(", "\"name\"", ")", ")", "try", ":", "class_name", "=", "config_defaults", ".", "pop", "(", "\"class_name\"", ")", "except", "KeyError", ":", "raise", "KeyError", "(", "\"Neither config : {} nor config_defaults : {} contains a class_name key.\"", ".", "format", "(", "config", ",", "config_defaults", ",", ")", ")", "else", ":", "# Pop the value without using it, to avoid sending an unwanted value to the config_class", "config_defaults", ".", "pop", "(", "\"class_name\"", ",", "None", ")", "class_", "=", "load_class", "(", "class_name", "=", "class_name", ",", "module_name", "=", "module_name", ")", "config_with_defaults", "=", "copy", ".", "deepcopy", "(", "config_defaults", ")", "config_with_defaults", ".", "update", "(", "config", ")", "if", "runtime_environment", "is", "not", "None", ":", "# If there are additional kwargs available in the runtime_environment requested by a", "# class to be instantiated, provide them", "argspec", "=", "inspect", ".", "getfullargspec", "(", "class_", ".", "__init__", ")", "[", "0", "]", "[", "1", ":", "]", "missing_args", "=", "set", "(", "argspec", ")", "-", "set", "(", "config_with_defaults", ".", "keys", "(", ")", ")", "config_with_defaults", ".", "update", "(", "{", "missing_arg", ":", "runtime_environment", "[", "missing_arg", "]", "for", "missing_arg", "in", "missing_args", "if", "missing_arg", "in", "runtime_environment", "}", ")", "# Add the entire runtime_environment as well if it's requested", "if", "\"runtime_environment\"", "in", "missing_args", ":", "config_with_defaults", ".", "update", "(", "{", "\"runtime_environment\"", ":", "runtime_environment", "}", ")", "try", ":", "class_instance", "=", "class_", "(", "*", "*", "config_with_defaults", ")", "except", "TypeError", "as", "e", ":", "raise", "TypeError", "(", "\"Couldn't instantiate class: {} with config: \\n\\t{}\\n \\n\"", ".", "format", "(", "class_name", ",", "format_dict_for_error_message", "(", "config_with_defaults", ")", ")", "+", "str", "(", "e", ")", ")", "return", "class_instance" ]
[ 54, 0 ]
[ 129, 25 ]
python
en
['en', 'en', 'en']
True
substitute_config_variable
( template_str, config_variables_dict, dollar_sign_escape_string: str = r"\$" )
This method takes a string, and if it contains a pattern ${SOME_VARIABLE} or $SOME_VARIABLE, returns a string where the pattern is replaced with the value of SOME_VARIABLE, otherwise returns the string unchanged. These patterns are case sensitive. There can be multiple patterns in a string, e.g. all 3 will be substituted in the following: $SOME_VARIABLE${some_OTHER_variable}$another_variable If the environment variable SOME_VARIABLE is set, the method uses its value for substitution. If it is not set, the value of SOME_VARIABLE is looked up in the config variables store (file). If it is not found there, the input string is returned as is. If the value to substitute is not a string, it is returned as-is. If the value to substitute begins with dollar_sign_escape_string it is not substituted. If the value starts with the keyword `secret|`, it tries to apply secret store substitution. :param template_str: a string that might or might not be of the form ${SOME_VARIABLE} or $SOME_VARIABLE :param config_variables_dict: a dictionary of config variables. It is loaded from the config variables store (by default, "uncommitted/config_variables.yml file) :param dollar_sign_escape_string: a string that will be used in place of a `$` when substitution is not desired. :return: a string with values substituted, or the same object if template_str is not a string.
This method takes a string, and if it contains a pattern ${SOME_VARIABLE} or $SOME_VARIABLE, returns a string where the pattern is replaced with the value of SOME_VARIABLE, otherwise returns the string unchanged. These patterns are case sensitive. There can be multiple patterns in a string, e.g. all 3 will be substituted in the following: $SOME_VARIABLE${some_OTHER_variable}$another_variable
def substitute_config_variable( template_str, config_variables_dict, dollar_sign_escape_string: str = r"\$" ): """ This method takes a string, and if it contains a pattern ${SOME_VARIABLE} or $SOME_VARIABLE, returns a string where the pattern is replaced with the value of SOME_VARIABLE, otherwise returns the string unchanged. These patterns are case sensitive. There can be multiple patterns in a string, e.g. all 3 will be substituted in the following: $SOME_VARIABLE${some_OTHER_variable}$another_variable If the environment variable SOME_VARIABLE is set, the method uses its value for substitution. If it is not set, the value of SOME_VARIABLE is looked up in the config variables store (file). If it is not found there, the input string is returned as is. If the value to substitute is not a string, it is returned as-is. If the value to substitute begins with dollar_sign_escape_string it is not substituted. If the value starts with the keyword `secret|`, it tries to apply secret store substitution. :param template_str: a string that might or might not be of the form ${SOME_VARIABLE} or $SOME_VARIABLE :param config_variables_dict: a dictionary of config variables. It is loaded from the config variables store (by default, "uncommitted/config_variables.yml file) :param dollar_sign_escape_string: a string that will be used in place of a `$` when substitution is not desired. :return: a string with values substituted, or the same object if template_str is not a string. """ if template_str is None: return template_str # 1. Make substitutions for non-escaped patterns try: match = re.finditer( r"(?<!\\)\$\{(.*?)\}|(?<!\\)\$([_a-zA-Z][_a-zA-Z0-9]*)", template_str ) except TypeError: # If the value is not a string (e.g., a boolean), we should return it as is return template_str for m in match: # Match either the first group e.g. ${Variable} or the second e.g. $Variable config_variable_name = m.group(1) or m.group(2) config_variable_value = config_variables_dict.get(config_variable_name) if config_variable_value is not None: if not isinstance(config_variable_value, str): return config_variable_value template_str = template_str.replace(m.group(), config_variable_value) else: raise ge_exceptions.MissingConfigVariableError( f"""\n\nUnable to find a match for config substitution variable: `{config_variable_name}`. Please add this missing variable to your `uncommitted/config_variables.yml` file or your environment variables. See https://great-expectations.readthedocs.io/en/latest/reference/data_context_reference.html#managing-environment-and-secrets""", missing_config_variable=config_variable_name, ) # 2. Replace the "$"'s that had been escaped template_str = template_str.replace(dollar_sign_escape_string, "$") template_str = substitute_value_from_secret_store(template_str) return template_str
[ "def", "substitute_config_variable", "(", "template_str", ",", "config_variables_dict", ",", "dollar_sign_escape_string", ":", "str", "=", "r\"\\$\"", ")", ":", "if", "template_str", "is", "None", ":", "return", "template_str", "# 1. Make substitutions for non-escaped patterns", "try", ":", "match", "=", "re", ".", "finditer", "(", "r\"(?<!\\\\)\\$\\{(.*?)\\}|(?<!\\\\)\\$([_a-zA-Z][_a-zA-Z0-9]*)\"", ",", "template_str", ")", "except", "TypeError", ":", "# If the value is not a string (e.g., a boolean), we should return it as is", "return", "template_str", "for", "m", "in", "match", ":", "# Match either the first group e.g. ${Variable} or the second e.g. $Variable", "config_variable_name", "=", "m", ".", "group", "(", "1", ")", "or", "m", ".", "group", "(", "2", ")", "config_variable_value", "=", "config_variables_dict", ".", "get", "(", "config_variable_name", ")", "if", "config_variable_value", "is", "not", "None", ":", "if", "not", "isinstance", "(", "config_variable_value", ",", "str", ")", ":", "return", "config_variable_value", "template_str", "=", "template_str", ".", "replace", "(", "m", ".", "group", "(", ")", ",", "config_variable_value", ")", "else", ":", "raise", "ge_exceptions", ".", "MissingConfigVariableError", "(", "f\"\"\"\\n\\nUnable to find a match for config substitution variable: `{config_variable_name}`.\nPlease add this missing variable to your `uncommitted/config_variables.yml` file or your environment variables.\nSee https://great-expectations.readthedocs.io/en/latest/reference/data_context_reference.html#managing-environment-and-secrets\"\"\"", ",", "missing_config_variable", "=", "config_variable_name", ",", ")", "# 2. Replace the \"$\"'s that had been escaped", "template_str", "=", "template_str", ".", "replace", "(", "dollar_sign_escape_string", ",", "\"$\"", ")", "template_str", "=", "substitute_value_from_secret_store", "(", "template_str", ")", "return", "template_str" ]
[ 171, 0 ]
[ 233, 23 ]
python
en
['en', 'error', 'th']
False
substitute_value_from_secret_store
(value)
This method takes a value, tries to parse the value to fetch a secret from a secret manager and returns the secret's value only if the input value is a string and contains one of the following patterns: - AWS Secrets Manager: the input value starts with ``secret|arn:aws:secretsmanager`` - GCP Secret Manager: the input value matches the following regex ``^secret\\|projects\\/[a-z0-9\\_\\-]{6,30}\\/secrets`` - Azure Key Vault: the input value matches the following regex ``^secret\\|https:\\/\\/[a-zA-Z0-9\\-]{3,24}\\.vault\\.azure\\.net`` Input value examples: - AWS Secrets Manager: ``secret|arn:aws:secretsmanager:eu-west-3:123456789012:secret:my_secret`` - GCP Secret Manager: ``secret|projects/gcp_project_id/secrets/my_secret`` - Azure Key Vault: ``secret|https://vault-name.vault.azure.net/secrets/my-secret`` :param value: a string that might or might not start with `secret|` :return: a string with the value substituted by the secret from the secret store, or the same object if value is not a string.
This method takes a value, tries to parse the value to fetch a secret from a secret manager and returns the secret's value only if the input value is a string and contains one of the following patterns:
def substitute_value_from_secret_store(value): """ This method takes a value, tries to parse the value to fetch a secret from a secret manager and returns the secret's value only if the input value is a string and contains one of the following patterns: - AWS Secrets Manager: the input value starts with ``secret|arn:aws:secretsmanager`` - GCP Secret Manager: the input value matches the following regex ``^secret\\|projects\\/[a-z0-9\\_\\-]{6,30}\\/secrets`` - Azure Key Vault: the input value matches the following regex ``^secret\\|https:\\/\\/[a-zA-Z0-9\\-]{3,24}\\.vault\\.azure\\.net`` Input value examples: - AWS Secrets Manager: ``secret|arn:aws:secretsmanager:eu-west-3:123456789012:secret:my_secret`` - GCP Secret Manager: ``secret|projects/gcp_project_id/secrets/my_secret`` - Azure Key Vault: ``secret|https://vault-name.vault.azure.net/secrets/my-secret`` :param value: a string that might or might not start with `secret|` :return: a string with the value substituted by the secret from the secret store, or the same object if value is not a string. """ if isinstance(value, str) and value.startswith("secret|"): if value.startswith("secret|arn:aws:secretsmanager"): return substitute_value_from_aws_secrets_manager(value) elif re.compile(r"^secret\|projects\/[a-z0-9\_\-]{6,30}\/secrets").match(value): return substitute_value_from_gcp_secret_manager(value) elif re.compile( r"^secret\|https:\/\/[a-zA-Z0-9\-]{3,24}\.vault\.azure\.net" ).match(value): return substitute_value_from_azure_keyvault(value) return value
[ "def", "substitute_value_from_secret_store", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", "and", "value", ".", "startswith", "(", "\"secret|\"", ")", ":", "if", "value", ".", "startswith", "(", "\"secret|arn:aws:secretsmanager\"", ")", ":", "return", "substitute_value_from_aws_secrets_manager", "(", "value", ")", "elif", "re", ".", "compile", "(", "r\"^secret\\|projects\\/[a-z0-9\\_\\-]{6,30}\\/secrets\"", ")", ".", "match", "(", "value", ")", ":", "return", "substitute_value_from_gcp_secret_manager", "(", "value", ")", "elif", "re", ".", "compile", "(", "r\"^secret\\|https:\\/\\/[a-zA-Z0-9\\-]{3,24}\\.vault\\.azure\\.net\"", ")", ".", "match", "(", "value", ")", ":", "return", "substitute_value_from_azure_keyvault", "(", "value", ")", "return", "value" ]
[ 237, 0 ]
[ 270, 16 ]
python
en
['en', 'error', 'th']
False
substitute_value_from_aws_secrets_manager
(value)
This methods uses a boto3 client and the secretsmanager service to try to retrieve the secret value from the elements it is able to parse from the input value. - value: string with pattern ``secret|arn:aws:secretsmanager:${region_name}:${account_id}:secret:${secret_name}`` optional : after the value above, a secret version can be added ``:${secret_version}`` optional : after the value above, a secret key can be added ``|${secret_key}`` - region_name: `AWS region used by the secrets manager <https://docs.aws.amazon.com/general/latest/gr/rande.html>`_ - account_id: `Account ID for the AWS account used by the secrets manager <https://docs.aws.amazon.com/en_us/IAM/latest/UserGuide/console_account-alias.html>`_ This value is currently not used. - secret_name: Name of the secret - secret_version: UUID of the version of the secret - secret_key: Only if the secret's data is a JSON string, which key of the dict should be retrieve :param value: a string that starts with ``secret|arn:aws:secretsmanager`` :return: a string with the value substituted by the secret from the AWS Secrets Manager store :raises: ImportError, ValueError
This methods uses a boto3 client and the secretsmanager service to try to retrieve the secret value from the elements it is able to parse from the input value.
def substitute_value_from_aws_secrets_manager(value): """ This methods uses a boto3 client and the secretsmanager service to try to retrieve the secret value from the elements it is able to parse from the input value. - value: string with pattern ``secret|arn:aws:secretsmanager:${region_name}:${account_id}:secret:${secret_name}`` optional : after the value above, a secret version can be added ``:${secret_version}`` optional : after the value above, a secret key can be added ``|${secret_key}`` - region_name: `AWS region used by the secrets manager <https://docs.aws.amazon.com/general/latest/gr/rande.html>`_ - account_id: `Account ID for the AWS account used by the secrets manager <https://docs.aws.amazon.com/en_us/IAM/latest/UserGuide/console_account-alias.html>`_ This value is currently not used. - secret_name: Name of the secret - secret_version: UUID of the version of the secret - secret_key: Only if the secret's data is a JSON string, which key of the dict should be retrieve :param value: a string that starts with ``secret|arn:aws:secretsmanager`` :return: a string with the value substituted by the secret from the AWS Secrets Manager store :raises: ImportError, ValueError """ regex = re.compile( r"^secret\|arn:aws:secretsmanager:([a-z\-0-9]+):([0-9]{12}):secret:([a-zA-Z0-9\/_\+=\.@\-]+)" r"(?:\:([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}))?(?:\|([^\|]+))?$" ) if not boto3: logger.error( "boto3 is not installed, please install great_expectations with aws_secrets extra > " "pip install great_expectations[aws_secrets]" ) raise ImportError("Could not import boto3") matches = regex.match(value) if not matches: raise ValueError(f"Could not match the value with regex {regex}") region_name = matches.group(1) secret_name = matches.group(3) secret_version = matches.group(4) secret_key = matches.group(5) # Create a Secrets Manager client session = boto3.session.Session() client = session.client(service_name="secretsmanager", region_name=region_name) if secret_version: secret_response = client.get_secret_value( SecretId=secret_name, VersionId=secret_version ) else: secret_response = client.get_secret_value(SecretId=secret_name) # Decrypts secret using the associated KMS CMK. # Depending on whether the secret is a string or binary, one of these fields will be populated. if "SecretString" in secret_response: secret = secret_response["SecretString"] else: secret = base64.b64decode(secret_response["SecretBinary"]).decode("utf-8") if secret_key: secret = json.loads(secret)[secret_key] return secret
[ "def", "substitute_value_from_aws_secrets_manager", "(", "value", ")", ":", "regex", "=", "re", ".", "compile", "(", "r\"^secret\\|arn:aws:secretsmanager:([a-z\\-0-9]+):([0-9]{12}):secret:([a-zA-Z0-9\\/_\\+=\\.@\\-]+)\"", "r\"(?:\\:([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}))?(?:\\|([^\\|]+))?$\"", ")", "if", "not", "boto3", ":", "logger", ".", "error", "(", "\"boto3 is not installed, please install great_expectations with aws_secrets extra > \"", "\"pip install great_expectations[aws_secrets]\"", ")", "raise", "ImportError", "(", "\"Could not import boto3\"", ")", "matches", "=", "regex", ".", "match", "(", "value", ")", "if", "not", "matches", ":", "raise", "ValueError", "(", "f\"Could not match the value with regex {regex}\"", ")", "region_name", "=", "matches", ".", "group", "(", "1", ")", "secret_name", "=", "matches", ".", "group", "(", "3", ")", "secret_version", "=", "matches", ".", "group", "(", "4", ")", "secret_key", "=", "matches", ".", "group", "(", "5", ")", "# Create a Secrets Manager client", "session", "=", "boto3", ".", "session", ".", "Session", "(", ")", "client", "=", "session", ".", "client", "(", "service_name", "=", "\"secretsmanager\"", ",", "region_name", "=", "region_name", ")", "if", "secret_version", ":", "secret_response", "=", "client", ".", "get_secret_value", "(", "SecretId", "=", "secret_name", ",", "VersionId", "=", "secret_version", ")", "else", ":", "secret_response", "=", "client", ".", "get_secret_value", "(", "SecretId", "=", "secret_name", ")", "# Decrypts secret using the associated KMS CMK.", "# Depending on whether the secret is a string or binary, one of these fields will be populated.", "if", "\"SecretString\"", "in", "secret_response", ":", "secret", "=", "secret_response", "[", "\"SecretString\"", "]", "else", ":", "secret", "=", "base64", ".", "b64decode", "(", "secret_response", "[", "\"SecretBinary\"", "]", ")", ".", "decode", "(", "\"utf-8\"", ")", "if", "secret_key", ":", "secret", "=", "json", ".", "loads", "(", "secret", ")", "[", "secret_key", "]", "return", "secret" ]
[ 273, 0 ]
[ 337, 17 ]
python
en
['en', 'error', 'th']
False
substitute_value_from_gcp_secret_manager
(value)
This methods uses a google.cloud.secretmanager.SecretManagerServiceClient to try to retrieve the secret value from the elements it is able to parse from the input value. value: string with pattern ``secret|projects/${project_id}/secrets/${secret_name}`` optional : after the value above, a secret version can be added ``/versions/${secret_version}`` optional : after the value above, a secret key can be added ``|${secret_key}`` - project_id: `Project ID of the GCP project on which the secret manager is implemented <https://cloud.google.com/resource-manager/docs/creating-managing-projects#before_you_begin>`_ - secret_name: Name of the secret - secret_version: ID of the version of the secret - secret_key: Only if the secret's data is a JSON string, which key of the dict should be retrieve :param value: a string that matches the following regex ``^secret|projects/[a-z0-9_-]{6,30}/secrets`` :return: a string with the value substituted by the secret from the GCP Secret Manager store :raises: ImportError, ValueError
This methods uses a google.cloud.secretmanager.SecretManagerServiceClient to try to retrieve the secret value from the elements it is able to parse from the input value.
def substitute_value_from_gcp_secret_manager(value): """ This methods uses a google.cloud.secretmanager.SecretManagerServiceClient to try to retrieve the secret value from the elements it is able to parse from the input value. value: string with pattern ``secret|projects/${project_id}/secrets/${secret_name}`` optional : after the value above, a secret version can be added ``/versions/${secret_version}`` optional : after the value above, a secret key can be added ``|${secret_key}`` - project_id: `Project ID of the GCP project on which the secret manager is implemented <https://cloud.google.com/resource-manager/docs/creating-managing-projects#before_you_begin>`_ - secret_name: Name of the secret - secret_version: ID of the version of the secret - secret_key: Only if the secret's data is a JSON string, which key of the dict should be retrieve :param value: a string that matches the following regex ``^secret|projects/[a-z0-9_-]{6,30}/secrets`` :return: a string with the value substituted by the secret from the GCP Secret Manager store :raises: ImportError, ValueError """ regex = re.compile( r"^secret\|projects\/([a-z0-9\_\-]{6,30})\/secrets/([a-zA-Z\_\-]{1,255})" r"(?:\/versions\/([a-z0-9]+))?(?:\|([^\|]+))?$" ) if not secretmanager: logger.error( "secretmanager is not installed, please install great_expectations with gcp extra > " "pip install great_expectations[gcp]" ) raise ImportError("Could not import secretmanager from google.cloud") client = secretmanager.SecretManagerServiceClient() matches = regex.match(value) if not matches: raise ValueError(f"Could not match the value with regex {regex}") project_id = matches.group(1) secret_id = matches.group(2) secret_version = matches.group(3) secret_key = matches.group(4) if not secret_version: secret_version = "latest" name = f"projects/{project_id}/secrets/{secret_id}/versions/{secret_version}" try: secret = client.access_secret_version(name=name)._pb.payload.data.decode( "utf-8" ) except AttributeError: secret = client.access_secret_version(name=name).payload.data.decode( "utf-8" ) # for google-cloud-secret-manager < 2.0.0 if secret_key: secret = json.loads(secret)[secret_key] return secret
[ "def", "substitute_value_from_gcp_secret_manager", "(", "value", ")", ":", "regex", "=", "re", ".", "compile", "(", "r\"^secret\\|projects\\/([a-z0-9\\_\\-]{6,30})\\/secrets/([a-zA-Z\\_\\-]{1,255})\"", "r\"(?:\\/versions\\/([a-z0-9]+))?(?:\\|([^\\|]+))?$\"", ")", "if", "not", "secretmanager", ":", "logger", ".", "error", "(", "\"secretmanager is not installed, please install great_expectations with gcp extra > \"", "\"pip install great_expectations[gcp]\"", ")", "raise", "ImportError", "(", "\"Could not import secretmanager from google.cloud\"", ")", "client", "=", "secretmanager", ".", "SecretManagerServiceClient", "(", ")", "matches", "=", "regex", ".", "match", "(", "value", ")", "if", "not", "matches", ":", "raise", "ValueError", "(", "f\"Could not match the value with regex {regex}\"", ")", "project_id", "=", "matches", ".", "group", "(", "1", ")", "secret_id", "=", "matches", ".", "group", "(", "2", ")", "secret_version", "=", "matches", ".", "group", "(", "3", ")", "secret_key", "=", "matches", ".", "group", "(", "4", ")", "if", "not", "secret_version", ":", "secret_version", "=", "\"latest\"", "name", "=", "f\"projects/{project_id}/secrets/{secret_id}/versions/{secret_version}\"", "try", ":", "secret", "=", "client", ".", "access_secret_version", "(", "name", "=", "name", ")", ".", "_pb", ".", "payload", ".", "data", ".", "decode", "(", "\"utf-8\"", ")", "except", "AttributeError", ":", "secret", "=", "client", ".", "access_secret_version", "(", "name", "=", "name", ")", ".", "payload", ".", "data", ".", "decode", "(", "\"utf-8\"", ")", "# for google-cloud-secret-manager < 2.0.0", "if", "secret_key", ":", "secret", "=", "json", ".", "loads", "(", "secret", ")", "[", "secret_key", "]", "return", "secret" ]
[ 340, 0 ]
[ 395, 17 ]
python
en
['en', 'error', 'th']
False