repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
kplindegaard/smbus2
smbus2/smbus2.py
SMBus.read_word_data
python
def read_word_data(self, i2c_addr, register, force=None): self._set_address(i2c_addr, force=force) msg = i2c_smbus_ioctl_data.create( read_write=I2C_SMBUS_READ, command=register, size=I2C_SMBUS_WORD_DATA ) ioctl(self.fd, I2C_SMBUS, msg) return msg.data.contents.word
Read a single word (2 bytes) from a given register. :param i2c_addr: i2c address :type i2c_addr: int :param register: Register to read :type register: int :param force: :type force: Boolean :return: 2-byte word :rtype: int
train
https://github.com/kplindegaard/smbus2/blob/a1088a03438dba84c266b73ad61b0c06750d0961/smbus2/smbus2.py#L409-L427
[ "def create(read_write=I2C_SMBUS_READ, command=0, size=I2C_SMBUS_BYTE_DATA):\n u = union_i2c_smbus_data()\n return i2c_smbus_ioctl_data(\n read_write=read_write, command=command, size=size,\n data=union_pointer_type(u))\n", "def _set_address(self, address, force=None):\n \"\"\"\n Set i2c...
class SMBus(object): def __init__(self, bus=None, force=False): """ Initialize and (optionally) open an i2c bus connection. :param bus: i2c bus number (e.g. 0 or 1). If not given, a subsequent call to ``open()`` is required. :type bus: int :param force: force us...
kplindegaard/smbus2
smbus2/smbus2.py
SMBus.process_call
python
def process_call(self, i2c_addr, register, value, force=None): self._set_address(i2c_addr, force=force) msg = i2c_smbus_ioctl_data.create( read_write=I2C_SMBUS_WRITE, command=register, size=I2C_SMBUS_PROC_CALL ) msg.data.contents.word = value ioctl(self.fd, I2C_SMBUS,...
Executes a SMBus Process Call, sending a 16-bit value and receiving a 16-bit response :param i2c_addr: i2c address :type i2c_addr: int :param register: Register to read/write to :type register: int :param value: Word value to transmit :type value: int :param forc...
train
https://github.com/kplindegaard/smbus2/blob/a1088a03438dba84c266b73ad61b0c06750d0961/smbus2/smbus2.py#L450-L470
[ "def create(read_write=I2C_SMBUS_READ, command=0, size=I2C_SMBUS_BYTE_DATA):\n u = union_i2c_smbus_data()\n return i2c_smbus_ioctl_data(\n read_write=read_write, command=command, size=size,\n data=union_pointer_type(u))\n", "def _set_address(self, address, force=None):\n \"\"\"\n Set i2c...
class SMBus(object): def __init__(self, bus=None, force=False): """ Initialize and (optionally) open an i2c bus connection. :param bus: i2c bus number (e.g. 0 or 1). If not given, a subsequent call to ``open()`` is required. :type bus: int :param force: force us...
kplindegaard/smbus2
smbus2/smbus2.py
SMBus.read_block_data
python
def read_block_data(self, i2c_addr, register, force=None): self._set_address(i2c_addr, force=force) msg = i2c_smbus_ioctl_data.create( read_write=I2C_SMBUS_READ, command=register, size=I2C_SMBUS_BLOCK_DATA ) ioctl(self.fd, I2C_SMBUS, msg) length = msg.data.contents.bl...
Read a block of up to 32-bytes from a given register. :param i2c_addr: i2c address :type i2c_addr: int :param register: Start register :type register: int :param force: :type force: Boolean :return: List of bytes :rtype: list
train
https://github.com/kplindegaard/smbus2/blob/a1088a03438dba84c266b73ad61b0c06750d0961/smbus2/smbus2.py#L472-L491
[ "def create(read_write=I2C_SMBUS_READ, command=0, size=I2C_SMBUS_BYTE_DATA):\n u = union_i2c_smbus_data()\n return i2c_smbus_ioctl_data(\n read_write=read_write, command=command, size=size,\n data=union_pointer_type(u))\n", "def _set_address(self, address, force=None):\n \"\"\"\n Set i2c...
class SMBus(object): def __init__(self, bus=None, force=False): """ Initialize and (optionally) open an i2c bus connection. :param bus: i2c bus number (e.g. 0 or 1). If not given, a subsequent call to ``open()`` is required. :type bus: int :param force: force us...
kplindegaard/smbus2
smbus2/smbus2.py
SMBus.write_block_data
python
def write_block_data(self, i2c_addr, register, data, force=None): length = len(data) if length > I2C_SMBUS_BLOCK_MAX: raise ValueError("Data length cannot exceed %d bytes" % I2C_SMBUS_BLOCK_MAX) self._set_address(i2c_addr, force=force) msg = i2c_smbus_ioctl_data.create( ...
Write a block of byte data to a given register. :param i2c_addr: i2c address :type i2c_addr: int :param register: Start register :type register: int :param data: List of bytes :type data: list :param force: :type force: Boolean :rtype: None
train
https://github.com/kplindegaard/smbus2/blob/a1088a03438dba84c266b73ad61b0c06750d0961/smbus2/smbus2.py#L493-L516
[ "def create(read_write=I2C_SMBUS_READ, command=0, size=I2C_SMBUS_BYTE_DATA):\n u = union_i2c_smbus_data()\n return i2c_smbus_ioctl_data(\n read_write=read_write, command=command, size=size,\n data=union_pointer_type(u))\n", "def _set_address(self, address, force=None):\n \"\"\"\n Set i2c...
class SMBus(object): def __init__(self, bus=None, force=False): """ Initialize and (optionally) open an i2c bus connection. :param bus: i2c bus number (e.g. 0 or 1). If not given, a subsequent call to ``open()`` is required. :type bus: int :param force: force us...
kplindegaard/smbus2
smbus2/smbus2.py
SMBus.read_i2c_block_data
python
def read_i2c_block_data(self, i2c_addr, register, length, force=None): if length > I2C_SMBUS_BLOCK_MAX: raise ValueError("Desired block length over %d bytes" % I2C_SMBUS_BLOCK_MAX) self._set_address(i2c_addr, force=force) msg = i2c_smbus_ioctl_data.create( read_write=I2C_...
Read a block of byte data from a given register. :param i2c_addr: i2c address :type i2c_addr: int :param register: Start register :type register: int :param length: Desired block length :type length: int :param force: :type force: Boolean :return:...
train
https://github.com/kplindegaard/smbus2/blob/a1088a03438dba84c266b73ad61b0c06750d0961/smbus2/smbus2.py#L546-L569
[ "def create(read_write=I2C_SMBUS_READ, command=0, size=I2C_SMBUS_BYTE_DATA):\n u = union_i2c_smbus_data()\n return i2c_smbus_ioctl_data(\n read_write=read_write, command=command, size=size,\n data=union_pointer_type(u))\n", "def _set_address(self, address, force=None):\n \"\"\"\n Set i2c...
class SMBus(object): def __init__(self, bus=None, force=False): """ Initialize and (optionally) open an i2c bus connection. :param bus: i2c bus number (e.g. 0 or 1). If not given, a subsequent call to ``open()`` is required. :type bus: int :param force: force us...
kplindegaard/smbus2
smbus2/smbus2.py
SMBus.i2c_rdwr
python
def i2c_rdwr(self, *i2c_msgs): ioctl_data = i2c_rdwr_ioctl_data.create(*i2c_msgs) ioctl(self.fd, I2C_RDWR, ioctl_data)
Combine a series of i2c read and write operations in a single transaction (with repeated start bits but no stop bits in between). This method takes i2c_msg instances as input, which must be created first with :py:meth:`i2c_msg.read` or :py:meth:`i2c_msg.write`. :param i2c_msgs: One or ...
train
https://github.com/kplindegaard/smbus2/blob/a1088a03438dba84c266b73ad61b0c06750d0961/smbus2/smbus2.py#L596-L609
[ "def create(*i2c_msg_instances):\n \"\"\"\n Factory method for creating a i2c_rdwr_ioctl_data struct that can\n be called with ``ioctl(fd, I2C_RDWR, data)``.\n\n :param i2c_msg_instances: Up to 42 i2c_msg instances\n :rtype: i2c_rdwr_ioctl_data\n \"\"\"\n n_msg = len(i2c_msg_instances)\n msg...
class SMBus(object): def __init__(self, bus=None, force=False): """ Initialize and (optionally) open an i2c bus connection. :param bus: i2c bus number (e.g. 0 or 1). If not given, a subsequent call to ``open()`` is required. :type bus: int :param force: force us...
jcushman/pdfquery
pdfquery/cache.py
BaseCache.set_hash_key
python
def set_hash_key(self, file): filehasher = hashlib.md5() while True: data = file.read(8192) if not data: break filehasher.update(data) file.seek(0) self.hash_key = filehasher.hexdigest()
Calculate and store hash key for file.
train
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/cache.py#L10-L19
null
class BaseCache(object): def __init__(self): self.hash_key = None def set(self, page_range_key, tree): """write tree to key""" pass def get(self, page_range_key): """load tree from key, or None if cache miss""" return None
jcushman/pdfquery
pdfquery/pdfquery.py
_append_sorted
python
def _append_sorted(root, el, comparator): """ Add el as a child of root, or as a child of one of root's children. Comparator is a function(a, b) returning > 0 if a is a child of b, < 0 if b is a child of a, 0 if neither. """ for child in root: rel = comparator(el, child) if re...
Add el as a child of root, or as a child of one of root's children. Comparator is a function(a, b) returning > 0 if a is a child of b, < 0 if b is a child of a, 0 if neither.
train
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L45-L60
null
from __future__ import print_function # -*- coding: utf-8 -*- # builtins import codecs import json import numbers import re import chardet try: from collections import OrderedDict except ImportError: OrderedDict = dict # sorry py2.6! Ordering isn't that important for our purposes anyway. # pdfminer from pdfm...
jcushman/pdfquery
pdfquery/pdfquery.py
_box_in_box
python
def _box_in_box(el, child): """ Return True if child is contained within el. """ return all([ float(el.get('x0')) <= float(child.get('x0')), float(el.get('x1')) >= float(child.get('x1')), float(el.get('y0')) <= float(child.get('y0')), float(el.get('y1')) >= float(child.get(...
Return True if child is contained within el.
train
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L63-L70
null
from __future__ import print_function # -*- coding: utf-8 -*- # builtins import codecs import json import numbers import re import chardet try: from collections import OrderedDict except ImportError: OrderedDict = dict # sorry py2.6! Ordering isn't that important for our purposes anyway. # pdfminer from pdfm...
jcushman/pdfquery
pdfquery/pdfquery.py
_comp_bbox
python
def _comp_bbox(el, el2): """ Return 1 if el in el2, -1 if el2 in el, else 0""" # only compare if both elements have x/y coordinates if _comp_bbox_keys_required <= set(el.keys()) and \ _comp_bbox_keys_required <= set(el2.keys()): if _box_in_box(el2, el): return 1 ...
Return 1 if el in el2, -1 if el2 in el, else 0
train
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L74-L83
null
from __future__ import print_function # -*- coding: utf-8 -*- # builtins import codecs import json import numbers import re import chardet try: from collections import OrderedDict except ImportError: OrderedDict = dict # sorry py2.6! Ordering isn't that important for our purposes anyway. # pdfminer from pdfm...
jcushman/pdfquery
pdfquery/pdfquery.py
smart_unicode_decode
python
def smart_unicode_decode(encoded_string): """ Given an encoded string of unknown format, detect the format with chardet and return the unicode version. Example input from bug #11: ('\xfe\xff\x00I\x00n\x00s\x00p\x00e\x00c\x00t\x00i\x00o\x00n\x00' '\x00R\x00e\x00p\x00o...
Given an encoded string of unknown format, detect the format with chardet and return the unicode version. Example input from bug #11: ('\xfe\xff\x00I\x00n\x00s\x00p\x00e\x00c\x00t\x00i\x00o\x00n\x00' '\x00R\x00e\x00p\x00o\x00r\x00t\x00 \x00v\x002\x00.\x002')
train
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L114-L146
null
from __future__ import print_function # -*- coding: utf-8 -*- # builtins import codecs import json import numbers import re import chardet try: from collections import OrderedDict except ImportError: OrderedDict = dict # sorry py2.6! Ordering isn't that important for our purposes anyway. # pdfminer from pdfm...
jcushman/pdfquery
pdfquery/pdfquery.py
prepare_for_json_encoding
python
def prepare_for_json_encoding(obj): """ Convert an arbitrary object into just JSON data types (list, dict, unicode str, int, bool, null). """ obj_type = type(obj) if obj_type == list or obj_type == tuple: return [prepare_for_json_encoding(item) for item in obj] if obj_type == dict...
Convert an arbitrary object into just JSON data types (list, dict, unicode str, int, bool, null).
train
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L148-L168
[ "def smart_unicode_decode(encoded_string):\n \"\"\"\n Given an encoded string of unknown format, detect the format with\n chardet and return the unicode version.\n Example input from bug #11:\n ('\\xfe\\xff\\x00I\\x00n\\x00s\\x00p\\x00e\\x00c\\x00t\\x00i\\x00o\\x00n\\x00'\n ...
from __future__ import print_function # -*- coding: utf-8 -*- # builtins import codecs import json import numbers import re import chardet try: from collections import OrderedDict except ImportError: OrderedDict = dict # sorry py2.6! Ordering isn't that important for our purposes anyway. # pdfminer from pdfm...
jcushman/pdfquery
pdfquery/pdfquery.py
obj_to_string
python
def obj_to_string(obj, top=True): """ Turn an arbitrary object into a unicode string. If complex (dict/list/tuple), will be json-encoded. """ obj = prepare_for_json_encoding(obj) if type(obj) == six.text_type: return obj return json.dumps(obj)
Turn an arbitrary object into a unicode string. If complex (dict/list/tuple), will be json-encoded.
train
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L170-L177
[ "def prepare_for_json_encoding(obj):\n \"\"\"\n Convert an arbitrary object into just JSON data types (list, dict, unicode str, int, bool, null).\n \"\"\"\n obj_type = type(obj)\n if obj_type == list or obj_type == tuple:\n return [prepare_for_json_encoding(item) for item in obj]\n if obj_t...
from __future__ import print_function # -*- coding: utf-8 -*- # builtins import codecs import json import numbers import re import chardet try: from collections import OrderedDict except ImportError: OrderedDict = dict # sorry py2.6! Ordering isn't that important for our purposes anyway. # pdfminer from pdfm...
jcushman/pdfquery
pdfquery/pdfquery.py
QPDFDocument.get_page_number
python
def get_page_number(self, index): """ Given an index, return page label as specified by catalog['PageLabels']['Nums'] In a PDF, page labels are stored as a list of pairs, like [starting_index, label_format, starting_index, label_format ...] For example: ...
Given an index, return page label as specified by catalog['PageLabels']['Nums'] In a PDF, page labels are stored as a list of pairs, like [starting_index, label_format, starting_index, label_format ...] For example: [0, {'S': 'D', 'St': 151}, 4, {'S':'R', 'P':'Foo'}] ...
train
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L188-L276
[ "def smart_unicode_decode(encoded_string):\n \"\"\"\n Given an encoded string of unknown format, detect the format with\n chardet and return the unicode version.\n Example input from bug #11:\n ('\\xfe\\xff\\x00I\\x00n\\x00s\\x00p\\x00e\\x00c\\x00t\\x00i\\x00o\\x00n\\x00'\n ...
class QPDFDocument(PDFDocument): def get_page_number(self, index): """ Given an index, return page label as specified by catalog['PageLabels']['Nums'] In a PDF, page labels are stored as a list of pairs, like [starting_index, label_format, starting_index, label_format ...] ...
jcushman/pdfquery
pdfquery/pdfquery.py
PDFQuery.load
python
def load(self, *page_numbers): """ Load etree and pyquery object for entire document, or given page numbers (ints or lists). After this is called, objects are available at pdf.tree and pdf.pq. >>> pdf.load() >>> pdf.tree <lxml.etree._ElementTree object at...
Load etree and pyquery object for entire document, or given page numbers (ints or lists). After this is called, objects are available at pdf.tree and pdf.pq. >>> pdf.load() >>> pdf.tree <lxml.etree._ElementTree object at ...> >>> pdf.pq('LTPage') [<LTPage...
train
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L370-L389
[ "def _flatten(l, ltypes=(list, tuple)):\n # via http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html\n ltype = type(l)\n l = list(l)\n i = 0\n while i < len(l):\n while isinstance(l[i], ltypes):\n if not l[i]:\n l.pop(i)\n i -= 1\n ...
class PDFQuery(object): def __init__( self, file, merge_tags=('LTChar', 'LTAnno'), round_floats=True, round_digits=3, input_text_formatter=None, normalize_spaces=True, resort=True, parse_tree_cacher=None, ...
jcushman/pdfquery
pdfquery/pdfquery.py
PDFQuery.extract
python
def extract(self, searches, tree=None, as_dict=True): """ >>> foo = pdf.extract([['pages', 'LTPage']]) >>> foo {'pages': [<LTPage>, <LTPage>]} >>> pdf.extract([['bar', ':in_bbox("100,100,400,400")']], foo['pages'][0]) {'bar': [<LTTextLineHorizont...
>>> foo = pdf.extract([['pages', 'LTPage']]) >>> foo {'pages': [<LTPage>, <LTPage>]} >>> pdf.extract([['bar', ':in_bbox("100,100,400,400")']], foo['pages'][0]) {'bar': [<LTTextLineHorizontal>, <LTTextBoxHorizontal>,...
train
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L391-L436
[ "def load(self, *page_numbers):\n \"\"\"\n Load etree and pyquery object for entire document, or given page\n numbers (ints or lists). After this is called, objects are\n available at pdf.tree and pdf.pq.\n\n >>> pdf.load()\n >>> pdf.tree\n <lxml.etree._ElementTree object at ...>\n >>> pdf.p...
class PDFQuery(object): def __init__( self, file, merge_tags=('LTChar', 'LTAnno'), round_floats=True, round_digits=3, input_text_formatter=None, normalize_spaces=True, resort=True, parse_tree_cacher=None, ...
jcushman/pdfquery
pdfquery/pdfquery.py
PDFQuery.get_pyquery
python
def get_pyquery(self, tree=None, page_numbers=None): """ Wrap given tree in pyquery and return. If no tree supplied, will generate one from given page_numbers, or all page numbers. """ if not page_numbers: page_numbers = [] if tree ...
Wrap given tree in pyquery and return. If no tree supplied, will generate one from given page_numbers, or all page numbers.
train
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L439-L454
[ "def get_tree(self, *page_numbers):\n \"\"\"\n Return lxml.etree.ElementTree for entire document, or page numbers\n given if any.\n \"\"\"\n cache_key = \"_\".join(map(str, _flatten(page_numbers)))\n tree = self._parse_tree_cacher.get(cache_key)\n if tree is None:\n # set up root...
class PDFQuery(object): def __init__( self, file, merge_tags=('LTChar', 'LTAnno'), round_floats=True, round_digits=3, input_text_formatter=None, normalize_spaces=True, resort=True, parse_tree_cacher=None, ...
jcushman/pdfquery
pdfquery/pdfquery.py
PDFQuery.get_tree
python
def get_tree(self, *page_numbers): """ Return lxml.etree.ElementTree for entire document, or page numbers given if any. """ cache_key = "_".join(map(str, _flatten(page_numbers))) tree = self._parse_tree_cacher.get(cache_key) if tree is None: ...
Return lxml.etree.ElementTree for entire document, or page numbers given if any.
train
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L456-L501
[ "def _flatten(l, ltypes=(list, tuple)):\n # via http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html\n ltype = type(l)\n l = list(l)\n i = 0\n while i < len(l):\n while isinstance(l[i], ltypes):\n if not l[i]:\n l.pop(i)\n i -= 1\n ...
class PDFQuery(object): def __init__( self, file, merge_tags=('LTChar', 'LTAnno'), round_floats=True, round_digits=3, input_text_formatter=None, normalize_spaces=True, resort=True, parse_tree_cacher=None, ...
jcushman/pdfquery
pdfquery/pdfquery.py
PDFQuery._clean_text
python
def _clean_text(self, branch): """ Remove text from node if same text exists in its children. Apply string formatter if set. """ if branch.text and self.input_text_formatter: branch.text = self.input_text_formatter(branch.text) try: ...
Remove text from node if same text exists in its children. Apply string formatter if set.
train
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L503-L516
[ "def _clean_text(self, branch):\n \"\"\"\n Remove text from node if same text exists in its children.\n Apply string formatter if set.\n \"\"\"\n if branch.text and self.input_text_formatter:\n branch.text = self.input_text_formatter(branch.text)\n try:\n for child in branch:...
class PDFQuery(object): def __init__( self, file, merge_tags=('LTChar', 'LTAnno'), round_floats=True, round_digits=3, input_text_formatter=None, normalize_spaces=True, resort=True, parse_tree_cacher=None, ...
jcushman/pdfquery
pdfquery/pdfquery.py
PDFQuery._getattrs
python
def _getattrs(self, obj, *attrs): """ Return dictionary of given attrs on given object, if they exist, processing through _filter_value(). """ filtered_attrs = {} for attr in attrs: if hasattr(obj, attr): filtered_attrs[attr] = obj_to_string( ...
Return dictionary of given attrs on given object, if they exist, processing through _filter_value().
train
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L575-L585
null
class PDFQuery(object): def __init__( self, file, merge_tags=('LTChar', 'LTAnno'), round_floats=True, round_digits=3, input_text_formatter=None, normalize_spaces=True, resort=True, parse_tree_cacher=None, ...
jcushman/pdfquery
pdfquery/pdfquery.py
PDFQuery.get_layout
python
def get_layout(self, page): """ Get PDFMiner Layout object for given page object or page number. """ if type(page) == int: page = self.get_page(page) self.interpreter.process_page(page) layout = self.device.get_result() layout = self._add_annots(layout, page.ann...
Get PDFMiner Layout object for given page object or page number.
train
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L600-L607
[ "def get_page(self, page_number):\n \"\"\" Get PDFPage object -- 0-indexed.\"\"\"\n return self._cached_pages(target_page=page_number)\n", "def _add_annots(self, layout, annots):\n \"\"\"Adds annotations to the layout object\n \"\"\"\n if annots:\n for annot in resolve1(annots):\n ...
class PDFQuery(object): def __init__( self, file, merge_tags=('LTChar', 'LTAnno'), round_floats=True, round_digits=3, input_text_formatter=None, normalize_spaces=True, resort=True, parse_tree_cacher=None, ...
jcushman/pdfquery
pdfquery/pdfquery.py
PDFQuery._cached_pages
python
def _cached_pages(self, target_page=-1): """ Get a page or all pages from page generator, caching results. This is necessary because PDFMiner searches recursively for pages, so we won't know how many there are until we parse the whole document, which we don't want to do unti...
Get a page or all pages from page generator, caching results. This is necessary because PDFMiner searches recursively for pages, so we won't know how many there are until we parse the whole document, which we don't want to do until we need to.
train
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L613-L640
null
class PDFQuery(object): def __init__( self, file, merge_tags=('LTChar', 'LTAnno'), round_floats=True, round_digits=3, input_text_formatter=None, normalize_spaces=True, resort=True, parse_tree_cacher=None, ...
jcushman/pdfquery
pdfquery/pdfquery.py
PDFQuery._add_annots
python
def _add_annots(self, layout, annots): """Adds annotations to the layout object """ if annots: for annot in resolve1(annots): annot = resolve1(annot) if annot.get('Rect') is not None: annot['bbox'] = annot.pop('Rect') # Rena...
Adds annotations to the layout object
train
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L642-L660
[ "def obj_to_string(obj, top=True):\n \"\"\"\n Turn an arbitrary object into a unicode string. If complex (dict/list/tuple), will be json-encoded.\n \"\"\"\n obj = prepare_for_json_encoding(obj)\n if type(obj) == six.text_type:\n return obj\n return json.dumps(obj)\n", "def _set_hwxy_attrs...
class PDFQuery(object): def __init__( self, file, merge_tags=('LTChar', 'LTAnno'), round_floats=True, round_digits=3, input_text_formatter=None, normalize_spaces=True, resort=True, parse_tree_cacher=None, ...
jcushman/pdfquery
pdfquery/pdfquery.py
PDFQuery._set_hwxy_attrs
python
def _set_hwxy_attrs(attr): """Using the bbox attribute, set the h, w, x0, x1, y0, and y1 attributes. """ bbox = attr['bbox'] attr['x0'] = bbox[0] attr['x1'] = bbox[2] attr['y0'] = bbox[1] attr['y1'] = bbox[3] attr['height'] = attr['y1'] - ...
Using the bbox attribute, set the h, w, x0, x1, y0, and y1 attributes.
train
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L663-L674
null
class PDFQuery(object): def __init__( self, file, merge_tags=('LTChar', 'LTAnno'), round_floats=True, round_digits=3, input_text_formatter=None, normalize_spaces=True, resort=True, parse_tree_cacher=None, ...
frictionlessdata/tableschema-py
tableschema/schema.py
Schema.primary_key
python
def primary_key(self): primary_key = self.__current_descriptor.get('primaryKey', []) if not isinstance(primary_key, list): primary_key = [primary_key] return primary_key
https://github.com/frictionlessdata/tableschema-py#schema
train
https://github.com/frictionlessdata/tableschema-py/blob/9c5fa930319e7c5b10351f794091c5f9de5e8684/tableschema/schema.py#L63-L69
null
class Schema(object): # Public def __init__(self, descriptor={}, strict=False): """https://github.com/frictionlessdata/tableschema-py#schema """ # Process descriptor descriptor = helpers.retrieve_descriptor(descriptor) # Set attributes self.__strict = strict ...
frictionlessdata/tableschema-py
tableschema/schema.py
Schema.foreign_keys
python
def foreign_keys(self): foreign_keys = self.__current_descriptor.get('foreignKeys', []) for key in foreign_keys: key.setdefault('fields', []) key.setdefault('reference', {}) key['reference'].setdefault('resource', '') key['reference'].setdefault('fields', ...
https://github.com/frictionlessdata/tableschema-py#schema
train
https://github.com/frictionlessdata/tableschema-py/blob/9c5fa930319e7c5b10351f794091c5f9de5e8684/tableschema/schema.py#L72-L85
null
class Schema(object): # Public def __init__(self, descriptor={}, strict=False): """https://github.com/frictionlessdata/tableschema-py#schema """ # Process descriptor descriptor = helpers.retrieve_descriptor(descriptor) # Set attributes self.__strict = strict ...
frictionlessdata/tableschema-py
tableschema/schema.py
Schema.add_field
python
def add_field(self, descriptor): self.__current_descriptor.setdefault('fields', []) self.__current_descriptor['fields'].append(descriptor) self.__build() return self.__fields[-1]
https://github.com/frictionlessdata/tableschema-py#schema
train
https://github.com/frictionlessdata/tableschema-py/blob/9c5fa930319e7c5b10351f794091c5f9de5e8684/tableschema/schema.py#L107-L113
[ "def __build(self):\n\n # Process descriptor\n expand = helpers.expand_schema_descriptor\n self.__current_descriptor = expand(self.__current_descriptor)\n self.__next_descriptor = deepcopy(self.__current_descriptor)\n\n # Validate descriptor\n try:\n self.__profile.validate(self.__current_d...
class Schema(object): # Public def __init__(self, descriptor={}, strict=False): """https://github.com/frictionlessdata/tableschema-py#schema """ # Process descriptor descriptor = helpers.retrieve_descriptor(descriptor) # Set attributes self.__strict = strict ...
frictionlessdata/tableschema-py
tableschema/schema.py
Schema.update_field
python
def update_field(self, name, update): for field in self.__next_descriptor['fields']: if field['name'] == name: field.update(update) return True return False
https://github.com/frictionlessdata/tableschema-py#schema
train
https://github.com/frictionlessdata/tableschema-py/blob/9c5fa930319e7c5b10351f794091c5f9de5e8684/tableschema/schema.py#L115-L122
null
class Schema(object): # Public def __init__(self, descriptor={}, strict=False): """https://github.com/frictionlessdata/tableschema-py#schema """ # Process descriptor descriptor = helpers.retrieve_descriptor(descriptor) # Set attributes self.__strict = strict ...
frictionlessdata/tableschema-py
tableschema/schema.py
Schema.remove_field
python
def remove_field(self, name): field = self.get_field(name) if field: predicat = lambda field: field.get('name') != name self.__current_descriptor['fields'] = filter( predicat, self.__current_descriptor['fields']) self.__build() return field
https://github.com/frictionlessdata/tableschema-py#schema
train
https://github.com/frictionlessdata/tableschema-py/blob/9c5fa930319e7c5b10351f794091c5f9de5e8684/tableschema/schema.py#L124-L133
[ "def get_field(self, name):\n \"\"\"https://github.com/frictionlessdata/tableschema-py#schema\n \"\"\"\n for field in self.fields:\n if field.name == name:\n return field\n return None\n", "def __build(self):\n\n # Process descriptor\n expand = helpers.expand_schema_descriptor\...
class Schema(object): # Public def __init__(self, descriptor={}, strict=False): """https://github.com/frictionlessdata/tableschema-py#schema """ # Process descriptor descriptor = helpers.retrieve_descriptor(descriptor) # Set attributes self.__strict = strict ...
frictionlessdata/tableschema-py
tableschema/schema.py
Schema.cast_row
python
def cast_row(self, row, fail_fast=False): # Prepare result = [] errors = [] # Check row length if len(row) != len(self.fields): message = 'Row length %s doesn\'t match fields count %s' message = message % (len(row), len(self.fields)) raise ex...
https://github.com/frictionlessdata/tableschema-py#schema
train
https://github.com/frictionlessdata/tableschema-py/blob/9c5fa930319e7c5b10351f794091c5f9de5e8684/tableschema/schema.py#L135-L163
null
class Schema(object): # Public def __init__(self, descriptor={}, strict=False): """https://github.com/frictionlessdata/tableschema-py#schema """ # Process descriptor descriptor = helpers.retrieve_descriptor(descriptor) # Set attributes self.__strict = strict ...
frictionlessdata/tableschema-py
tableschema/schema.py
Schema.infer
python
def infer(self, rows, headers=1, confidence=0.75): # Get headers if isinstance(headers, int): headers_row = headers while True: headers_row -= 1 headers = rows.pop(0) if not headers_row: break elif not i...
https://github.com/frictionlessdata/tableschema-py#schema
train
https://github.com/frictionlessdata/tableschema-py/blob/9c5fa930319e7c5b10351f794091c5f9de5e8684/tableschema/schema.py#L165-L213
[ "def __build(self):\n\n # Process descriptor\n expand = helpers.expand_schema_descriptor\n self.__current_descriptor = expand(self.__current_descriptor)\n self.__next_descriptor = deepcopy(self.__current_descriptor)\n\n # Validate descriptor\n try:\n self.__profile.validate(self.__current_d...
class Schema(object): # Public def __init__(self, descriptor={}, strict=False): """https://github.com/frictionlessdata/tableschema-py#schema """ # Process descriptor descriptor = helpers.retrieve_descriptor(descriptor) # Set attributes self.__strict = strict ...
frictionlessdata/tableschema-py
tableschema/schema.py
Schema.save
python
def save(self, target, ensure_ascii=True): mode = 'w' encoding = 'utf-8' if six.PY2: mode = 'wb' encoding = None helpers.ensure_dir(target) with io.open(target, mode=mode, encoding=encoding) as file: json.dump(self.__current_descriptor, file, i...
https://github.com/frictionlessdata/tableschema-py#schema
train
https://github.com/frictionlessdata/tableschema-py/blob/9c5fa930319e7c5b10351f794091c5f9de5e8684/tableschema/schema.py#L226-L236
[ "def ensure_dir(path):\n \"\"\"Ensure directory exists.\n\n Args:\n path(str): dir path\n\n \"\"\"\n dirpath = os.path.dirname(path)\n if dirpath and not os.path.exists(dirpath):\n os.makedirs(dirpath)\n" ]
class Schema(object): # Public def __init__(self, descriptor={}, strict=False): """https://github.com/frictionlessdata/tableschema-py#schema """ # Process descriptor descriptor = helpers.retrieve_descriptor(descriptor) # Set attributes self.__strict = strict ...
frictionlessdata/tableschema-py
tableschema/helpers.py
ensure_dir
python
def ensure_dir(path): dirpath = os.path.dirname(path) if dirpath and not os.path.exists(dirpath): os.makedirs(dirpath)
Ensure directory exists. Args: path(str): dir path
train
https://github.com/frictionlessdata/tableschema-py/blob/9c5fa930319e7c5b10351f794091c5f9de5e8684/tableschema/helpers.py#L67-L76
null
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os import io import sys import six import json import requests from copy import deepcopy from importlib import import_module from . import ...
frictionlessdata/tableschema-py
tableschema/helpers.py
normalize_value
python
def normalize_value(value): cast = str if six.PY2: cast = unicode # noqa return cast(value).lower()
Convert value to string and make it lower cased.
train
https://github.com/frictionlessdata/tableschema-py/blob/9c5fa930319e7c5b10351f794091c5f9de5e8684/tableschema/helpers.py#L79-L85
null
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os import io import sys import six import json import requests from copy import deepcopy from importlib import import_module from . import ...
frictionlessdata/tableschema-py
tableschema/field.py
Field.cast_value
python
def cast_value(self, value, constraints=True): # Null value if value in self.__missing_values: value = None # Cast value cast_value = value if value is not None: cast_value = self.__cast_function(value) if cast_value == config.ERROR: ...
https://github.com/frictionlessdata/tableschema-py#field
train
https://github.com/frictionlessdata/tableschema-py/blob/9c5fa930319e7c5b10351f794091c5f9de5e8684/tableschema/field.py#L71-L102
null
class Field(object): """Table Schema field representation. """ # Public def __init__(self, descriptor, missing_values=config.DEFAULT_MISSING_VALUES): # Process descriptor descriptor = helpers.expand_field_descriptor(descriptor) # Set attributes self.__descriptor = des...
frictionlessdata/tableschema-py
tableschema/table.py
Table.iter
python
def iter(self, keyed=False, extended=False, cast=True, relations=False): # Prepare unique checks if cast: unique_fields_cache = {} if self.schema: unique_fields_cache = _create_unique_fields_cache(self.schema) # Open/iterate stream self.__stream....
https://github.com/frictionlessdata/tableschema-py#schema
train
https://github.com/frictionlessdata/tableschema-py/blob/9c5fa930319e7c5b10351f794091c5f9de5e8684/tableschema/table.py#L68-L128
[ "def _create_unique_fields_cache(schema):\n primary_key_indexes = []\n cache = {}\n\n # Unique\n for index, field in enumerate(schema.fields):\n if field.name in schema.primary_key:\n primary_key_indexes.append(index)\n if field.constraints.get('unique'):\n cache[tupl...
class Table(object): # Public def __init__(self, source, schema=None, strict=False, post_cast=[], storage=None, **options): """https://github.com/frictionlessdata/tableschema-py#schema """ # Set attributes self.__source = source self.__stream = None ...
frictionlessdata/tableschema-py
tableschema/table.py
Table.read
python
def read(self, keyed=False, extended=False, cast=True, relations=False, limit=None): result = [] rows = self.iter(keyed=keyed, extended=extended, cast=cast, relations=relations) for count, row in enumerate(rows, start=1): result.append(row) if count == limit: ...
https://github.com/frictionlessdata/tableschema-py#schema
train
https://github.com/frictionlessdata/tableschema-py/blob/9c5fa930319e7c5b10351f794091c5f9de5e8684/tableschema/table.py#L130-L139
[ "def iter(self, keyed=False, extended=False, cast=True, relations=False):\n \"\"\"https://github.com/frictionlessdata/tableschema-py#schema\n \"\"\"\n\n # Prepare unique checks\n if cast:\n unique_fields_cache = {}\n if self.schema:\n unique_fields_cache = _create_unique_fields_...
class Table(object): # Public def __init__(self, source, schema=None, strict=False, post_cast=[], storage=None, **options): """https://github.com/frictionlessdata/tableschema-py#schema """ # Set attributes self.__source = source self.__stream = None ...
frictionlessdata/tableschema-py
tableschema/table.py
Table.infer
python
def infer(self, limit=100, confidence=0.75): if self.__schema is None or self.__headers is None: # Infer (tabulator) if not self.__storage: with self.__stream as stream: if self.__schema is None: self.__schema = Schema() ...
https://github.com/frictionlessdata/tableschema-py#schema
train
https://github.com/frictionlessdata/tableschema-py/blob/9c5fa930319e7c5b10351f794091c5f9de5e8684/tableschema/table.py#L141-L165
[ "def infer(self, rows, headers=1, confidence=0.75):\n \"\"\"https://github.com/frictionlessdata/tableschema-py#schema\n \"\"\"\n\n # Get headers\n if isinstance(headers, int):\n headers_row = headers\n while True:\n headers_row -= 1\n headers = rows.pop(0)\n ...
class Table(object): # Public def __init__(self, source, schema=None, strict=False, post_cast=[], storage=None, **options): """https://github.com/frictionlessdata/tableschema-py#schema """ # Set attributes self.__source = source self.__stream = None ...
frictionlessdata/tableschema-py
tableschema/table.py
Table.save
python
def save(self, target, storage=None, **options): # Save (tabulator) if storage is None: with Stream(self.iter, headers=self.__schema.headers) as stream: stream.save(target, **options) return True # Save (storage) else: if not isinstan...
https://github.com/frictionlessdata/tableschema-py#schema
train
https://github.com/frictionlessdata/tableschema-py/blob/9c5fa930319e7c5b10351f794091c5f9de5e8684/tableschema/table.py#L167-L183
[ "def iter(self, keyed=False, extended=False, cast=True, relations=False):\n \"\"\"https://github.com/frictionlessdata/tableschema-py#schema\n \"\"\"\n\n # Prepare unique checks\n if cast:\n unique_fields_cache = {}\n if self.schema:\n unique_fields_cache = _create_unique_fields_...
class Table(object): # Public def __init__(self, source, schema=None, strict=False, post_cast=[], storage=None, **options): """https://github.com/frictionlessdata/tableschema-py#schema """ # Set attributes self.__source = source self.__stream = None ...
frictionlessdata/tableschema-py
tableschema/cli.py
infer
python
def infer(data, row_limit, confidence, encoding, to_file): descriptor = tableschema.infer(data, encoding=encoding, limit=row_limit, confidence=confidence) if to_file: with io.open(to_file, mode='w+t'...
Infer a schema from data. * data must be a local filepath * data must be CSV * the file encoding is assumed to be UTF-8 unless an encoding is passed with --encoding * the first line of data must be headers * these constraints are just for the CLI
train
https://github.com/frictionlessdata/tableschema-py/blob/9c5fa930319e7c5b10351f794091c5f9de5e8684/tableschema/cli.py#L36-L53
[ "def infer(source, headers=1, limit=100, confidence=0.75, **options):\n \"\"\"https://github.com/frictionlessdata/tableschema-py#schema\n \"\"\"\n\n # Deprecated arguments order\n is_string = lambda value: isinstance(value, six.string_types)\n if isinstance(source, list) and all(map(is_string, source...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import io import sys import json import click import tableschema DIR = os.path.abspath(os.path.dirname(__file__)) VERSION_FILE = os.path.join(os.path.dirname(__file__), 'VERS...
frictionlessdata/tableschema-py
tableschema/cli.py
validate
python
def validate(schema): try: tableschema.validate(schema) click.echo("Schema is valid") sys.exit(0) except tableschema.exceptions.ValidationError as exception: click.echo("Schema is not valid") click.echo(exception.errors) sys.exit(1)
Validate that a supposed schema is in fact a Table Schema.
train
https://github.com/frictionlessdata/tableschema-py/blob/9c5fa930319e7c5b10351f794091c5f9de5e8684/tableschema/cli.py#L58-L67
[ "def validate(descriptor):\n \"\"\"https://github.com/frictionlessdata/tableschema-py#schema\n \"\"\"\n Schema(descriptor, strict=True)\n return True\n" ]
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import io import sys import json import click import tableschema DIR = os.path.abspath(os.path.dirname(__file__)) VERSION_FILE = os.path.join(os.path.dirname(__file__), 'VERS...
frictionlessdata/tableschema-py
tableschema/infer.py
infer
python
def infer(source, headers=1, limit=100, confidence=0.75, **options): # Deprecated arguments order is_string = lambda value: isinstance(value, six.string_types) if isinstance(source, list) and all(map(is_string, source)): warnings.warn('Correct arguments order infer(source, headers)', UserWarning) ...
https://github.com/frictionlessdata/tableschema-py#schema
train
https://github.com/frictionlessdata/tableschema-py/blob/9c5fa930319e7c5b10351f794091c5f9de5e8684/tableschema/infer.py#L14-L26
[ "def infer(self, limit=100, confidence=0.75):\n \"\"\"https://github.com/frictionlessdata/tableschema-py#schema\n \"\"\"\n if self.__schema is None or self.__headers is None:\n\n # Infer (tabulator)\n if not self.__storage:\n with self.__stream as stream:\n if self._...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import six import warnings from .table import Table # Module API
tmbo/questionary
questionary/utils.py
default_values_of
python
def default_values_of(func): signature = inspect.signature(func) return [k for k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty or v.kind != inspect.Parameter.POSITIONAL_OR_KEYWORD]
Return the defaults of the function `func`.
train
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/utils.py#L7-L14
null
# -*- coding: utf-8 -*- import inspect ACTIVATED_ASYNC_MODE = False def arguments_of(func): """Return the parameters of the function `func`.""" return list(inspect.signature(func).parameters.keys()) def required_arguments(func): """Return all arguments of a function that do not have a default value."...
tmbo/questionary
questionary/utils.py
required_arguments
python
def required_arguments(func): defaults = default_values_of(func) args = arguments_of(func) if defaults: args = args[:-len(defaults)] return args
Return all arguments of a function that do not have a default value.
train
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/utils.py#L23-L30
[ "def default_values_of(func):\n \"\"\"Return the defaults of the function `func`.\"\"\"\n\n signature = inspect.signature(func)\n return [k\n for k, v in signature.parameters.items()\n if v.default is not inspect.Parameter.empty or\n v.kind != inspect.Parameter.POSITIONAL_O...
# -*- coding: utf-8 -*- import inspect ACTIVATED_ASYNC_MODE = False def default_values_of(func): """Return the defaults of the function `func`.""" signature = inspect.signature(func) return [k for k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty or...
tmbo/questionary
questionary/prompts/text.py
text
python
def text(message: Text, default: Text = "", validate: Union[Type[Validator], Callable[[Text], bool], None] = None, # noqa qmark: Text = DEFAULT_QUESTION_PREFIX, style: Optional[Style] = None, **kwargs: Any) -> Question: ...
Prompt the user to enter a free text message. This question type can be used to prompt the user for some text input. Args: message: Question text default: Default value will be returned if the user just hits enter. validate: Require the entered valu...
train
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/prompts/text.py#L15-L65
[ "def build_validator(validate: Any) -> Optional[Validator]:\n if validate:\n if inspect.isclass(validate) and issubclass(validate, Validator):\n return validate()\n elif callable(validate):\n class _InputValidator(Validator):\n def validate(self, document):\n ...
# -*- coding: utf-8 -*- from prompt_toolkit.document import Document from prompt_toolkit.shortcuts.prompt import ( PromptSession) from prompt_toolkit.styles import merge_styles, Style from prompt_toolkit.validation import Validator from typing import Text, Type, Union, Callable, Optional, Any from questionary.con...
tmbo/questionary
questionary/question.py
Question.ask_async
python
async def ask_async(self, patch_stdout: bool = False, kbi_msg: str = DEFAULT_KBI_MESSAGE) -> Any: if self.should_skip_question: return self.default try: sys.stdout.flush() return await self.unsafe_ask_async(patch_stdou...
Ask the question using asyncio and return user response.
train
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/question.py#L21-L34
[ "async def unsafe_ask_async(self, patch_stdout: bool = False) -> Any:\n \"\"\"Ask the question using asyncio and return user response.\n\n Does not catch keyboard interrupts.\"\"\"\n\n if not utils.ACTIVATED_ASYNC_MODE:\n await utils.activate_prompt_toolkit_async_mode()\n\n if patch_stdout:\n ...
class Question: """A question to be prompted. This is an internal class. Questions should be created using the predefined questions (e.g. text or password).""" def __init__(self, application: prompt_toolkit.Application): self.application = application self.should_skip_question = False ...
tmbo/questionary
questionary/question.py
Question.ask
python
def ask(self, patch_stdout: bool = False, kbi_msg: str = DEFAULT_KBI_MESSAGE) -> Any: if self.should_skip_question: return self.default try: return self.unsafe_ask(patch_stdout) except KeyboardInterrupt: print("\n{}\n".format(kbi_msg)...
Ask the question synchronously and return user response.
train
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/question.py#L36-L48
[ "def unsafe_ask(self, patch_stdout: bool = False) -> Any:\n \"\"\"Ask the question synchronously and return user response.\n\n Does not catch keyboard interrupts.\"\"\"\n\n if patch_stdout:\n with prompt_toolkit.patch_stdout.patch_stdout():\n return self.application.run()\n else:\n ...
class Question: """A question to be prompted. This is an internal class. Questions should be created using the predefined questions (e.g. text or password).""" def __init__(self, application: prompt_toolkit.Application): self.application = application self.should_skip_question = False ...
tmbo/questionary
questionary/question.py
Question.unsafe_ask
python
def unsafe_ask(self, patch_stdout: bool = False) -> Any: if patch_stdout: with prompt_toolkit.patch_stdout.patch_stdout(): return self.application.run() else: return self.application.run()
Ask the question synchronously and return user response. Does not catch keyboard interrupts.
train
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/question.py#L50-L59
null
class Question: """A question to be prompted. This is an internal class. Questions should be created using the predefined questions (e.g. text or password).""" def __init__(self, application: prompt_toolkit.Application): self.application = application self.should_skip_question = False ...
tmbo/questionary
questionary/question.py
Question.skip_if
python
def skip_if(self, condition: bool, default: Any = None) -> 'Question': self.should_skip_question = condition self.default = default return self
Skip the question if flag is set and return the default instead.
train
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/question.py#L61-L66
null
class Question: """A question to be prompted. This is an internal class. Questions should be created using the predefined questions (e.g. text or password).""" def __init__(self, application: prompt_toolkit.Application): self.application = application self.should_skip_question = False ...
tmbo/questionary
questionary/question.py
Question.unsafe_ask_async
python
async def unsafe_ask_async(self, patch_stdout: bool = False) -> Any: if not utils.ACTIVATED_ASYNC_MODE: await utils.activate_prompt_toolkit_async_mode() if patch_stdout: # with prompt_toolkit.patch_stdout.patch_stdout(): return await self.application.run_async().to_...
Ask the question using asyncio and return user response. Does not catch keyboard interrupts.
train
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/question.py#L68-L80
[ "async def activate_prompt_toolkit_async_mode():\n \"\"\"Configure prompt toolkit to use the asyncio event loop.\n\n Needs to be async, so we use the right event loop in py 3.5\"\"\"\n from prompt_toolkit.eventloop import use_asyncio_event_loop\n\n global ACTIVATED_ASYNC_MODE\n\n # Tell prompt_toolki...
class Question: """A question to be prompted. This is an internal class. Questions should be created using the predefined questions (e.g. text or password).""" def __init__(self, application: prompt_toolkit.Application): self.application = application self.should_skip_question = False ...
tmbo/questionary
questionary/prompts/common.py
_fix_unecessary_blank_lines
python
def _fix_unecessary_blank_lines(ps: PromptSession) -> None: default_container = ps.layout.container default_buffer_window = \ default_container.get_children()[0].content.get_children()[1].content assert isinstance(default_buffer_window, Window) # this forces the main window to stay as small a...
This is a fix for additional empty lines added by prompt toolkit. This assumes the layout of the default session doesn't change, if it does, this needs an update.
train
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/prompts/common.py#L269-L283
null
# -*- coding: utf-8 -*- import inspect from prompt_toolkit import PromptSession from prompt_toolkit.filters import IsDone, Always from prompt_toolkit.layout import ( FormattedTextControl, Layout, HSplit, ConditionalContainer, Window) from prompt_toolkit.validation import Validator, ValidationError from typing i...
tmbo/questionary
questionary/prompts/common.py
create_inquirer_layout
python
def create_inquirer_layout( ic: InquirerControl, get_prompt_tokens: Callable[[], List[Tuple[Text, Text]]], **kwargs) -> Layout: ps = PromptSession(get_prompt_tokens, reserve_space_for_menu=0, **kwargs) _fix_unecessary_blank_lines(ps) return Layout(HSplit([ ps.layout.contai...
Create a layout combining question and inquirer selection.
train
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/prompts/common.py#L286-L302
[ "def _fix_unecessary_blank_lines(ps: PromptSession) -> None:\n \"\"\"This is a fix for additional empty lines added by prompt toolkit.\n\n This assumes the layout of the default session doesn't change, if it\n does, this needs an update.\"\"\"\n\n default_container = ps.layout.container\n\n default_b...
# -*- coding: utf-8 -*- import inspect from prompt_toolkit import PromptSession from prompt_toolkit.filters import IsDone, Always from prompt_toolkit.layout import ( FormattedTextControl, Layout, HSplit, ConditionalContainer, Window) from prompt_toolkit.validation import Validator, ValidationError from typing i...
tmbo/questionary
questionary/prompts/common.py
Choice.build
python
def build(c: Union[Text, 'Choice', Dict[Text, Any]]) -> 'Choice': if isinstance(c, Choice): return c elif isinstance(c, str): return Choice(c, c) else: return Choice(c.get('name'), c.get('value'), c.get('dis...
Create a choice object from different representations.
train
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/prompts/common.py#L52-L64
null
class Choice(object): """One choice in a select, rawselect or checkbox.""" def __init__(self, title: Text, value: Optional[Any] = None, disabled: Optional[Text] = None, checked: bool = False, shortcut_key: Optional[Text] = Non...
tmbo/questionary
questionary/prompts/password.py
password
python
def password(message: Text, default: Text = "", validate: Union[Type[Validator], Callable[[Text], bool], None] = None, # noqa qmark: Text = DEFAULT_QUESTION_PREFIX, style: Optional[Style] = None, ...
Question the user to enter a secret text not displayed in the prompt. This question type can be used to prompt the user for information that should not be shown in the command line. The typed text will be replaced with `*`. Args: message: Question text default: Defau...
train
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/prompts/password.py#L12-L51
[ "def text(message: Text,\n default: Text = \"\",\n validate: Union[Type[Validator],\n Callable[[Text], bool],\n None] = None, # noqa\n qmark: Text = DEFAULT_QUESTION_PREFIX,\n style: Optional[Style] = None,\n **kwargs: Any) -> ...
# -*- coding: utf-8 -*- from typing import Text, Type, Union, Callable, Optional, Any from prompt_toolkit.styles import Style from prompt_toolkit.validation import Validator from questionary.question import Question from questionary.constants import DEFAULT_QUESTION_PREFIX from questionary.prompts import text
tmbo/questionary
questionary/prompts/select.py
select
python
def select(message: Text, choices: List[Union[Text, Choice, Dict[Text, Any]]], default: Optional[Text] = None, qmark: Text = DEFAULT_QUESTION_PREFIX, style: Optional[Style] = None, use_shortcuts: bool = False, use_indicator: bool = False, **kw...
Prompt the user to select one item from the list of choices. The user can only select one option. Args: message: Question text choices: Items shown in the selection, this can contain `Choice` or or `Separator` objects or simple items as strings. Passing `Choi...
train
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/prompts/select.py#L25-L149
[ "def create_inquirer_layout(\n ic: InquirerControl,\n get_prompt_tokens: Callable[[], List[Tuple[Text, Text]]],\n **kwargs) -> Layout:\n \"\"\"Create a layout combining question and inquirer selection.\"\"\"\n\n ps = PromptSession(get_prompt_tokens, reserve_space_for_menu=0, **kwargs)\n\n...
# -*- coding: utf-8 -*- import time from questionary.prompts import common from typing import Any, Optional, Text, List, Union, Dict from prompt_toolkit.application import Application from prompt_toolkit.filters import IsDone, Never, Always from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.keys i...
tmbo/questionary
questionary/form.py
form
python
def form(**kwargs: Question): return Form(*(FormField(k, q) for k, q in kwargs.items()))
Create a form with multiple questions. The parameter name of a question will be the key for the answer in the returned dict.
train
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/form.py#L9-L14
null
from collections import namedtuple from questionary.constants import DEFAULT_KBI_MESSAGE from questionary.question import Question FormField = namedtuple("FormField", ["key", "question"]) class Form: """Multi question prompts. Questions are asked one after another. All the answers are returned as a dict w...
tmbo/questionary
questionary/prompt.py
prompt
python
def prompt(questions: List[Dict[Text, Any]], answers: Optional[Dict[Text, Any]] = None, patch_stdout: bool = False, true_color: bool = False, kbi_msg: Text = DEFAULT_KBI_MESSAGE, **kwargs): if isinstance(questions, dict): questions = [questions] a...
Prompt the user for input on all the questions.
train
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/prompt.py#L18-L104
[ "def prompt_by_name(name):\n return AVAILABLE_PROMPTS.get(name)\n", "def missing_arguments(func, argdict):\n \"\"\"Return all arguments that are missing to call func.\"\"\"\n return set(required_arguments(func)) - set(argdict.keys())\n" ]
# -*- coding: utf-8 -*- from prompt_toolkit.output import ColorDepth from typing import Any, Text, Dict, Optional, List from questionary import utils from questionary.constants import DEFAULT_KBI_MESSAGE from questionary.prompts import AVAILABLE_PROMPTS, prompt_by_name class PromptParameterException(ValueError): ...
tmbo/questionary
questionary/prompts/confirm.py
confirm
python
def confirm(message: Text, default: bool = True, qmark: Text = DEFAULT_QUESTION_PREFIX, style: Optional[Style] = None, **kwargs: Any) -> Question: merged_style = merge_styles([DEFAULT_STYLE, style]) status = {'answer': None} def get_prompt_tokens(): ...
Prompt the user to confirm or reject. This question type can be used to prompt the user for a confirmation of a yes-or-no question. If the user just hits enter, the default value will be returned. Args: message: Question text default: Default value will be returned i...
train
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/prompts/confirm.py#L16-L94
null
# -*- coding: utf-8 -*- from prompt_toolkit import PromptSession from prompt_toolkit.formatted_text import ( to_formatted_text) from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.keys import Keys from prompt_toolkit.styles import merge_styles, Style from typing import Optional, Text, Any from q...
tmbo/questionary
questionary/prompts/rawselect.py
rawselect
python
def rawselect(message: Text, choices: List[Union[Text, Choice, Dict[Text, Any]]], default: Optional[Text] = None, qmark: Text = DEFAULT_QUESTION_PREFIX, style: Optional[Style] = None, **kwargs: Any) -> Question: return select.select(message, choi...
Ask the user to select one item from a list of choices using shortcuts. The user can only select one option. Args: message: Question text choices: Items shown in the selection, this can contain `Choice` or or `Separator` objects or simple items as strings. Pass...
train
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/prompts/rawselect.py#L12-L43
[ "def select(message: Text,\n choices: List[Union[Text, Choice, Dict[Text, Any]]],\n default: Optional[Text] = None,\n qmark: Text = DEFAULT_QUESTION_PREFIX,\n style: Optional[Style] = None,\n use_shortcuts: bool = False,\n use_indicator: bool = False,\n ...
# -*- coding: utf-8 -*- from typing import Text, List, Optional, Any, Union, Dict from prompt_toolkit.styles import Style from questionary.constants import DEFAULT_QUESTION_PREFIX from questionary.prompts import select from questionary.prompts.common import Choice from questionary.question import Question
tmbo/questionary
questionary/prompts/checkbox.py
checkbox
python
def checkbox(message: Text, choices: List[Union[Text, Choice, Dict[Text, Any]]], default: Optional[Text] = None, qmark: Text = DEFAULT_QUESTION_PREFIX, style: Optional[Style] = None, **kwargs: Any) -> Question: merged_style = merge_styles([DEFAULT_ST...
Ask the user to select from a list of items. This is a multiselect, the user can choose one, none or many of the items. Args: message: Question text choices: Items shown in the selection, this can contain `Choice` or or `Separator` objects or simple items as strings. Pass...
train
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/prompts/checkbox.py#L23-L150
[ "def create_inquirer_layout(\n ic: InquirerControl,\n get_prompt_tokens: Callable[[], List[Tuple[Text, Text]]],\n **kwargs) -> Layout:\n \"\"\"Create a layout combining question and inquirer selection.\"\"\"\n\n ps = PromptSession(get_prompt_tokens, reserve_space_for_menu=0, **kwargs)\n\n...
# -*- coding: utf-8 -*- from prompt_toolkit.application import Application from prompt_toolkit.filters import IsDone from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.keys import Keys from prompt_toolkit.layout import Layout from prompt_toolkit.layout.containers import ( ConditionalContainer, ...
box/flaky
flaky/flaky_decorator.py
flaky
python
def flaky(max_runs=None, min_passes=None, rerun_filter=None): # In case @flaky is applied to a function or class without arguments # (and without parentheses), max_runs will refer to the wrapped object. # In this case, the default value can be used. wrapped = None if hasattr(max_runs, '__call__'): ...
Decorator used to mark a test as "flaky". When used in conjuction with the flaky nosetests plugin, will cause the decorated test to be retried until min_passes successes are achieved out of up to max_runs test runs. :param max_runs: The maximum number of times the decorated test will be run. :t...
train
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/flaky_decorator.py#L8-L56
[ "def default_flaky_attributes(max_runs=None, min_passes=None, rerun_filter=None):\n \"\"\"\n Returns the default flaky attributes to set on a flaky test.\n\n :param max_runs:\n The value of the FlakyNames.MAX_RUNS attribute to use.\n :type max_runs:\n `int`\n :param min_passes:\n ...
# coding: utf-8 from __future__ import unicode_literals from flaky.defaults import default_flaky_attributes
box/flaky
flaky/flaky_nose_plugin.py
FlakyPlugin.options
python
def options(self, parser, env=os.environ): # pylint:disable=dangerous-default-value super(FlakyPlugin, self).options(parser, env=env) self.add_report_option(parser.add_option) group = OptionGroup( parser, "Force flaky", "Force all tests to be flaky.") self.add_force_f...
Base class override. Add options to the nose argument parser.
train
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/flaky_nose_plugin.py#L35-L46
null
class FlakyPlugin(_FlakyPlugin, Plugin): """ Plugin for nosetests that allows retrying flaky tests. """ name = 'flaky' def __init__(self): super(FlakyPlugin, self).__init__() self._logger = logging.getLogger('nose.plugins.flaky') self._flaky_result = None self._nose_...
box/flaky
flaky/flaky_nose_plugin.py
FlakyPlugin._get_stream
python
def _get_stream(self, multiprocess=False): if multiprocess: from flaky.multiprocess_string_io import MultiprocessingStringIO return MultiprocessingStringIO() return self._stream
Get the stream used to store the flaky report. If this nose run is going to use the multiprocess plugin, then use a multiprocess-list backed StringIO proxy; otherwise, use the default stream. :param multiprocess: Whether or not this test run is configured for multiprocessing...
train
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/flaky_nose_plugin.py#L48-L67
null
class FlakyPlugin(_FlakyPlugin, Plugin): """ Plugin for nosetests that allows retrying flaky tests. """ name = 'flaky' def __init__(self): super(FlakyPlugin, self).__init__() self._logger = logging.getLogger('nose.plugins.flaky') self._flaky_result = None self._nose_...
box/flaky
flaky/flaky_nose_plugin.py
FlakyPlugin.configure
python
def configure(self, options, conf): super(FlakyPlugin, self).configure(options, conf) if not self.enabled: return is_multiprocess = int(getattr(options, 'multiprocess_workers', 0)) > 0 self._stream = self._get_stream(is_multiprocess) self._flaky_result = TextTestResul...
Base class override.
train
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/flaky_nose_plugin.py#L69-L81
null
class FlakyPlugin(_FlakyPlugin, Plugin): """ Plugin for nosetests that allows retrying flaky tests. """ name = 'flaky' def __init__(self): super(FlakyPlugin, self).__init__() self._logger = logging.getLogger('nose.plugins.flaky') self._flaky_result = None self._nose_...
box/flaky
flaky/flaky_nose_plugin.py
FlakyPlugin.handleError
python
def handleError(self, test, err): # pylint:disable=invalid-name want_error = self._handle_test_error_or_failure(test, err) if not want_error and id(test) in self._tests_that_reran: self._nose_result.addError(test, err) return want_error or None
Baseclass override. Called when a test raises an exception. If the test isn't going to be rerun again, then report the error to the nose test result. :param test: The test that has raised an error :type test: :class:`nose.case.Test` :param err: ...
train
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/flaky_nose_plugin.py#L129-L153
null
class FlakyPlugin(_FlakyPlugin, Plugin): """ Plugin for nosetests that allows retrying flaky tests. """ name = 'flaky' def __init__(self): super(FlakyPlugin, self).__init__() self._logger = logging.getLogger('nose.plugins.flaky') self._flaky_result = None self._nose_...
box/flaky
flaky/flaky_nose_plugin.py
FlakyPlugin.handleFailure
python
def handleFailure(self, test, err): # pylint:disable=invalid-name want_failure = self._handle_test_error_or_failure(test, err) if not want_failure and id(test) in self._tests_that_reran: self._nose_result.addFailure(test, err) return want_failure or None
Baseclass override. Called when a test fails. If the test isn't going to be rerun again, then report the failure to the nose test result. :param test: The test that has raised an error :type test: :class:`nose.case.Test` :param err: Informati...
train
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/flaky_nose_plugin.py#L155-L179
null
class FlakyPlugin(_FlakyPlugin, Plugin): """ Plugin for nosetests that allows retrying flaky tests. """ name = 'flaky' def __init__(self): super(FlakyPlugin, self).__init__() self._logger = logging.getLogger('nose.plugins.flaky') self._flaky_result = None self._nose_...
box/flaky
flaky/flaky_nose_plugin.py
FlakyPlugin.addSuccess
python
def addSuccess(self, test): # pylint:disable=invalid-name will_handle = self._handle_test_success(test) test_id = id(test) # If this isn't a rerun, the builtin reporter is going to report it as a success if will_handle and test_id not in self._tests_that_reran: self._...
Baseclass override. Called when a test succeeds. Count remaining retries and compare with number of required successes that have not yet been achieved; retry if necessary. Returning True from this method keeps the test runner from reporting the test as a success; this way we can retry ...
train
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/flaky_nose_plugin.py#L181-L210
null
class FlakyPlugin(_FlakyPlugin, Plugin): """ Plugin for nosetests that allows retrying flaky tests. """ name = 'flaky' def __init__(self): super(FlakyPlugin, self).__init__() self._logger = logging.getLogger('nose.plugins.flaky') self._flaky_result = None self._nose_...
box/flaky
flaky/defaults.py
default_flaky_attributes
python
def default_flaky_attributes(max_runs=None, min_passes=None, rerun_filter=None): if max_runs is None: max_runs = 2 if min_passes is None: min_passes = 1 if min_passes <= 0: raise ValueError('min_passes must be positive') if max_runs < min_passes: raise ValueError('min_pas...
Returns the default flaky attributes to set on a flaky test. :param max_runs: The value of the FlakyNames.MAX_RUNS attribute to use. :type max_runs: `int` :param min_passes: The value of the FlakyNames.MIN_PASSES attribute to use. :type min_passes: `int` :param rerun...
train
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/defaults.py#L27-L63
null
# coding: utf-8 from flaky.names import FlakyNames def _true(*args): """ Default rerun filter function that always returns True. """ # pylint:disable=unused-argument return True class FilterWrapper(object): """ Filter function wrapper. Expected to be called as though it's a filter f...
box/flaky
flaky/utils.py
ensure_unicode_string
python
def ensure_unicode_string(obj): try: return unicode_type(obj) except UnicodeDecodeError: if hasattr(obj, 'decode'): return obj.decode('utf-8', 'replace') return str(obj).decode('utf-8', 'replace')
Return a unicode string representation of the given obj. :param obj: The obj we want to represent in unicode :type obj: varies :rtype: `unicode`
train
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/utils.py#L12-L28
null
# coding: utf-8 from __future__ import unicode_literals # pylint:disable=invalid-name try: unicode_type = unicode except NameError: unicode_type = str
box/flaky
flaky/_flaky_plugin.py
_FlakyPlugin._report_final_failure
python
def _report_final_failure(self, err, flaky, name): min_passes = flaky[FlakyNames.MIN_PASSES] current_passes = flaky[FlakyNames.CURRENT_PASSES] message = self._failure_message.format( current_passes, min_passes, ) self._log_test_failure(name, err, message)
Report that the test has failed too many times to pass at least min_passes times. By default, this means that the test has failed twice. :param err: Information about the test failure (from sys.exc_info()) :type err: `tuple` of `class`, :class:`Exception`, `trac...
train
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/_flaky_plugin.py#L50-L76
null
class _FlakyPlugin(object): _retry_failure_message = ' failed ({0} runs remaining out of {1}).' _failure_message = ' failed; it passed {0} out of the required {1} times.' _not_rerun_message = ' failed and was not selected for rerun.' def __init__(self): super(_FlakyPlugin, self).__init__() ...
box/flaky
flaky/_flaky_plugin.py
_FlakyPlugin._log_intermediate_failure
python
def _log_intermediate_failure(self, err, flaky, name): max_runs = flaky[FlakyNames.MAX_RUNS] runs_left = max_runs - flaky[FlakyNames.CURRENT_RUNS] message = self._retry_failure_message.format( runs_left, max_runs, ) self._log_test_failure(name, err, messag...
Report that the test has failed, but still has reruns left. Then rerun the test. :param err: Information about the test failure (from sys.exc_info()) :type err: `tuple` of `class`, :class:`Exception`, `traceback` :param flaky: Dictionary of flaky attr...
train
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/_flaky_plugin.py#L78-L102
null
class _FlakyPlugin(object): _retry_failure_message = ' failed ({0} runs remaining out of {1}).' _failure_message = ' failed; it passed {0} out of the required {1} times.' _not_rerun_message = ' failed and was not selected for rerun.' def __init__(self): super(_FlakyPlugin, self).__init__() ...
box/flaky
flaky/_flaky_plugin.py
_FlakyPlugin.add_report_option
python
def add_report_option(add_option): add_option( '--no-flaky-report', action='store_false', dest='flaky_report', default=True, help="Suppress the report at the end of the " "run detailing flaky test results.", ) add_optio...
Add an option to the test runner to suppress the flaky report. :param add_option: A function that can add an option to the test runner. Its argspec should equal that of argparse.add_option. :type add_option: `callable`
train
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/_flaky_plugin.py#L300-L326
null
class _FlakyPlugin(object): _retry_failure_message = ' failed ({0} runs remaining out of {1}).' _failure_message = ' failed; it passed {0} out of the required {1} times.' _not_rerun_message = ' failed and was not selected for rerun.' def __init__(self): super(_FlakyPlugin, self).__init__() ...
box/flaky
flaky/_flaky_plugin.py
_FlakyPlugin.add_force_flaky_options
python
def add_force_flaky_options(add_option): add_option( '--force-flaky', action="store_true", dest="force_flaky", default=False, help="If this option is specified, we will treat all tests as " "flaky." ) add_option( ...
Add options to the test runner that force all tests to be flaky. :param add_option: A function that can add an option to the test runner. Its argspec should equal that of argparse.add_option. :type add_option: `callable`
train
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/_flaky_plugin.py#L329-L366
null
class _FlakyPlugin(object): _retry_failure_message = ' failed ({0} runs remaining out of {1}).' _failure_message = ' failed; it passed {0} out of the required {1} times.' _not_rerun_message = ' failed and was not selected for rerun.' def __init__(self): super(_FlakyPlugin, self).__init__() ...
box/flaky
flaky/_flaky_plugin.py
_FlakyPlugin._add_flaky_report
python
def _add_flaky_report(self, stream): value = self._stream.getvalue() # If everything succeeded and --no-success-flaky-report is specified # don't print anything. if not self._flaky_success_report and not value: return stream.write('===Flaky Test Report===\n\n') ...
Baseclass override. Write details about flaky tests to the test report. :param stream: The test stream to which the report can be written. :type stream: `file`
train
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/_flaky_plugin.py#L368-L395
null
class _FlakyPlugin(object): _retry_failure_message = ' failed ({0} runs remaining out of {1}).' _failure_message = ' failed; it passed {0} out of the required {1} times.' _not_rerun_message = ' failed and was not selected for rerun.' def __init__(self): super(_FlakyPlugin, self).__init__() ...
box/flaky
flaky/_flaky_plugin.py
_FlakyPlugin._copy_flaky_attributes
python
def _copy_flaky_attributes(cls, test, test_class): test_callable = cls._get_test_callable(test) if test_callable is None: return for attr, value in cls._get_flaky_attributes(test_class).items(): already_set = hasattr(test, attr) if already_set: ...
Copy flaky attributes from the test callable or class to the test. :param test: The test that is being prepared to run :type test: :class:`nose.case.Test`
train
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/_flaky_plugin.py#L398-L418
[ "def _set_flaky_attribute(test_item, flaky_attribute, value):\n \"\"\"\n Sets an attribute on a flaky test. Uses magic __dict__ since setattr\n doesn't work for bound methods.\n\n :param test_item:\n The test callable on which to set the attribute\n :type test_item:\n `callable` or :cla...
class _FlakyPlugin(object): _retry_failure_message = ' failed ({0} runs remaining out of {1}).' _failure_message = ' failed; it passed {0} out of the required {1} times.' _not_rerun_message = ' failed and was not selected for rerun.' def __init__(self): super(_FlakyPlugin, self).__init__() ...
box/flaky
flaky/_flaky_plugin.py
_FlakyPlugin._increment_flaky_attribute
python
def _increment_flaky_attribute(cls, test_item, flaky_attribute): cls._set_flaky_attribute(test_item, flaky_attribute, cls._get_flaky_attribute(test_item, flaky_attribute) + 1)
Increments the value of an attribute on a flaky test. :param test_item: The test callable on which to set the attribute :type test_item: `callable` or :class:`nose.case.Test` or :class:`Function` :param flaky_attribute: The name of the attribute to set ...
train
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/_flaky_plugin.py#L463-L476
null
class _FlakyPlugin(object): _retry_failure_message = ' failed ({0} runs remaining out of {1}).' _failure_message = ' failed; it passed {0} out of the required {1} times.' _not_rerun_message = ' failed and was not selected for rerun.' def __init__(self): super(_FlakyPlugin, self).__init__() ...
box/flaky
flaky/_flaky_plugin.py
_FlakyPlugin._has_flaky_attributes
python
def _has_flaky_attributes(cls, test): current_runs = cls._get_flaky_attribute(test, FlakyNames.CURRENT_RUNS) return current_runs is not None
Returns True if the test callable in question is marked as flaky. :param test: The test that is being prepared to run :type test: :class:`nose.case.Test` or :class:`Function` :return: :rtype: `bool`
train
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/_flaky_plugin.py#L479-L492
[ "def _get_flaky_attribute(test_item, flaky_attribute):\n \"\"\"\n Gets an attribute describing the flaky test.\n\n :param test_item:\n The test method from which to get the attribute\n :type test_item:\n `callable` or :class:`nose.case.Test` or :class:`Function`\n :param flaky_attribute...
class _FlakyPlugin(object): _retry_failure_message = ' failed ({0} runs remaining out of {1}).' _failure_message = ' failed; it passed {0} out of the required {1} times.' _not_rerun_message = ' failed and was not selected for rerun.' def __init__(self): super(_FlakyPlugin, self).__init__() ...
box/flaky
flaky/_flaky_plugin.py
_FlakyPlugin._get_flaky_attributes
python
def _get_flaky_attributes(cls, test_item): return { attr: cls._get_flaky_attribute( test_item, attr, ) for attr in FlakyNames() }
Get all the flaky related attributes from the test. :param test_item: The test callable from which to get the flaky related attributes. :type test_item: `callable` or :class:`nose.case.Test` or :class:`Function` :return: :rtype: `dict` of `unicode` to...
train
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/_flaky_plugin.py#L495-L512
null
class _FlakyPlugin(object): _retry_failure_message = ' failed ({0} runs remaining out of {1}).' _failure_message = ' failed; it passed {0} out of the required {1} times.' _not_rerun_message = ' failed and was not selected for rerun.' def __init__(self): super(_FlakyPlugin, self).__init__() ...
frictionlessdata/datapackage-pipelines
datapackage_pipelines/utilities/dirtools.py
_filehash
python
def _filehash(filepath, blocksize=4096): sha = hashlib.sha256() with open(filepath, 'rb') as fp: while 1: data = fp.read(blocksize) if data: sha.update(data) else: break return sha
Return the hash object for the file `filepath', processing the file by chunk of `blocksize'. :type filepath: str :param filepath: Path to file :type blocksize: int :param blocksize: Size of the chunk when processing the file
train
https://github.com/frictionlessdata/datapackage-pipelines/blob/3a34bbdf042d13c3bec5eef46ff360ee41403874/datapackage_pipelines/utilities/dirtools.py#L34-L53
null
# -*- coding: utf-8 -*- # Source: https://github.com/tsileo/dirtools (copied here because pypi package is not updated) import logging import os import hashlib from contextlib import closing # for Python2.6 compatibility import tarfile import tempfile from datetime import datetime import json from globster import Glo...
frictionlessdata/datapackage-pipelines
datapackage_pipelines/utilities/dirtools.py
compute_diff
python
def compute_diff(dir_base, dir_cmp): data = {} data['deleted'] = list(set(dir_cmp['files']) - set(dir_base['files'])) data['created'] = list(set(dir_base['files']) - set(dir_cmp['files'])) data['updated'] = [] data['deleted_dirs'] = list(set(dir_cmp['subdirs']) - set(dir_base['subdirs'])) for f...
Compare `dir_base' and `dir_cmp' and returns a list with the following keys: - deleted files `deleted' - created files `created' - updated files `updated' - deleted directories `deleted_dirs'
train
https://github.com/frictionlessdata/datapackage-pipelines/blob/3a34bbdf042d13c3bec5eef46ff360ee41403874/datapackage_pipelines/utilities/dirtools.py#L373-L392
null
# -*- coding: utf-8 -*- # Source: https://github.com/tsileo/dirtools (copied here because pypi package is not updated) import logging import os import hashlib from contextlib import closing # for Python2.6 compatibility import tarfile import tempfile from datetime import datetime import json from globster import Glo...
frictionlessdata/datapackage-pipelines
datapackage_pipelines/utilities/dirtools.py
File.compress_to
python
def compress_to(self, archive_path=None): if archive_path is None: archive = tempfile.NamedTemporaryFile(delete=False) tar_args = () tar_kwargs = {'fileobj': archive} _return = archive.name else: tar_args = (archive_path) tar_kwargs...
Compress the directory with gzip using tarlib. :type archive_path: str :param archive_path: Path to the archive, if None, a tempfile is created
train
https://github.com/frictionlessdata/datapackage-pipelines/blob/3a34bbdf042d13c3bec5eef46ff360ee41403874/datapackage_pipelines/utilities/dirtools.py#L84-L104
null
class File(object): def __init__(self, path): self.file = os.path.basename(path) self.path = os.path.abspath(path) def _hash(self): """ Return the hash object. """ return _filehash(self.path) def hash(self): """ Return the hash hexdigest. """ return filehash...
frictionlessdata/datapackage-pipelines
datapackage_pipelines/utilities/dirtools.py
Dir.hash
python
def hash(self, index_func=os.path.getmtime): # TODO alternative to filehash => mtime as a faster alternative shadir = hashlib.sha256() for f in self.files(): try: shadir.update(str(index_func(os.path.join(self.path, f)))) except (IOError, OSError): ...
Hash for the entire directory (except excluded files) recursively. Use mtime instead of sha256 by default for a faster hash. >>> dir.hash(index_func=dirtools.filehash)
train
https://github.com/frictionlessdata/datapackage-pipelines/blob/3a34bbdf042d13c3bec5eef46ff360ee41403874/datapackage_pipelines/utilities/dirtools.py#L138-L153
[ "def files(self, pattern=None, sort_key=lambda k: k, sort_reverse=False, abspath=False):\n \"\"\" Return a sorted list containing relative path of all files (recursively).\n\n :type pattern: str\n :param pattern: Unix style (glob like/gitignore like) pattern\n\n :param sort_key: key argument for sorted\...
class Dir(object): """ Wrapper for dirtools arround a path. Try to load a .exclude file, ready to compute hashdir, :type directory: str :param directory: Root directory for initialization :type exclude_file: str :param exclude_file: File containing exclusion pattern, .exclude by defa...
frictionlessdata/datapackage-pipelines
datapackage_pipelines/utilities/dirtools.py
Dir.iterfiles
python
def iterfiles(self, pattern=None, abspath=False): if pattern is not None: globster = Globster([pattern]) for root, dirs, files in self.walk(): for f in files: if pattern is None or (pattern is not None and globster.match(f)): if abspath: ...
Generator for all the files not excluded recursively. Return relative path. :type pattern: str :param pattern: Unix style (glob like/gitignore like) pattern
train
https://github.com/frictionlessdata/datapackage-pipelines/blob/3a34bbdf042d13c3bec5eef46ff360ee41403874/datapackage_pipelines/utilities/dirtools.py#L155-L172
[ "def walk(self):\n \"\"\" Walk the directory like os.path\n (yields a 3-tuple (dirpath, dirnames, filenames)\n except it exclude all files/directories on the fly. \"\"\"\n for root, dirs, files in os.walk(self.path, topdown=True):\n # TODO relative walk, recursive call if root excluder found???\n...
class Dir(object): """ Wrapper for dirtools arround a path. Try to load a .exclude file, ready to compute hashdir, :type directory: str :param directory: Root directory for initialization :type exclude_file: str :param exclude_file: File containing exclusion pattern, .exclude by defa...
frictionlessdata/datapackage-pipelines
datapackage_pipelines/utilities/dirtools.py
Dir.files
python
def files(self, pattern=None, sort_key=lambda k: k, sort_reverse=False, abspath=False): return sorted(self.iterfiles(pattern, abspath=abspath), key=sort_key, reverse=sort_reverse)
Return a sorted list containing relative path of all files (recursively). :type pattern: str :param pattern: Unix style (glob like/gitignore like) pattern :param sort_key: key argument for sorted :param sort_reverse: reverse argument for sorted :rtype: list :return: L...
train
https://github.com/frictionlessdata/datapackage-pipelines/blob/3a34bbdf042d13c3bec5eef46ff360ee41403874/datapackage_pipelines/utilities/dirtools.py#L174-L188
[ "def iterfiles(self, pattern=None, abspath=False):\n \"\"\" Generator for all the files not excluded recursively.\n\n Return relative path.\n\n :type pattern: str\n :param pattern: Unix style (glob like/gitignore like) pattern\n\n \"\"\"\n if pattern is not None:\n globster = Globster([patt...
class Dir(object): """ Wrapper for dirtools arround a path. Try to load a .exclude file, ready to compute hashdir, :type directory: str :param directory: Root directory for initialization :type exclude_file: str :param exclude_file: File containing exclusion pattern, .exclude by defa...
frictionlessdata/datapackage-pipelines
datapackage_pipelines/utilities/dirtools.py
Dir.itersubdirs
python
def itersubdirs(self, pattern=None, abspath=False): if pattern is not None: globster = Globster([pattern]) for root, dirs, files in self.walk(): for d in dirs: if pattern is None or (pattern is not None and globster.match(d)): if abspath: ...
Generator for all subdirs (except excluded). :type pattern: str :param pattern: Unix style (glob like/gitignore like) pattern
train
https://github.com/frictionlessdata/datapackage-pipelines/blob/3a34bbdf042d13c3bec5eef46ff360ee41403874/datapackage_pipelines/utilities/dirtools.py#L195-L210
[ "def walk(self):\n \"\"\" Walk the directory like os.path\n (yields a 3-tuple (dirpath, dirnames, filenames)\n except it exclude all files/directories on the fly. \"\"\"\n for root, dirs, files in os.walk(self.path, topdown=True):\n # TODO relative walk, recursive call if root excluder found???\n...
class Dir(object): """ Wrapper for dirtools arround a path. Try to load a .exclude file, ready to compute hashdir, :type directory: str :param directory: Root directory for initialization :type exclude_file: str :param exclude_file: File containing exclusion pattern, .exclude by defa...
frictionlessdata/datapackage-pipelines
datapackage_pipelines/utilities/dirtools.py
Dir.subdirs
python
def subdirs(self, pattern=None, sort_key=lambda k: k, sort_reverse=False, abspath=False): return sorted(self.itersubdirs(pattern, abspath=abspath), key=sort_key, reverse=sort_reverse)
Return a sorted list containing relative path of all subdirs (recursively). :type pattern: str :param pattern: Unix style (glob like/gitignore like) pattern :param sort_key: key argument for sorted :param sort_reverse: reverse argument for sorted :rtype: list :return:...
train
https://github.com/frictionlessdata/datapackage-pipelines/blob/3a34bbdf042d13c3bec5eef46ff360ee41403874/datapackage_pipelines/utilities/dirtools.py#L212-L225
[ "def itersubdirs(self, pattern=None, abspath=False):\n \"\"\" Generator for all subdirs (except excluded).\n\n :type pattern: str\n :param pattern: Unix style (glob like/gitignore like) pattern\n\n \"\"\"\n if pattern is not None:\n globster = Globster([pattern])\n for root, dirs, files in ...
class Dir(object): """ Wrapper for dirtools arround a path. Try to load a .exclude file, ready to compute hashdir, :type directory: str :param directory: Root directory for initialization :type exclude_file: str :param exclude_file: File containing exclusion pattern, .exclude by defa...
frictionlessdata/datapackage-pipelines
datapackage_pipelines/utilities/dirtools.py
Dir.size
python
def size(self): dir_size = 0 for f in self.iterfiles(abspath=True): dir_size += os.path.getsize(f) return dir_size
Return directory size in bytes. :rtype: int :return: Total directory size in bytes.
train
https://github.com/frictionlessdata/datapackage-pipelines/blob/3a34bbdf042d13c3bec5eef46ff360ee41403874/datapackage_pipelines/utilities/dirtools.py#L227-L236
[ "def iterfiles(self, pattern=None, abspath=False):\n \"\"\" Generator for all the files not excluded recursively.\n\n Return relative path.\n\n :type pattern: str\n :param pattern: Unix style (glob like/gitignore like) pattern\n\n \"\"\"\n if pattern is not None:\n globster = Globster([patt...
class Dir(object): """ Wrapper for dirtools arround a path. Try to load a .exclude file, ready to compute hashdir, :type directory: str :param directory: Root directory for initialization :type exclude_file: str :param exclude_file: File containing exclusion pattern, .exclude by defa...
frictionlessdata/datapackage-pipelines
datapackage_pipelines/utilities/dirtools.py
Dir.is_excluded
python
def is_excluded(self, path): match = self.globster.match(self.relpath(path)) if match: log.debug("{0} matched {1} for exclusion".format(path, match)) return True return False
Return True if `path' should be excluded given patterns in the `exclude_file'.
train
https://github.com/frictionlessdata/datapackage-pipelines/blob/3a34bbdf042d13c3bec5eef46ff360ee41403874/datapackage_pipelines/utilities/dirtools.py#L238-L245
[ "def relpath(self, path):\n \"\"\" Return a relative filepath to path from Dir path. \"\"\"\n return os.path.relpath(path, start=self.path)\n" ]
class Dir(object): """ Wrapper for dirtools arround a path. Try to load a .exclude file, ready to compute hashdir, :type directory: str :param directory: Root directory for initialization :type exclude_file: str :param exclude_file: File containing exclusion pattern, .exclude by defa...
frictionlessdata/datapackage-pipelines
datapackage_pipelines/utilities/dirtools.py
Dir.find_projects
python
def find_projects(self, file_identifier=".project"): projects = [] for d in self.subdirs(): project_file = os.path.join(self.directory, d, file_identifier) if os.path.isfile(project_file): projects.append(d) return projects
Search all directory recursively for subdirs with `file_identifier' in it. :type file_identifier: str :param file_identifier: File identier, .project by default. :rtype: list :return: The list of subdirs with a `file_identifier' in it.
train
https://github.com/frictionlessdata/datapackage-pipelines/blob/3a34bbdf042d13c3bec5eef46ff360ee41403874/datapackage_pipelines/utilities/dirtools.py#L269-L285
[ "def subdirs(self, pattern=None, sort_key=lambda k: k, sort_reverse=False, abspath=False):\n \"\"\" Return a sorted list containing relative path of all subdirs (recursively).\n\n :type pattern: str\n :param pattern: Unix style (glob like/gitignore like) pattern\n\n :param sort_key: key argument for sor...
class Dir(object): """ Wrapper for dirtools arround a path. Try to load a .exclude file, ready to compute hashdir, :type directory: str :param directory: Root directory for initialization :type exclude_file: str :param exclude_file: File containing exclusion pattern, .exclude by defa...
frictionlessdata/datapackage-pipelines
datapackage_pipelines/utilities/dirtools.py
Dir.relpath
python
def relpath(self, path): return os.path.relpath(path, start=self.path)
Return a relative filepath to path from Dir path.
train
https://github.com/frictionlessdata/datapackage-pipelines/blob/3a34bbdf042d13c3bec5eef46ff360ee41403874/datapackage_pipelines/utilities/dirtools.py#L287-L289
null
class Dir(object): """ Wrapper for dirtools arround a path. Try to load a .exclude file, ready to compute hashdir, :type directory: str :param directory: Root directory for initialization :type exclude_file: str :param exclude_file: File containing exclusion pattern, .exclude by defa...
frictionlessdata/datapackage-pipelines
datapackage_pipelines/utilities/dirtools.py
DirState.compute_state
python
def compute_state(self): data = {} data['directory'] = self._dir.path data['files'] = list(self._dir.files()) data['subdirs'] = list(self._dir.subdirs()) data['index'] = self.index() return data
Generate the index.
train
https://github.com/frictionlessdata/datapackage-pipelines/blob/3a34bbdf042d13c3bec5eef46ff360ee41403874/datapackage_pipelines/utilities/dirtools.py#L321-L328
[ "def index(self):\n index = {}\n for f in self._dir.iterfiles():\n try:\n index[f] = self.index_cmp(os.path.join(self._dir.path, f))\n except Exception as exc:\n print(f, exc)\n return index\n" ]
class DirState(object): """ Hold a directory state / snapshot meta-data for later comparison. """ def __init__(self, _dir=None, state=None, index_cmp=os.path.getmtime): self._dir = _dir self.index_cmp = index_cmp self.state = state or self.compute_state() def index(self): i...
frictionlessdata/datapackage-pipelines
datapackage_pipelines/cli.py
run
python
def run(pipeline_id, verbose, use_cache, dirty, force, concurrency, slave): exitcode = 0 running = [] progress = {} def progress_cb(report): pid, count, success, *_, stats = report print('\x1b[%sA' % (1+len(running))) if pid not in progress: running.append(pid) ...
Run a pipeline by pipeline-id. pipeline-id supports '%' wildcard for any-suffix matching, 'all' for running all pipelines and comma-delimited list of pipeline ids
train
https://github.com/frictionlessdata/datapackage-pipelines/blob/3a34bbdf042d13c3bec5eef46ff360ee41403874/datapackage_pipelines/cli.py#L50-L117
[ "def run_pipelines(pipeline_id_pattern,\n root_dir,\n use_cache=True,\n dirty=False,\n force=False,\n concurrency=1,\n verbose_logs=True,\n progress_cb=None,\n slave=False):\n \...
import sys import json import os import click import requests from .utilities.stat_utils import user_facing_stats from .manager.logging_config import logging from .specs import pipelines, PipelineSpec #noqa from .status import status_mgr from .manager import run_pipelines @click.group(invoke_without_command=True)...
frictionlessdata/datapackage-pipelines
datapackage_pipelines/web/server.py
basic_auth_required
python
def basic_auth_required(view_func): @wraps(view_func) def wrapper(*args, **kwargs): if app.config.get('BASIC_AUTH_ACTIVE', False): if basic_auth.authenticate(): return view_func(*args, **kwargs) else: return basic_auth.challenge() else: ...
A decorator that can be used to protect specific views with HTTP basic access authentication. Conditional on having BASIC_AUTH_USERNAME and BASIC_AUTH_PASSWORD set as env vars.
train
https://github.com/frictionlessdata/datapackage-pipelines/blob/3a34bbdf042d13c3bec5eef46ff360ee41403874/datapackage_pipelines/web/server.py#L87-L102
null
import datetime import os from io import BytesIO import logging from functools import wraps from copy import deepcopy from collections import Counter import slugify import yaml import mistune import requests from flask import \ Blueprint, Flask, render_template, abort, send_file, make_response from flask_cors imp...
frictionlessdata/datapackage-pipelines
datapackage_pipelines/web/server.py
badge
python
def badge(pipeline_id): '''An individual pipeline status''' if not pipeline_id.startswith('./'): pipeline_id = './' + pipeline_id pipeline_status = status.get(pipeline_id) status_color = 'lightgray' if pipeline_status.pipeline_details: status_text = pipeline_status.state().lower() ...
An individual pipeline status
train
https://github.com/frictionlessdata/datapackage-pipelines/blob/3a34bbdf042d13c3bec5eef46ff360ee41403874/datapackage_pipelines/web/server.py#L267-L288
[ "def _make_badge_response(subject, text, colour):\n image_url = 'https://img.shields.io/badge/{}-{}-{}.svg'.format(\n subject, text, colour)\n r = requests.get(image_url)\n buffer_image = BytesIO(r.content)\n buffer_image.seek(0)\n res = make_response(send_file(buffer_image, mimetype='image/sv...
import datetime import os from io import BytesIO import logging from functools import wraps from copy import deepcopy from collections import Counter import slugify import yaml import mistune import requests from flask import \ Blueprint, Flask, render_template, abort, send_file, make_response from flask_cors imp...
frictionlessdata/datapackage-pipelines
datapackage_pipelines/web/server.py
badge_collection
python
def badge_collection(pipeline_path): '''Status badge for a collection of pipelines.''' all_pipeline_ids = sorted(status.all_pipeline_ids()) if not pipeline_path.startswith('./'): pipeline_path = './' + pipeline_path # Filter pipeline ids to only include those that start with pipeline_path. ...
Status badge for a collection of pipelines.
train
https://github.com/frictionlessdata/datapackage-pipelines/blob/3a34bbdf042d13c3bec5eef46ff360ee41403874/datapackage_pipelines/web/server.py#L292-L326
[ "def _make_badge_response(subject, text, colour):\n image_url = 'https://img.shields.io/badge/{}-{}-{}.svg'.format(\n subject, text, colour)\n r = requests.get(image_url)\n buffer_image = BytesIO(r.content)\n buffer_image.seek(0)\n res = make_response(send_file(buffer_image, mimetype='image/sv...
import datetime import os from io import BytesIO import logging from functools import wraps from copy import deepcopy from collections import Counter import slugify import yaml import mistune import requests from flask import \ Blueprint, Flask, render_template, abort, send_file, make_response from flask_cors imp...
frictionlessdata/datapackage-pipelines
datapackage_pipelines/manager/runner.py
run_pipelines
python
def run_pipelines(pipeline_id_pattern, root_dir, use_cache=True, dirty=False, force=False, concurrency=1, verbose_logs=True, progress_cb=None, slave=False): with concurrent...
Run a pipeline by pipeline-id. pipeline-id supports the '%' wildcard for any-suffix matching. Use 'all' or '%' for running all pipelines
train
https://github.com/frictionlessdata/datapackage-pipelines/blob/3a34bbdf042d13c3bec5eef46ff360ee41403874/datapackage_pipelines/manager/runner.py#L161-L274
[ "def execute_pipeline(spec,\n execution_id,\n trigger='manual',\n use_cache=True):\n\n debug = trigger == 'manual' or os.environ.get('DPP_DEBUG')\n logging.info(\"%s RUNNING %s\", execution_id[:8], spec.pipeline_id)\n\n loop = asyncio.get_event_lo...
import sys import os import json import concurrent import subprocess import threading from queue import Queue from collections import namedtuple from ..utilities.execution_id import gen_execution_id from ..specs import pipelines, PipelineSpec #noqa from ..status import status_mgr from ..lib.internal.sink import SINK...
kennethreitz/records
records.py
isexception
python
def isexception(obj): if isinstance(obj, Exception): return True if isclass(obj) and issubclass(obj, Exception): return True return False
Given an object, return a boolean indicating whether it is an instance or subclass of :py:class:`Exception`.
train
https://github.com/kennethreitz/records/blob/ecd857266c5e7830d657cbe0196816314790563b/records.py#L16-L24
null
# -*- coding: utf-8 -*- import os from sys import stdout from collections import OrderedDict from contextlib import contextmanager from inspect import isclass import tablib from docopt import docopt from sqlalchemy import create_engine, exc, inspect, text DATABASE_URL = os.environ.get('DATABASE_URL') class Record...
kennethreitz/records
records.py
_reduce_datetimes
python
def _reduce_datetimes(row): row = list(row) for i in range(len(row)): if hasattr(row[i], 'isoformat'): row[i] = row[i].isoformat() return tuple(row)
Receives a row, converts datetimes to strings.
train
https://github.com/kennethreitz/records/blob/ecd857266c5e7830d657cbe0196816314790563b/records.py#L424-L432
null
# -*- coding: utf-8 -*- import os from sys import stdout from collections import OrderedDict from contextlib import contextmanager from inspect import isclass import tablib from docopt import docopt from sqlalchemy import create_engine, exc, inspect, text DATABASE_URL = os.environ.get('DATABASE_URL') def isexcepti...
kennethreitz/records
records.py
Record.as_dict
python
def as_dict(self, ordered=False): items = zip(self.keys(), self.values()) return OrderedDict(items) if ordered else dict(items)
Returns the row as a dictionary, as ordered.
train
https://github.com/kennethreitz/records/blob/ecd857266c5e7830d657cbe0196816314790563b/records.py#L81-L85
[ "def keys(self):\n \"\"\"Returns the list of column names from the query.\"\"\"\n return self._keys\n", "def values(self):\n \"\"\"Returns the list of values from the query.\"\"\"\n return self._values\n" ]
class Record(object): """A row, from a query, from a database.""" __slots__ = ('_keys', '_values') def __init__(self, keys, values): self._keys = keys self._values = values # Ensure that lengths match properly. assert len(self._keys) == len(self._values) def keys(self)...
kennethreitz/records
records.py
Record.dataset
python
def dataset(self): data = tablib.Dataset() data.headers = self.keys() row = _reduce_datetimes(self.values()) data.append(row) return data
A Tablib Dataset containing the row.
train
https://github.com/kennethreitz/records/blob/ecd857266c5e7830d657cbe0196816314790563b/records.py#L88-L96
[ "def _reduce_datetimes(row):\n \"\"\"Receives a row, converts datetimes to strings.\"\"\"\n\n row = list(row)\n\n for i in range(len(row)):\n if hasattr(row[i], 'isoformat'):\n row[i] = row[i].isoformat()\n return tuple(row)\n", "def keys(self):\n \"\"\"Returns the list of column ...
class Record(object): """A row, from a query, from a database.""" __slots__ = ('_keys', '_values') def __init__(self, keys, values): self._keys = keys self._values = values # Ensure that lengths match properly. assert len(self._keys) == len(self._values) def keys(self)...