code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if kind is None and tag is None: raise TypeError("get() takes at least one keyword-only argument. 'kind' or 'tag'.") kinds = self.all tags = self.all if kind is not None: kinds = self.kinds[kind] if tag is not None: tags = self.tags[tag] return (x for x in kinds.intersection(tags))
def get(self, *, kind: Type=None, tag: Hashable=None, **_) -> Iterator
Get an iterator of objects by kind or tag. kind: Any type. Pass to get a subset of contained items with the given type. tag: Any Hashable object. Pass to get a subset of contained items with the given tag. Pass both kind and tag to get objects that are both that type and that tag. Examples: container.get(type=MyObject) container.get(tag="red") container.get(type=MyObject, tag="red")
3.102009
3.344198
0.92758
self.all.remove(game_object) for kind in type(game_object).mro(): self.kinds[kind].remove(game_object) for s in self.tags.values(): s.discard(game_object)
def remove(self, game_object: Hashable) -> None
Remove the given object from the container. game_object: A hashable contained by container. Example: container.remove(myObject)
4.501195
4.797457
0.938246
next = self.next self.next = None if self.next or not self.running: message = "The Scene.change interface is deprecated. Use the events commands instead." warn(message, DeprecationWarning) return self.running, {"scene_class": next}
def change(self) -> Tuple[bool, dict]
Default case, override in subclass as necessary.
10.59479
10.218267
1.036848
self.game_objects.add(game_object, tags)
def add(self, game_object: Hashable, tags: Iterable=())-> None
Add a game_object to the scene. game_object: Any GameObject object. The item to be added. tags: An iterable of Hashable objects. Values that can be used to retrieve a group containing the game_object. Examples: scene.add(MyGameObject()) scene.add(MyGameObject(), tags=("red", "blue")
5.515954
8.472594
0.651035
return self.game_objects.get(kind=kind, tag=tag, **kwargs)
def get(self, *, kind: Type=None, tag: Hashable=None, **kwargs) -> Iterator
Get an iterator of GameObjects by kind or tag. kind: Any type. Pass to get a subset of contained GameObjects with the given type. tag: Any Hashable object. Pass to get a subset of contained GameObjects with the given tag. Pass both kind and tag to get objects that are both that type and that tag. Examples: scene.get(type=MyGameObject) scene.get(tag="red") scene.get(type=MyGameObject, tag="red")
6.635554
6.615271
1.003066
if section is None: filename = "requirements.txt" else: filename = f"requirements-{section}.txt" with open(filename) as file: return [line.strip() for line in file]
def requirements(section=None)
Helper for loading dependencies from requirements files.
2.563999
2.434721
1.053098
filehasher = hashlib.md5() while True: data = file.read(8192) if not data: break filehasher.update(data) file.seek(0) self.hash_key = filehasher.hexdigest()
def set_hash_key(self, file)
Calculate and store hash key for file.
2.13027
1.948619
1.093221
def _append_sorted(root, el, comparator): for child in root: rel = comparator(el, child) if rel > 0: # el fits inside child, add to child and return _append_sorted(child, el, comparator) return if rel < 0: # child fits inside el, move child into el (may move more than one) _append_sorted(el, child, comparator) # we weren't added to a child, so add to root root.append(el)
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.
null
null
null
def _box_in_box(el, child): 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('y1')), ])
Return True if child is contained within el.
null
null
null
def _comp_bbox(el, el2): # 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 if _box_in_box(el, el2): return -1 return 0
Return 1 if el in el2, -1 if el2 in el, else 0
null
null
null
def smart_unicode_decode(encoded_string): if not encoded_string: return u'' # optimization -- first try ascii try: return encoded_string.decode('ascii') except UnicodeDecodeError: pass # detect encoding detected_encoding = chardet.detect(encoded_string) # bug 54 -- depending on chardet version, if encoding is not guessed, # either detected_encoding will be None or detected_encoding['encoding'] will be None detected_encoding = detected_encoding['encoding'] if detected_encoding and detected_encoding.get('encoding') else 'utf8' decoded_string = six.text_type( encoded_string, encoding=detected_encoding, errors='replace' ) # unicode string may still have useless BOM character at the beginning if decoded_string and decoded_string[0] in bom_headers: decoded_string = decoded_string[1:] return decoded_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\x00r\x00t\x00 \x00v\x002\x00.\x002')
null
null
null
def prepare_for_json_encoding(obj): 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: # alphabetizing keys lets us compare attributes for equality across runs return OrderedDict( (prepare_for_json_encoding(k), prepare_for_json_encoding(obj[k])) for k in sorted(obj.keys()) ) if obj_type == six.binary_type: return smart_unicode_decode(obj) if obj_type == bool or obj is None or obj_type == six.text_type or isinstance(obj, numbers.Number): return obj if obj_type == PSLiteral: # special case because pdfminer.six currently adds extra quotes to PSLiteral.__repr__ return u"/%s" % obj.name return six.text_type(obj)
Convert an arbitrary object into just JSON data types (list, dict, unicode str, int, bool, null).
null
null
null
def obj_to_string(obj, top=True): 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.
null
null
null
def get_page_number(self, index): # get and cache page ranges if not hasattr(self, 'page_range_pairs'): try: page_ranges = resolve1(self.catalog['PageLabels'])['Nums'] assert len(page_ranges) > 1 and len(page_ranges) % 2 == 0 self.page_range_pairs = list( reversed(list(zip(page_ranges[::2], page_ranges[1::2])))) except: self.page_range_pairs = [] if not self.page_range_pairs: return "" # find page range containing index for starting_index, label_format in self.page_range_pairs: if starting_index <= index: break # we found correct label_format label_format = resolve1(label_format) page_label = "" # handle numeric part of label if 'S' in label_format: # first find number for this page ... page_label = index - starting_index if 'St' in label_format: # alternate start value page_label += label_format['St'] else: page_label += 1 # ... then convert to correct format num_type = label_format['S'].name # roman (upper or lower) if num_type.lower() == 'r': import roman page_label = roman.toRoman(page_label) if num_type == 'r': page_label = page_label.lower() # letters elif num_type.lower() == 'a': # a to z for the first 26 pages, aa to zz for the next 26, and # so on letter = chr(page_label % 26 + 65) letter *= page_label / 26 + 1 if num_type == 'a': letter = letter.lower() page_label = letter # decimal arabic else: # if num_type == 'D': page_label = obj_to_string(page_label) # handle string prefix if 'P' in label_format: page_label = smart_unicode_decode(label_format['P']) + page_label return page_label
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'}] So we have to first find the correct label_format based on the closest starting_index lower than the requested index, then use the label_format to convert the index to a page label. Label format meaning: /S = [ D Decimal arabic numerals R Uppercase roman numerals r Lowercase roman numerals A Uppercase letters (A to Z for the first 26 pages, AA to ZZ for the next 26, and so on) a Lowercase letters (a to z for the first 26 pages, aa to zz for the next 26, and so on) ] (if no /S, just use prefix ...) /P = text string label /St = integer start value
null
null
null
def load(self, *page_numbers): self.tree = self.get_tree(*_flatten(page_numbers)) self.pq = self.get_pyquery(self.tree)
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>, <LTPage>] >>> pdf.load(1) >>> pdf.pq('LTPage') [<LTPage>] >>> pdf.load(0, 1) >>> pdf.pq('LTPage') [<LTPage>, <LTPage>]
null
null
null
def extract(self, searches, tree=None, as_dict=True): if self.tree is None or self.pq is None: self.load() if tree is None: pq = self.pq else: pq = PyQuery(tree, css_translator=PDFQueryTranslator()) results = [] formatter = None parent = pq for search in searches: if len(search) < 3: search = list(search) + [formatter] key, search, tmp_formatter = search if key == 'with_formatter': if isinstance(search, six.string_types): # is a pyquery method name, e.g. 'text' formatter = lambda o, search=search: getattr(o, search)() elif hasattr(search, '__call__') or not search: # is a method, or None to end formatting formatter = search else: raise TypeError("Formatter should be either a pyquery " "method name or a callable function.") elif key == 'with_parent': parent = pq(search) if search else pq else: try: result = parent("*").filter(search) if \ hasattr(search, '__call__') else parent(search) except cssselect.SelectorSyntaxError as e: raise cssselect.SelectorSyntaxError( "Error applying selector '%s': %s" % (search, e)) if tmp_formatter: result = tmp_formatter(result) results += result if type(result) == tuple else [[key, result]] if as_dict: results = dict(results) return results
>>> foo = pdf.extract([['pages', 'LTPage']]) >>> foo {'pages': [<LTPage>, <LTPage>]} >>> pdf.extract([['bar', ':in_bbox("100,100,400,400")']], foo['pages'][0]) {'bar': [<LTTextLineHorizontal>, <LTTextBoxHorizontal>,...
null
null
null
def get_pyquery(self, tree=None, page_numbers=None): if not page_numbers: page_numbers = [] if tree is None: if not page_numbers and self.tree is not None: tree = self.tree else: tree = self.get_tree(page_numbers) if hasattr(tree, 'getroot'): tree = tree.getroot() return PyQuery(tree, css_translator=PDFQueryTranslator())
Wrap given tree in pyquery and return. If no tree supplied, will generate one from given page_numbers, or all page numbers.
null
null
null
def get_tree(self, *page_numbers): cache_key = "_".join(map(str, _flatten(page_numbers))) tree = self._parse_tree_cacher.get(cache_key) if tree is None: # set up root root = parser.makeelement("pdfxml") if self.doc.info: for k, v in list(self.doc.info[0].items()): k = obj_to_string(k) v = obj_to_string(resolve1(v)) try: root.set(k, v) except ValueError as e: # Sometimes keys have a character in them, like ':', # that isn't allowed in XML attribute names. # If that happens we just replace non-word characters # with '_'. if "Invalid attribute name" in e.args[0]: k = re.sub('\W', '_', k) root.set(k, v) # Parse pages and append to root. # If nothing was passed in for page_numbers, we do this for all # pages, but if None was explicitly passed in, we skip it. if not(len(page_numbers) == 1 and page_numbers[0] is None): if page_numbers: pages = [[n, self.get_layout(self.get_page(n))] for n in _flatten(page_numbers)] else: pages = enumerate(self.get_layouts()) for n, page in pages: page = self._xmlize(page) page.set('page_index', obj_to_string(n)) page.set('page_label', self.doc.get_page_number(n)) root.append(page) self._clean_text(root) # wrap root in ElementTree tree = etree.ElementTree(root) self._parse_tree_cacher.set(cache_key, tree) return tree
Return lxml.etree.ElementTree for entire document, or page numbers given if any.
null
null
null
def _clean_text(self, branch): if branch.text and self.input_text_formatter: branch.text = self.input_text_formatter(branch.text) try: for child in branch: self._clean_text(child) if branch.text and branch.text.find(child.text) >= 0: branch.text = branch.text.replace(child.text, '', 1) except TypeError: # not an iterable node pass
Remove text from node if same text exists in its children. Apply string formatter if set.
null
null
null
def _getattrs(self, obj, *attrs): filtered_attrs = {} for attr in attrs: if hasattr(obj, attr): filtered_attrs[attr] = obj_to_string( self._filter_value(getattr(obj, attr)) ) return filtered_attrs
Return dictionary of given attrs on given object, if they exist, processing through _filter_value().
null
null
null
def get_layout(self, page): 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.annots) return layout
Get PDFMiner Layout object for given page object or page number.
null
null
null
def _cached_pages(self, target_page=-1): try: # pdfminer < 20131022 self._pages_iter = self._pages_iter or self.doc.get_pages() except AttributeError: # pdfminer >= 20131022 self._pages_iter = self._pages_iter or \ PDFPage.create_pages(self.doc) if target_page >= 0: while len(self._pages) <= target_page: next_page = next(self._pages_iter) if not next_page: return None next_page.page_number = 0 self._pages += [next_page] try: return self._pages[target_page] except IndexError: return None self._pages += list(self._pages_iter) return self._pages
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.
null
null
null
def _add_annots(self, layout, annots): if annots: for annot in resolve1(annots): annot = resolve1(annot) if annot.get('Rect') is not None: annot['bbox'] = annot.pop('Rect') # Rename key annot = self._set_hwxy_attrs(annot) try: annot['URI'] = resolve1(annot['A'])['URI'] except KeyError: pass for k, v in six.iteritems(annot): if not isinstance(v, six.string_types): annot[k] = obj_to_string(v) elem = parser.makeelement('Annot', annot) layout.add(elem) return layout
Adds annotations to the layout object
null
null
null
def _set_hwxy_attrs(attr): bbox = attr['bbox'] attr['x0'] = bbox[0] attr['x1'] = bbox[2] attr['y0'] = bbox[1] attr['y1'] = bbox[3] attr['height'] = attr['y1'] - attr['y0'] attr['width'] = attr['x1'] - attr['x0'] return attr
Using the bbox attribute, set the h, w, x0, x1, y0, and y1 attributes.
null
null
null
raise ctypes.WinError(ctypes.get_last_error()) return args
def _check_bool(result, func, args): # pylint: disable=unused-argument if not result
Used as an error handler for Windows calls Gets last error if call is not successful
12.055176
8.361044
1.441827
if filehandle is None: filehandle = msvcrt.get_osfhandle(sys.__stdout__.fileno()) csbi = ConsoleScreenBufferInfo() KERNEL32.GetConsoleScreenBufferInfo(filehandle, ctypes.byref(csbi)) return csbi
def get_csbi(filehandle=None)
Returns a CONSOLE_SCREEN_BUFFER_INFO structure for the given console or stdout
2.89669
2.498348
1.159442
if filehandle is None: filehandle = msvcrt.get_osfhandle(sys.__stdout__.fileno()) current_mode = wintypes.DWORD() KERNEL32.GetConsoleMode(filehandle, ctypes.byref(current_mode)) new_mode = 0x0004 | current_mode.value KERNEL32.SetConsoleMode(filehandle, new_mode)
def enable_vt_mode(filehandle=None)
Enables virtual terminal processing mode for the given console or stdout
2.369822
2.237778
1.059007
def func(self, content=''): return self._apply_color(code, content) # pylint: disable=protected-access setattr(Terminal, color, func)
def create_color_method(color, code)
Create a function for the given color Done inside this function to keep the variables out of the main scope
9.170565
7.462556
1.228877
normal = u'\x1B[0m' seq = u'\x1B[%sm' % code # Replace any normal sequences with this sequence to support nested colors return seq + (normal + seq).join(content.split(normal)) + normal
def _apply_color(code, content)
Apply a color code to text
8.216197
7.8767
1.043101
def func(content=''): return self._apply_color(u'38;5;%d' % code, content) return func
def color(self, code)
When color is given as a number, apply that color to the content While this is designed to support 256 color terminals, Windows will approximate this with 16 colors
12.971244
9.692566
1.338267
# In Python 3.3+ we can let the standard library handle this if GTS_SUPPORTED: return os.get_terminal_size(self.stream_fd) window = get_csbi(self.stream_fh).srWindow return TerminalSize(window.Right - window.Left + 1, window.Bottom - window.Top + 1)
def _height_and_width(self)
Query console for dimensions Returns named tuple (columns, lines)
10.46125
9.58729
1.091158
ftp = ftplib.FTP(SITE) ftp.set_debuglevel(DEBUG) ftp.login(USER, PASSWD) ftp.cwd(DIR) filelist = ftp.nlst() filecounter = MANAGER.counter(total=len(filelist), desc='Downloading', unit='files') for filename in filelist: with Writer(filename, ftp.size(filename), DEST) as writer: ftp.retrbinary('RETR %s' % filename, writer.write) print(filename) filecounter.update() ftp.close()
def download()
Download all files from an FTP share
3.733722
3.515347
1.062121
self.fileobj.write(block) self.status.update(len(block))
def write(self, block)
Write to local file and update progress bar
6.582901
4.568313
1.440992
with enlighten.Manager() as manager: with manager.counter(total=SPLINES, desc='Reticulating:', unit='splines') as retic: for num in range(SPLINES): # pylint: disable=unused-variable time.sleep(random.uniform(0.1, 0.5)) # Random processing time retic.update() with manager.counter(total=LLAMAS, desc='Herding:', unit='llamas') as herd: for num in range(SPLINES): # pylint: disable=unused-variable time.sleep(random.uniform(0.1, 0.5)) # Random processing time herd.update()
def process_files()
Use Manager and Counter as context managers
3.575188
3.358598
1.064488
with io.open(filename, encoding=encoding) as sourcecode: for line in sourcecode: version = RE_VERSION.match(line) if version: return version.group(1) return None
def get_version(filename, encoding='utf8')
Get __version__ definition out of a source file
3.053578
3.03926
1.004711
with io.open(filename, encoding=encoding) as source: return source.read()
def readme(filename, encoding='utf8')
Read the contents of a file
3.725224
5.118334
0.72782
filesize = os.stat(filename).st_size if filesize: sys.stdout.write('Misspelled Words:\n') with io.open(filename, encoding=encoding) as wordlist: for line in wordlist: sys.stdout.write(' ' + line) return 1 if filesize else 0
def print_spelling_errors(filename, encoding='utf8')
Print misspelled words returned by sphinxcontrib-spelling
3.248869
3.23433
1.004495
# Simulated preparation pbar = manager.counter(total=initials, desc='Initializing:', unit='initials') for num in range(initials): # pylint: disable=unused-variable time.sleep(random.uniform(0.1, 0.5)) # Random processing time pbar.update() pbar.close()
def initialize(manager, initials=15)
Simple progress bar example
4.774447
4.422461
1.079591
manager = enlighten.get_manager() initialize(manager, 15) load(manager, 80) run_tests(manager, 40) process_files(manager) manager.stop() # Clears all temporary counters and progress bars time.sleep(3)
def main()
Main function
10.815252
10.799357
1.001472
stream = stream or sys.stdout isatty = hasattr(stream, 'isatty') and stream.isatty() kwargs['enabled'] = isatty and kwargs.get('enabled', True) return Manager(stream=stream, counterclass=counterclass, **kwargs)
def get_manager(stream=None, counterclass=Counter, **kwargs)
Args: stream(:py:term:`file object`): Output stream. If :py:data:`None`, defaults to :py:data:`sys.stdout` counter_class(:py:term:`class`): Progress bar class (Default: :py:class:`Counter`) kwargs(dict): Any additional :py:term:`keyword arguments<keyword argument>` will passed to the manager class. Returns: :py:class:`Manager`: Manager instance Convenience function to get a manager instance If ``stream`` is not attached to a TTY, the :py:class:`Manager` instance is disabled.
2.57498
2.778427
0.926776
for key, val in self.defaults.items(): if key not in kwargs: kwargs[key] = val kwargs['manager'] = self counter = self.counter_class(**kwargs) if position is None: toRefresh = [] if self.counters: pos = 2 for cter in reversed(self.counters): if self.counters[cter] < pos: toRefresh.append(cter) cter.clear(flush=False) self.counters[cter] = pos pos += 1 self.counters[counter] = 1 self._set_scroll_area() for cter in reversed(toRefresh): cter.refresh(flush=False) self.stream.flush() elif position in self.counters.values(): raise ValueError('Counter position %d is already occupied.' % position) elif position > self.height: raise ValueError('Counter position %d is greater than terminal height.' % position) else: self.counters[counter] = position return counter
def counter(self, position=None, **kwargs)
Args: position(int): Line number counting from the bottom of the screen kwargs(dict): Any additional :py:term:`keyword arguments<keyword argument>` are passed to :py:class:`Counter` Returns: :py:class:`Counter`: Instance of counter class Get a new progress bar instance If ``position`` is specified, the counter's position can change dynamically if additional counters are called without a ``position`` argument.
3.49951
3.400225
1.029199
assert self.resize_lock except AssertionError: self.resize_lock = True term = self.term term.clear_cache() newHeight = term.height newWidth = term.width lastHeight = lastWidth = 0 while newHeight != lastHeight or newWidth != lastWidth: lastHeight = newHeight lastWidth = newWidth time.sleep(.2) term.clear_cache() newHeight = term.height newWidth = term.width if newWidth < self.width: offset = (self.scroll_offset - 1) * (1 + self.width // newWidth) term.move_to(0, max(0, newHeight - offset)) self.stream.write(term.clear_eos) self.width = newWidth self._set_scroll_area(force=True) for cter in self.counters: cter.refresh(flush=False) self.stream.flush() self.resize_lock = False
def _resize_handler(self, *args, **kwarg): # pylint: disable=unused-argument # Make sure only one resize handler is running try
Called when a window resize signal is detected Resets the scroll window
4.066381
4.155388
0.97858
# Save scroll offset for resizing oldOffset = self.scroll_offset self.scroll_offset = newOffset = max(self.counters.values()) + 1 if not self.enabled: return # Set exit handling only once if not self.process_exit: atexit.register(self._at_exit) if not self.no_resize and RESIZE_SUPPORTED: signal.signal(signal.SIGWINCH, self._resize_handler) self.process_exit = True if self.set_scroll: term = self.term newHeight = term.height scrollPosition = max(0, newHeight - newOffset) if force or newOffset > oldOffset or newHeight != self.height: self.height = newHeight # Add line feeds so we don't overwrite existing output if newOffset - oldOffset > 0: term.move_to(0, max(0, newHeight - oldOffset)) self.stream.write('\n' * (newOffset - oldOffset)) # Reset scroll area self.term.change_scroll(scrollPosition) # Always reset position term.move_to(0, scrollPosition) if self.companion_term: self.companion_term.move_to(0, scrollPosition)
def _set_scroll_area(self, force=False)
Args: force(bool): Set the scroll area even if no change in height and position is detected Sets the scroll window based on the counter positions
4.847734
4.713205
1.028543
if self.process_exit: try: term = self.term if self.set_scroll: term.reset() else: term.move_to(0, term.height) self.term.feed() except ValueError: # Possibly closed file handles pass
def _at_exit(self)
Resets terminal to normal configuration
9.568307
8.741894
1.094535
if self.enabled: term = self.term stream = self.stream positions = self.counters.values() if not self.no_resize and RESIZE_SUPPORTED: signal.signal(signal.SIGWINCH, self.sigwinch_orig) try: for num in range(self.scroll_offset - 1, 0, -1): if num not in positions: term.move_to(0, term.height - num) stream.write(term.clear_eol) stream.flush() finally: if self.set_scroll: self.term.reset() if self.companion_term: self.companion_term.reset() else: term.move_to(0, term.height) self.process_exit = False self.enabled = False for cter in self.counters: cter.enabled = False # Feed terminal if lowest position isn't cleared if 1 in positions: term.feed()
def stop(self)
Clean up and reset terminal This method should be called when the manager and counters will no longer be needed. Any progress bars that have ``leave`` set to :py:data:`True` or have not been closed will remain on the console. All others will be cleared. Manager and all counters will be disabled.
5.858943
5.496691
1.065904
if self.enabled: term = self.term stream = self.stream try: term.move_to(0, term.height - position) # Include \r and term call to cover most conditions if NEEDS_UNICODE_HELP: # pragma: no cover (Version dependent 2.6) encoding = stream.encoding or 'UTF-8' stream.write(('\r' + term.clear_eol + output).encode(encoding)) else: # pragma: no cover (Version dependent >= 2.7) stream.write('\r' + term.clear_eol + output) finally: # Reset position and scrolling self._set_scroll_area() if flush: stream.flush()
def write(self, output='', flush=True, position=0)
Args: output(str: Output string flush(bool): Flush the output stream after writing position(int): Position relative to the bottom of the screen to write output Write to stream at a given position
6.384001
6.41677
0.994893
# Always do minutes and seconds in mm:ss format minutes = seconds // 60 hours = minutes // 60 rtn = u'{0:02.0f}:{1:02.0f}'.format(minutes % 60, seconds % 60) # Add hours if there are any if hours: rtn = u'{0:d}h {1}'.format(int(hours % 24), rtn) # Add days if there are any days = int(hours // 24) if days: rtn = u'{0:d}d {1}'.format(days, rtn) return rtn
def _format_time(seconds)
Args: seconds (float): amount of time Format time string for eta and elapsed
2.784911
2.830608
0.983856
if self.color is None: return content if self._color and self._color[0] == self.color: return self._color[1](content) if self.color in COLORS: spec = getattr(self.manager.term, self.color) else: spec = self.manager.term.color(self.color) self._color = (self.color, spec) return spec(content)
def _colorize(self, content)
Args: content(str): Color as a string or number 0 - 255 (Default: None) Returns: :py:class:`str`: content formatted with color Format ``content`` with the color specified for this progress bar If no color is specified for this instance, the content is returned unmodified The color discovery within this method is caching to improve performance
3.485507
3.089096
1.128326
self.count += incr self.parent.update(incr, force)
def update(self, incr=1, force=False)
Args: incr(int): Amount to increment ``count`` (Default: 1) force(bool): Force refresh even if ``min_delta`` has not been reached Increment progress bar and redraw Both this counter and the parent are incremented. Progress bar is only redrawn if min_delta seconds past since the last update on the parent.
9.385905
5.240402
1.791066
# Make sure source is a parent or peer if source is self.parent or getattr(source, 'parent', None) is self.parent: if self.count + incr < 0 or source.count - incr < 0: raise ValueError('Invalid increment: %s' % incr) if source is self.parent: if self.parent.count - self.parent.subcount - incr < 0: raise ValueError('Invalid increment: %s' % incr) else: source.count -= incr self.count += incr self.parent.update(0, force) else: raise ValueError('source must be parent or peer')
def update_from(self, source, incr=1, force=False)
Args: source(:py:class:`SubCounter`): :py:class:`SubCounter` or :py:class:`Counter` to increment from incr(int): Amount to increment ``count`` (Default: 1) force(bool): Force refresh even if ``min_delta`` has not been reached Move a value to this counter from another counter. ``source`` must be the parent :py:class:`Counter` instance or a :py:class:`SubCounter` with the same parent
3.670932
3.607832
1.01749
# Clock stops running when total is reached if self.count == self.total: elapsed = self.last_update - self.start else: elapsed = time.time() - self.start return elapsed
def elapsed(self)
Get elapsed time is seconds (float)
7.504732
6.354336
1.181041
if self.enabled: self.manager.write(flush=flush, position=self.position)
def clear(self, flush=True)
Args: flush(bool): Flush stream after clearing progress bar (Default:True) Clear progress bar
11.503092
13.254638
0.867854
if clear and not self.leave: self.clear() else: self.refresh() self.manager.remove(self)
def close(self, clear=False)
Do final refresh and remove from manager If ``leave`` is True, the default, the effect is the same as :py:meth:`refresh`.
7.611193
4.97271
1.530593
fields = {} subcounters = [] for num, subcounter in enumerate(self._subcounters, 1): if self.total: subPercentage = subcounter.count / float(self.total) else: subPercentage = 0.0 # Save in tuple: count, percentage, color subcounters.append((subcounter, subPercentage)) # Set fields fields['percentage_{0}'.format(num)] = subPercentage * 100 fields['count_{0}'.format(num)] = subcounter.count if subcounter.all_fields: interations = abs(subcounter.count - subcounter.start_count) if elapsed: # Use float to force to float in Python 2 rate = fields['rate_{0}'.format(num)] = interations / float(elapsed) else: rate = fields['rate_{0}'.format(num)] = 0.0 if self.total == 0: fields['eta_{0}'.format(num)] = u'00:00' elif rate: fields['eta_{0}'.format(num)] = _format_time((self.total - interations) / rate) else: fields['eta_{0}'.format(num)] = u'?' return subcounters, fields
def _get_subcounters(self, elapsed)
Args: elapsed(float): Time since started. Returns: :py:class:`tuple`: list of subcounters and dictionary of additional fields Each subcounter in the list will be in a tuple of (subcounter, percentage) Fields in the dictionary are addressed in the Format documentation of this class
3.490476
3.354206
1.040627
width = width or self.manager.width iterations = abs(self.count - self.start_count) fields = {'bar': u'{0}', 'count': self.count, 'desc': self.desc or u'', 'total': self.total, 'unit': self.unit or u'', 'desc_pad': u' ' if self.desc else u'', 'unit_pad': u' ' if self.unit else u''} # Get elapsed time if elapsed is None: elapsed = self.elapsed fields['elapsed'] = _format_time(elapsed) # Get rate. Elapsed could be 0 if counter was not updated and has a zero total. if elapsed: # Use iterations so a counter running backwards is accurate fields['rate'] = iterations / elapsed else: fields['rate'] = 0.0 # Only process bar if total was given and n doesn't exceed total if self.total is not None and self.count <= self.total: fields['len_total'] = len(str(self.total)) # Get percentage if self.total == 0: # If total is 0, force to 100 percent percentage = 1 fields['eta'] = u'00:00' else: # Use float to force to float in Python 2 percentage = self.count / float(self.total) # Get eta if fields['rate']: # Use iterations so a counter running backwards is accurate fields['eta'] = _format_time((self.total - iterations) / fields['rate']) else: fields['eta'] = u'?' fields['percentage'] = percentage * 100 # Have to go through subcounters here so the fields are available subcounters, subFields = self._get_subcounters(elapsed) # Calculate count and percentage for remainder if subcounters: fields.update(subFields) fields['count_0'] = self.count - sum(sub[0].count for sub in subcounters) fields['percentage_0'] = (percentage - sum(sub[1] for sub in subcounters)) * 100 # Partially format rtn = self.bar_format.format(**fields) # Format the bar barWidth = width - len(rtn) + self.offset + 3 # 3 is for the bar placeholder complete = barWidth * percentage barLen = int(complete) barText = u'' subOffset = 0 for subcounter, subPercentage in reversed(subcounters): subLen = int(barWidth * subPercentage) # pylint: disable=protected-access barText += subcounter._colorize(self.series[-1] * subLen) subOffset += subLen barText += self.series[-1] * (barLen - subOffset) if barLen < barWidth: barText += self.series[int(round((complete - barLen) * (len(self.series) - 1)))] barText += self.series[0] * (barWidth - barLen - 1) return rtn.format(self._colorize(barText)) # Otherwise return a counter fields['fill'] = u'{0}' rtn = self.counter_format.format(**fields) return rtn.format(u' ' * (width - len(rtn) + self.offset + 3))
def format(self, width=None, elapsed=None)
Args: width (int): Width in columns to make progress bar elapsed(float): Time since started. Automatically determined if :py:data:`None` Returns: :py:class:`str`: Formatted progress bar or counter Format progress bar or counter
3.997903
3.920027
1.019866
if self.enabled: self.manager.write(output=self.format(elapsed=elapsed), flush=flush, position=self.position)
def refresh(self, flush=True, elapsed=None)
Args: flush(bool): Flush stream after writing progress bar (Default:True) elapsed(float): Time since started. Automatically determined if :py:data:`None` Redraw progress bar
8.525968
9.173417
0.929421
self.count += incr if self.enabled: currentTime = time.time() # Update if force, 100%, or minimum delta has been reached if force or self.count == self.total or \ currentTime - self.last_update >= self.min_delta: self.last_update = currentTime self.refresh(elapsed=currentTime - self.start)
def update(self, incr=1, force=False)
Args: incr(int): Amount to increment ``count`` (Default: 1) force(bool): Force refresh even if ``min_delta`` has not been reached Increment progress bar and redraw Progress bar is only redrawn if ``min_delta`` seconds past since the last update
5.646006
4.54727
1.241625
subcounter = SubCounter(self, color=color, count=count, all_fields=all_fields) self._subcounters.append(subcounter) return subcounter
def add_subcounter(self, color, count=0, all_fields=False)
Args: color(str): Series color as a string or integer see :ref:`Series Color <series_color>` count(int): Initial count (Default: 0) all_fields(bool): Populate ``rate`` and ``eta`` formatting fields (Default: False) Returns: :py:class:`SubCounter`: Subcounter instance Add a subcounter for multicolored progress bars
2.382094
3.58415
0.664619
# Get a top level progress bar enterprise = manager.counter(total=DATACENTERS, desc='Processing:', unit='datacenters') # Iterate through data centers for dnum in range(1, DATACENTERS + 1): systems = random.randint(*SYSTEMS) # Random number of systems # Get a child progress bar. leave is False so it can be replaced currCenter = manager.counter(total=systems, desc=' Datacenter %d:' % dnum, unit='systems', leave=False) # Iterate through systems for snum in range(1, systems + 1): # Has no total, so will act as counter. Leave is False system = manager.counter(desc=' System %d:' % snum, unit='files', leave=False) files = random.randint(*FILES) # Random file count # Iterate through files for fnum in range(files): # pylint: disable=unused-variable system.update() # Update count time.sleep(random.uniform(0.0001, 0.0005)) # Random processing time system.close() # Close counter so it gets removed # Log status LOGGER.info('Updated %d files on System %d in Datacenter %d', files, snum, dnum) currCenter.update() # Update count currCenter.close() # Close counter so it gets removed enterprise.update() # Update count enterprise.close()
def process_files(manager)
Process a random number of files on a random number of systems across multiple data centers
4.651668
4.24742
1.095175
with enlighten.Counter(total=100, desc='Simple', unit='ticks') as pbar: for num in range(100): # pylint: disable=unused-variable time.sleep(0.05) pbar.update()
def process_files()
Process files with a single progress bar
4.948991
4.136228
1.196499
pb_connecting = manager.counter(total=units, desc='Loading', unit='services', color='red', bar_format=BAR_FMT) pb_loading = pb_connecting.add_subcounter('yellow') pb_loaded = pb_connecting.add_subcounter('green', all_fields=True) connecting = [] loading = [] loaded = [] count = 0 while pb_loaded.count < units: time.sleep(random.uniform(0.05, 0.15)) # Random processing time for idx, node in enumerate(loading): if node.loaded: loading.pop(idx) loaded.append(node) LOGGER.info('Service %d loaded', node.iden) pb_loaded.update_from(pb_loading) for idx, node in enumerate(connecting): if node.connected: connecting.pop(idx) node.load() loading.append(node) LOGGER.info('Service %d connected', node.iden) pb_loading.update_from(pb_connecting) # Connect to up to 5 units at a time for _ in range(0, min(units - count, 5 - len(connecting))): node = Node(count) node.connect() connecting.append(node) LOGGER.info('Connection to service %d', node.iden) pb_connecting.update() count += 1
def load(manager, units=80)
Simulate loading services from a remote node States are connecting (red), loading(yellow), and loaded (green)
3.600684
3.275332
1.099334
value = getattr(self, variable) if value is None: return False if value is True: return True if random.randint(1, num) == num: setattr(self, variable, True) return True return False
def _state(self, variable, num)
Generic method to randomly determine if state is reached
3.829702
3.249222
1.178652
pbar = enlighten.Counter(total=count, desc='Simple', unit='ticks', bar_format=BAR_FMT, counter_format=COUNTER_FMT) for num in range(100): # pylint: disable=unused-variable time.sleep(0.05) pbar.update(1.1)
def process_files(count=None)
Process files with a single progress bar
5.802391
5.308958
1.092943
self.stream.write(self.normal_cursor) self.stream.write(self.csr(0, self.height)) self.stream.write(self.move(self.height, 0))
def reset(self)
Reset scroll window and cursor to default
6.644414
4.79637
1.385301
self.stream.write(self.hide_cursor) self.stream.write(self.csr(0, position)) self.stream.write(self.move(position, 0))
def change_scroll(self, position)
Args: position (int): Vertical location to end scroll window Change scroll window
5.760587
5.857982
0.983374
self.stream.write(self.move(ypos, xpos))
def move_to(self, xpos, ypos)
Move cursor to specified position
12.928288
11.264468
1.147705
try: return self._cache['height_and_width'] except KeyError: handw = self._cache['height_and_width'] = super(Terminal, self)._height_and_width() return handw
def _height_and_width(self)
Override for blessings.Terminal._height_and_width Adds caching
5.715716
3.780308
1.511971
'''Capture locals, module name, filename, and line number from the stacktrace to provide the source of the assertion error and formatted note. ''' stack = traceback.walk_stack(sys._getframe().f_back) # We want locals from the test definition (which always begins # with 'test_' in unittest), which will be at a different # level in the stack depending on how many tests are in each # test case, how many test cases there are, etc. # The branch where we exhaust this loop is not covered # because we always find a test. for frame, _ in stack: # pragma: no branch code = frame.f_code if code.co_name.startswith('test_'): return (frame.f_locals.copy(), frame.f_globals['__name__'], code.co_filename, frame.f_lineno)
def get_stack_info()
Capture locals, module name, filename, and line number from the stacktrace to provide the source of the assertion error and formatted note.
7.678405
4.72991
1.623372
'''Fail if ``obj`` is not between ``lower`` and ``upper``. If ``strict=True`` (default), fail unless ``lower < obj < upper``. If ``strict=False``, fail unless ``lower <= obj <= upper``. This is equivalent to ``self.assertTrue(lower < obj < upper)`` or ``self.assertTrue(lower <= obj <= upper)``, but with a nicer default message. Parameters ---------- obj lower upper strict : bool msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. ''' if strict: standardMsg = '%s is not strictly between %s and %s' % ( obj, lower, upper) op = operator.lt else: standardMsg = '%s is not between %s and %s' % (obj, lower, upper) op = operator.le if not (op(lower, obj) and op(obj, upper)): self.fail(self._formatMessage(msg, standardMsg))
def assertBetween(self, obj, lower, upper, strict=True, msg=None)
Fail if ``obj`` is not between ``lower`` and ``upper``. If ``strict=True`` (default), fail unless ``lower < obj < upper``. If ``strict=False``, fail unless ``lower <= obj <= upper``. This is equivalent to ``self.assertTrue(lower < obj < upper)`` or ``self.assertTrue(lower <= obj <= upper)``, but with a nicer default message. Parameters ---------- obj lower upper strict : bool msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used.
2.669611
1.545575
1.72726
'''Fail if ``sequence`` is not monotonically increasing. If ``strict=True`` (default), fail unless each element in ``sequence`` is less than the following element as determined by the ``<`` operator. If ``strict=False``, fail unless each element in ``sequence`` is less than or equal to the following element as determined by the ``<=`` operator. .. code-block:: python assert all((i < j) for i, j in zip(sequence, sequence[1:])) assert all((i <= j) for i, j in zip(sequence, sequence[1:])) Parameters ---------- sequence : iterable strict : bool msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``sequence`` is not iterable. ''' if not isinstance(sequence, collections.Iterable): raise TypeError('First argument is not iterable') if strict: standardMsg = ('Elements in %s are not strictly monotonically ' 'increasing') % (sequence,) op = operator.lt else: standardMsg = ('Elements in %s are not monotonically ' 'increasing') % (sequence,) op = operator.le if not self._monotonic(op, sequence): self.fail(self._formatMessage(msg, standardMsg))
def assertMonotonicIncreasing(self, sequence, strict=True, msg=None)
Fail if ``sequence`` is not monotonically increasing. If ``strict=True`` (default), fail unless each element in ``sequence`` is less than the following element as determined by the ``<`` operator. If ``strict=False``, fail unless each element in ``sequence`` is less than or equal to the following element as determined by the ``<=`` operator. .. code-block:: python assert all((i < j) for i, j in zip(sequence, sequence[1:])) assert all((i <= j) for i, j in zip(sequence, sequence[1:])) Parameters ---------- sequence : iterable strict : bool msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``sequence`` is not iterable.
2.57686
1.604229
1.606292
'''Fail if ``sequence`` is monotonically decreasing. If ``strict=True`` (default), fail if each element in ``sequence`` is greater than the following element as determined by the ``>`` operator. If ``strict=False``, fail if each element in ``sequence`` is greater than or equal to the following element as determined by the ``>=`` operator. .. code-block:: python assert not all((i > j) for i, j in zip(sequence, sequence[1:])) assert not all((i >= j) for i, j in zip(sequence, sequence[1:])) Parameters ---------- sequence : iterable strict : bool msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``sequence`` is not iterable. ''' if not isinstance(sequence, collections.Iterable): raise TypeError('First argument is not iterable') if strict: standardMsg = ('Elements in %s are strictly monotonically ' 'decreasing') % (sequence,) op = operator.gt else: standardMsg = ('Elements in %s are monotonically ' 'decreasing') % (sequence,) op = operator.ge if self._monotonic(op, sequence): self.fail(self._formatMessage(msg, standardMsg))
def assertNotMonotonicDecreasing(self, sequence, strict=True, msg=None)
Fail if ``sequence`` is monotonically decreasing. If ``strict=True`` (default), fail if each element in ``sequence`` is greater than the following element as determined by the ``>`` operator. If ``strict=False``, fail if each element in ``sequence`` is greater than or equal to the following element as determined by the ``>=`` operator. .. code-block:: python assert not all((i > j) for i, j in zip(sequence, sequence[1:])) assert not all((i >= j) for i, j in zip(sequence, sequence[1:])) Parameters ---------- sequence : iterable strict : bool msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``sequence`` is not iterable.
2.691819
1.608763
1.673223
'''Fail if elements in ``container`` are not unique. Parameters ---------- container : iterable msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``container`` is not iterable. ''' if not isinstance(container, collections.Iterable): raise TypeError('First argument is not iterable') standardMsg = 'Elements in %s are not unique' % (container,) # We iterate over each element in the container instead of # comparing len(container) == len(set(container)) to allow # for containers that contain unhashable types for idx, elem in enumerate(container): # If elem appears at an earlier or later index position # the elements are not unique if elem in container[:idx] or elem in container[idx+1:]: self.fail(self._formatMessage(msg, standardMsg))
def assertUnique(self, container, msg=None)
Fail if elements in ``container`` are not unique. Parameters ---------- container : iterable msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``container`` is not iterable.
4.274814
2.972276
1.438229
'''If ``filename`` is a string or bytes object, open the ``filename`` and return the file object. If ``filename`` is file-like (i.e., it has 'read' and 'write' attributes, return ``filename``. Parameters ---------- filename : str, bytes, file Raises ------ TypeError If ``filename`` is not a string, bytes, or file-like object. File-likeness is determined by checking for 'read' and 'write' attributes. ''' if isinstance(filename, (str, bytes)): f = open(filename) elif hasattr(filename, 'read') and hasattr(filename, 'write'): f = filename else: raise TypeError('filename must be str or bytes, or a file') return f
def _get_or_open_file(filename)
If ``filename`` is a string or bytes object, open the ``filename`` and return the file object. If ``filename`` is file-like (i.e., it has 'read' and 'write' attributes, return ``filename``. Parameters ---------- filename : str, bytes, file Raises ------ TypeError If ``filename`` is not a string, bytes, or file-like object. File-likeness is determined by checking for 'read' and 'write' attributes.
3.381946
1.572956
2.150058
'''Fail if ``filename`` does not exist as determined by ``os.path.isfile(filename)``. Parameters ---------- filename : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. ''' standardMsg = '%s does not exist' % filename if not os.path.isfile(filename): self.fail(self._formatMessage(msg, standardMsg))
def assertFileExists(self, filename, msg=None)
Fail if ``filename`` does not exist as determined by ``os.path.isfile(filename)``. Parameters ---------- filename : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used.
4.836887
2.027187
2.38601
'''Fail if ``filename`` does not have the given ``name`` as determined by the ``==`` operator. Parameters ---------- filename : str, bytes, file-like name : str, byes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' fname = self._get_file_name(filename) self.assertEqual(fname, name, msg=msg)
def assertFileNameEqual(self, filename, name, msg=None)
Fail if ``filename`` does not have the given ``name`` as determined by the ``==`` operator. Parameters ---------- filename : str, bytes, file-like name : str, byes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like.
5.211449
1.689125
3.085295
'''Fail if ``filename`` has the given ``name`` as determined by the ``!=`` operator. Parameters ---------- filename : str, bytes, file-like name : str, byes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' fname = self._get_file_name(filename) self.assertNotEqual(fname, name, msg=msg)
def assertFileNameNotEqual(self, filename, name, msg=None)
Fail if ``filename`` has the given ``name`` as determined by the ``!=`` operator. Parameters ---------- filename : str, bytes, file-like name : str, byes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like.
5.256299
1.70738
3.078577
'''Fail unless ``filename`` matches ``expected_regex``. Parameters ---------- filename : str, bytes, file-like expected_regex : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' fname = self._get_file_name(filename) self.assertRegex(fname, expected_regex, msg=msg)
def assertFileNameRegex(self, filename, expected_regex, msg=None)
Fail unless ``filename`` matches ``expected_regex``. Parameters ---------- filename : str, bytes, file-like expected_regex : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like.
4.330366
1.733763
2.497669
'''Fail if ``filename`` matches ``expected_regex``. Parameters ---------- filename : str, bytes, file-like expected_regex : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' fname = self._get_file_name(filename) self.assertNotRegex(fname, expected_regex, msg=msg)
def assertFileNameNotRegex(self, filename, expected_regex, msg=None)
Fail if ``filename`` matches ``expected_regex``. Parameters ---------- filename : str, bytes, file-like expected_regex : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like.
4.321646
1.760243
2.455142
'''Fail if ``filename`` does not have the given ``extension`` as determined by the ``==`` operator. Parameters ---------- filename : str, bytes, file-like extension : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' ftype = self._get_file_type(filename) self.assertEqual(ftype, extension, msg=msg)
def assertFileTypeEqual(self, filename, extension, msg=None)
Fail if ``filename`` does not have the given ``extension`` as determined by the ``==`` operator. Parameters ---------- filename : str, bytes, file-like extension : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like.
4.885047
1.715544
2.847521
'''Fail if ``filename`` has the given ``extension`` as determined by the ``!=`` operator. Parameters ---------- filename : str, bytes, file-like extension : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' ftype = self._get_file_type(filename) self.assertNotEqual(ftype, extension, msg=msg)
def assertFileTypeNotEqual(self, filename, extension, msg=None)
Fail if ``filename`` has the given ``extension`` as determined by the ``!=`` operator. Parameters ---------- filename : str, bytes, file-like extension : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like.
5.072291
1.753645
2.892428
'''Fail if ``filename`` is not encoded with the given ``encoding`` as determined by the '==' operator. Parameters ---------- filename : str, bytes, file-like encoding : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' fencoding = self._get_file_encoding(filename) fname = self._get_file_name(filename) standardMsg = '%s is not %s encoded' % (fname, encoding) self.assertEqual(fencoding.lower(), encoding.lower(), self._formatMessage(msg, standardMsg))
def assertFileEncodingEqual(self, filename, encoding, msg=None)
Fail if ``filename`` is not encoded with the given ``encoding`` as determined by the '==' operator. Parameters ---------- filename : str, bytes, file-like encoding : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like.
4.644382
2.087678
2.224664
'''Fail if ``filename`` is encoded with the given ``encoding`` as determined by the '!=' operator. Parameters ---------- filename : str, bytes, file-like encoding : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' fencoding = self._get_file_encoding(filename) fname = self._get_file_name(filename) standardMsg = '%s is %s encoded' % (fname, encoding) self.assertNotEqual(fencoding.lower(), encoding.lower(), self._formatMessage(msg, standardMsg))
def assertFileEncodingNotEqual(self, filename, encoding, msg=None)
Fail if ``filename`` is encoded with the given ``encoding`` as determined by the '!=' operator. Parameters ---------- filename : str, bytes, file-like encoding : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like.
4.858863
2.135895
2.27486
'''Fail if ``filename`` does not have the given ``size`` as determined by the '==' operator. Parameters ---------- filename : str, bytes, file-like size : int, float msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' fsize = self._get_file_size(filename) self.assertEqual(fsize, size, msg=msg)
def assertFileSizeEqual(self, filename, size, msg=None)
Fail if ``filename`` does not have the given ``size`` as determined by the '==' operator. Parameters ---------- filename : str, bytes, file-like size : int, float msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like.
5.162169
1.674822
3.082219
'''Fail if ``filename`` has the given ``size`` as determined by the '!=' operator. Parameters ---------- filename : str, bytes, file-like size : int, float msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' fsize = self._get_file_size(filename) self.assertNotEqual(fsize, size, msg=msg)
def assertFileSizeNotEqual(self, filename, size, msg=None)
Fail if ``filename`` has the given ``size`` as determined by the '!=' operator. Parameters ---------- filename : str, bytes, file-like size : int, float msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like.
5.35629
1.732124
3.092326
'''Fail if ``filename`` does not have the given ``size`` as determined by their difference rounded to the given number of decimal ``places`` (default 7) and comparing to zero, or if their difference is greater than a given ``delta``. Parameters ---------- filename : str, bytes, file-like size : int, float places : int msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. delta : int, float Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' fsize = self._get_file_size(filename) self.assertAlmostEqual( fsize, size, places=places, msg=msg, delta=delta)
def assertFileSizeAlmostEqual( self, filename, size, places=None, msg=None, delta=None)
Fail if ``filename`` does not have the given ``size`` as determined by their difference rounded to the given number of decimal ``places`` (default 7) and comparing to zero, or if their difference is greater than a given ``delta``. Parameters ---------- filename : str, bytes, file-like size : int, float places : int msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. delta : int, float Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like.
4.239718
1.5102
2.807389
'''Fail unless ``filename`` does not have the given ``size`` as determined by their difference rounded to the given number ofdecimal ``places`` (default 7) and comparing to zero, or if their difference is greater than a given ``delta``. Parameters ---------- filename : str, bytes, file-like size : int, float places : int msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. delta : int, float Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' fsize = self._get_file_size(filename) self.assertNotAlmostEqual( fsize, size, places=places, msg=msg, delta=delta)
def assertFileSizeNotAlmostEqual( self, filename, size, places=None, msg=None, delta=None)
Fail unless ``filename`` does not have the given ``size`` as determined by their difference rounded to the given number ofdecimal ``places`` (default 7) and comparing to zero, or if their difference is greater than a given ``delta``. Parameters ---------- filename : str, bytes, file-like size : int, float places : int msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. delta : int, float Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like.
4.63483
1.516972
3.055316
'''Fail if ``filename``'s size is not greater than ``size`` as determined by the '>' operator. Parameters ---------- filename : str, bytes, file-like size : int, float msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' fsize = self._get_file_size(filename) self.assertGreater(fsize, size, msg=msg)
def assertFileSizeGreater(self, filename, size, msg=None)
Fail if ``filename``'s size is not greater than ``size`` as determined by the '>' operator. Parameters ---------- filename : str, bytes, file-like size : int, float msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like.
4.681837
1.699448
2.754916
'''Fail if ``filename``'s size is not greater than or equal to ``size`` as determined by the '>=' operator. Parameters ---------- filename : str, bytes, file-like size : int, float msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' fsize = self._get_file_size(filename) self.assertGreaterEqual(fsize, size, msg=msg)
def assertFileSizeGreaterEqual(self, filename, size, msg=None)
Fail if ``filename``'s size is not greater than or equal to ``size`` as determined by the '>=' operator. Parameters ---------- filename : str, bytes, file-like size : int, float msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like.
4.636314
1.68073
2.758513
'''Fail if ``filename``'s size is not less than ``size`` as determined by the '<' operator. Parameters ---------- filename : str, bytes, file-like size : int, float msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' fsize = self._get_file_size(filename) self.assertLess(fsize, size, msg=msg)
def assertFileSizeLess(self, filename, size, msg=None)
Fail if ``filename``'s size is not less than ``size`` as determined by the '<' operator. Parameters ---------- filename : str, bytes, file-like size : int, float msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like.
4.789204
1.695026
2.825446
'''Fail if ``filename``'s size is not less than or equal to ``size`` as determined by the '<=' operator. Parameters ---------- filename : str, bytes, file-like size : int, float msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like. ''' fsize = self._get_file_size(filename) self.assertLessEqual(fsize, size, msg=msg)
def assertFileSizeLessEqual(self, filename, size, msg=None)
Fail if ``filename``'s size is not less than or equal to ``size`` as determined by the '<=' operator. Parameters ---------- filename : str, bytes, file-like size : int, float msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``filename`` is not a str or bytes object and is not file-like.
4.527374
1.686104
2.68511
'''Fail if ``levels1`` and ``levels2`` do not have the same domain. Parameters ---------- levels1 : iterable levels2 : iterable msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If either ``levels1`` or ``levels2`` is not iterable. ''' if not isinstance(levels1, collections.Iterable): raise TypeError('First argument is not iterable') if not isinstance(levels2, collections.Iterable): raise TypeError('Second argument is not iterable') standardMsg = '%s levels != %s levels' % (levels1, levels2) if not all(level in levels2 for level in levels1): self.fail(self._formatMessage(msg, standardMsg)) if not all(level in levels1 for level in levels2): self.fail(self._formatMessage(msg, standardMsg))
def assertCategoricalLevelsEqual(self, levels1, levels2, msg=None)
Fail if ``levels1`` and ``levels2`` do not have the same domain. Parameters ---------- levels1 : iterable levels2 : iterable msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If either ``levels1`` or ``levels2`` is not iterable.
2.633651
1.699843
1.549349
'''Fail if ``levels1`` and ``levels2`` have the same domain. Parameters ---------- levels1 : iterable levels2 : iterable msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If either ``levels1`` or ``levels2`` is not iterable. ''' if not isinstance(levels1, collections.Iterable): raise TypeError('First argument is not iterable') if not isinstance(levels2, collections.Iterable): raise TypeError('Second argument is not iterable') standardMsg = '%s levels == %s levels' % (levels1, levels2) unshared_levels = False if not all(level in levels2 for level in levels1): unshared_levels = True if not all(level in levels1 for level in levels2): unshared_levels = True if not unshared_levels: self.fail(self._formatMessage(msg, standardMsg))
def assertCategoricalLevelsNotEqual(self, levels1, levels2, msg=None)
Fail if ``levels1`` and ``levels2`` have the same domain. Parameters ---------- levels1 : iterable levels2 : iterable msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If either ``levels1`` or ``levels2`` is not iterable.
2.873913
1.939226
1.48199
'''Fail if ``level`` is not in ``levels``. This is equivalent to ``self.assertIn(level, levels)``. Parameters ---------- level levels : iterable msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``levels`` is not iterable. ''' if not isinstance(levels, collections.Iterable): raise TypeError('Second argument is not iterable') self.assertIn(level, levels, msg=msg)
def assertCategoricalLevelIn(self, level, levels, msg=None)
Fail if ``level`` is not in ``levels``. This is equivalent to ``self.assertIn(level, levels)``. Parameters ---------- level levels : iterable msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``levels`` is not iterable.
3.861754
1.902853
2.029455
'''Fail if ``level`` is in ``levels``. This is equivalent to ``self.assertNotIn(level, levels)``. Parameters ---------- level levels : iterable msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``levels`` is not iterable. ''' if not isinstance(levels, collections.Iterable): raise TypeError('Second argument is not iterable') self.assertNotIn(level, levels, msg=msg)
def assertCategoricalLevelNotIn(self, level, levels, msg=None)
Fail if ``level`` is in ``levels``. This is equivalent to ``self.assertNotIn(level, levels)``. Parameters ---------- level levels : iterable msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``levels`` is not iterable.
3.784996
1.862874
2.031805
'''Fail if any elements in ``sequence`` are not before ``target``. If ``target`` is iterable, it must have the same length as ``sequence`` If ``strict=True``, fail unless all elements in ``sequence`` are strictly less than ``target``. If ``strict=False``, fail unless all elements in ``sequence`` are less than or equal to ``target``. Parameters ---------- sequence : iterable target : datetime, date, iterable strict : bool msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``sequence`` is not iterable. ValueError If ``target`` is iterable but does not have the same length as ``sequence``. TypeError If ``target`` is not a datetime or date object and is not iterable. ''' if not isinstance(sequence, collections.Iterable): raise TypeError('First argument is not iterable') if strict: standardMsg = '%s is not strictly less than %s' % (sequence, target) op = operator.lt else: standardMsg = '%s is not less than %s' % (sequence, target) op = operator.le # Null date(time)s will always compare False, but # we want to know about null date(time)s if isinstance(target, collections.Iterable): if len(target) != len(sequence): raise ValueError(('Length mismatch: ' 'first argument contains %s elements, ' 'second argument contains %s elements' % ( len(sequence), len(target)))) if not all(op(i, j) for i, j in zip(sequence, target)): self.fail(self._formatMessage(msg, standardMsg)) elif isinstance(target, (date, datetime)): if not all(op(element, target) for element in sequence): self.fail(self._formatMessage(msg, standardMsg)) else: raise TypeError( 'Second argument is not a datetime or date object or iterable')
def assertDateTimesBefore(self, sequence, target, strict=True, msg=None)
Fail if any elements in ``sequence`` are not before ``target``. If ``target`` is iterable, it must have the same length as ``sequence`` If ``strict=True``, fail unless all elements in ``sequence`` are strictly less than ``target``. If ``strict=False``, fail unless all elements in ``sequence`` are less than or equal to ``target``. Parameters ---------- sequence : iterable target : datetime, date, iterable strict : bool msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``sequence`` is not iterable. ValueError If ``target`` is iterable but does not have the same length as ``sequence``. TypeError If ``target`` is not a datetime or date object and is not iterable.
2.67872
1.807768
1.481784
'''Fail if any elements in ``sequence`` are not in the past. If the max element is a datetime, "past" is defined as anything prior to ``datetime.now()``; if the max element is a date, "past" is defined as anything prior to ``date.today()``. If ``strict=True``, fail unless all elements in ``sequence`` are strictly less than ``date.today()`` (or ``datetime.now()``). If ``strict=False``, fail unless all elements in ``sequence`` are less than or equal to ``date.today()`` (or ``datetime.now()``). Parameters ---------- sequence : iterable strict : bool msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``sequence`` is not iterable. TypeError If max element in ``sequence`` is not a datetime or date object. ''' if not isinstance(sequence, collections.Iterable): raise TypeError('First argument is not iterable') # Cannot compare datetime to date, so if dates are provided use # date.today(), if datetimes are provided use datetime.today() if isinstance(max(sequence), datetime): target = datetime.today() elif isinstance(max(sequence), date): target = date.today() else: raise TypeError('Expected iterable of datetime or date objects') self.assertDateTimesBefore(sequence, target, strict=strict, msg=msg)
def assertDateTimesPast(self, sequence, strict=True, msg=None)
Fail if any elements in ``sequence`` are not in the past. If the max element is a datetime, "past" is defined as anything prior to ``datetime.now()``; if the max element is a date, "past" is defined as anything prior to ``date.today()``. If ``strict=True``, fail unless all elements in ``sequence`` are strictly less than ``date.today()`` (or ``datetime.now()``). If ``strict=False``, fail unless all elements in ``sequence`` are less than or equal to ``date.today()`` (or ``datetime.now()``). Parameters ---------- sequence : iterable strict : bool msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``sequence`` is not iterable. TypeError If max element in ``sequence`` is not a datetime or date object.
3.215503
1.674235
1.92058
'''Fail if any elements in ``sequence`` are not in the future. If the min element is a datetime, "future" is defined as anything after ``datetime.now()``; if the min element is a date, "future" is defined as anything after ``date.today()``. If ``strict=True``, fail unless all elements in ``sequence`` are strictly greater than ``date.today()`` (or ``datetime.now()``). If ``strict=False``, fail all elements in ``sequence`` are greater than or equal to ``date.today()`` (or ``datetime.now()``). Parameters ---------- sequence : iterable strict : bool msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``sequence`` is not iterable. TypeError If min element in ``sequence`` is not a datetime or date object. ''' if not isinstance(sequence, collections.Iterable): raise TypeError('First argument is not iterable') # Cannot compare datetime to date, so if dates are provided use # date.today(), if datetimes are provided use datetime.today() if isinstance(min(sequence), datetime): target = datetime.today() elif isinstance(min(sequence), date): target = date.today() else: raise TypeError('Expected iterable of datetime or date objects') self.assertDateTimesAfter(sequence, target, strict=strict, msg=msg)
def assertDateTimesFuture(self, sequence, strict=True, msg=None)
Fail if any elements in ``sequence`` are not in the future. If the min element is a datetime, "future" is defined as anything after ``datetime.now()``; if the min element is a date, "future" is defined as anything after ``date.today()``. If ``strict=True``, fail unless all elements in ``sequence`` are strictly greater than ``date.today()`` (or ``datetime.now()``). If ``strict=False``, fail all elements in ``sequence`` are greater than or equal to ``date.today()`` (or ``datetime.now()``). Parameters ---------- sequence : iterable strict : bool msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``sequence`` is not iterable. TypeError If min element in ``sequence`` is not a datetime or date object.
3.457873
1.683526
2.053947
'''Fail if any elements in ``sequence`` aren't separated by the expected ``fequency``. Parameters ---------- sequence : iterable frequency : timedelta msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``sequence`` is not iterable. TypeError If ``frequency`` is not a timedelta object. ''' # TODO (jsa): check that elements in sequence are dates or # datetimes, keeping in mind that sequence may contain null # values if not isinstance(sequence, collections.Iterable): raise TypeError('First argument is not iterable') if not isinstance(frequency, timedelta): raise TypeError('Second argument is not a timedelta object') standardMsg = 'unexpected frequencies found in %s' % sequence s1 = pd.Series(sequence) s2 = s1.shift(-1) freq = s2 - s1 if not all(f == frequency for f in freq[:-1]): self.fail(self._formatMessage(msg, standardMsg))
def assertDateTimesFrequencyEqual(self, sequence, frequency, msg=None)
Fail if any elements in ``sequence`` aren't separated by the expected ``fequency``. Parameters ---------- sequence : iterable frequency : timedelta msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``sequence`` is not iterable. TypeError If ``frequency`` is not a timedelta object.
4.822483
2.781729
1.733628
'''Fail unless max element in ``sequence`` is separated from the present by ``lag`` as determined by the '==' operator. If the max element is a datetime, "present" is defined as ``datetime.now()``; if the max element is a date, "present" is defined as ``date.today()``. This is equivalent to ``self.assertEqual(present - max(sequence), lag)``. Parameters ---------- sequence : iterable lag : timedelta msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``sequence`` is not iterable. TypeError If ``lag`` is not a timedelta object. TypeError If max element in ``sequence`` is not a datetime or date object. ''' if not isinstance(sequence, collections.Iterable): raise TypeError('First argument is not iterable') if not isinstance(lag, timedelta): raise TypeError('Second argument is not a timedelta object') # Cannot compare datetime to date, so if dates are provided use # date.today(), if datetimes are provided use datetime.today() if isinstance(max(sequence), datetime): target = datetime.today() elif isinstance(max(sequence), date): target = date.today() else: raise TypeError('Expected iterable of datetime or date objects') self.assertEqual(target - max(sequence), lag, msg=msg)
def assertDateTimesLagEqual(self, sequence, lag, msg=None)
Fail unless max element in ``sequence`` is separated from the present by ``lag`` as determined by the '==' operator. If the max element is a datetime, "present" is defined as ``datetime.now()``; if the max element is a date, "present" is defined as ``date.today()``. This is equivalent to ``self.assertEqual(present - max(sequence), lag)``. Parameters ---------- sequence : iterable lag : timedelta msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``sequence`` is not iterable. TypeError If ``lag`` is not a timedelta object. TypeError If max element in ``sequence`` is not a datetime or date object.
3.708205
1.695533
2.187044
'''Fail if max element in ``sequence`` is separated from the present by ``lag`` or more as determined by the '<' operator. If the max element is a datetime, "present" is defined as ``datetime.now()``; if the max element is a date, "present" is defined as ``date.today()``. This is equivalent to ``self.assertLess(present - max(sequence), lag)``. Parameters ---------- sequence : iterable lag : timedelta msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``sequence`` is not iterable. TypeError If ``lag`` is not a timedelta object. TypeError If max element in ``sequence`` is not a datetime or date object. ''' if not isinstance(sequence, collections.Iterable): raise TypeError('First argument is not iterable') if not isinstance(lag, timedelta): raise TypeError('Second argument is not a timedelta object') # Cannot compare datetime to date, so if dates are provided use # date.today(), if datetimes are provided use datetime.today() if isinstance(max(sequence), datetime): target = datetime.today() elif isinstance(max(sequence), date): target = date.today() else: raise TypeError('Expected iterable of datetime or date objects') self.assertLess(target - max(sequence), lag, msg=msg)
def assertDateTimesLagLess(self, sequence, lag, msg=None)
Fail if max element in ``sequence`` is separated from the present by ``lag`` or more as determined by the '<' operator. If the max element is a datetime, "present" is defined as ``datetime.now()``; if the max element is a date, "present" is defined as ``date.today()``. This is equivalent to ``self.assertLess(present - max(sequence), lag)``. Parameters ---------- sequence : iterable lag : timedelta msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``sequence`` is not iterable. TypeError If ``lag`` is not a timedelta object. TypeError If max element in ``sequence`` is not a datetime or date object.
3.654718
1.689882
2.162706