text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def maybe_coroutine(obj): """ If 'obj' is a coroutine and we're using Python3, wrap it in ensureDeferred. Otherwise return the original object. (This is to insert in all callback chains from user code, in case that user code is Python3 and used 'async def') """
if six.PY3 and asyncio.iscoroutine(obj): return defer.ensureDeferred(obj) return obj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_non_public_numeric_address(host): """ returns True if 'host' is not public """
# for numeric hostnames, skip RFC1918 addresses, since no Tor exit # node will be able to reach those. Likewise ignore IPv6 addresses. try: a = ipaddress.ip_address(six.text_type(host)) except ValueError: return False # non-numeric, let Tor try it if a.is_loopback or a.is_multicast or a.is_private or a.is_reserved \ or a.is_unspecified: return True # too weird, don't connect return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compute_permanent_id(private_key): """ Internal helper. Return an authenticated service's permanent ID given an RSA private key object. The permanent ID is the base32 encoding of the SHA1 hash of the first 10 bytes (80 bits) of the public key. """
pub = private_key.public_key() p = pub.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.PKCS1 ) z = ''.join(p.decode('ascii').strip().split('\n')[1:-1]) b = base64.b64decode(z) h1 = hashlib.new('sha1') h1.update(b) permanent_id = h1.digest()[:10] return base64.b32encode(permanent_id).lower().decode('ascii')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate_ports(reactor, ports): """ Internal helper for Onion services. Validates an incoming list of port mappings and returns a list of strings suitable for passing to other onion-services functions. Accepts 3 different ways of specifying ports: - list of ints: each int is the public port, local port random - list of 2-tuples of ints: (pubic, local) ports. - list of strings like "80 127.0.0.1:1234" This is async in case it needs to ask for a random, unallocated local port. """
if not isinstance(ports, (list, tuple)): raise ValueError("'ports' must be a list of strings, ints or 2-tuples") processed_ports = [] for port in ports: if isinstance(port, (set, list, tuple)): if len(port) != 2: raise ValueError( "'ports' must contain a single int or a 2-tuple of ints" ) remote, local = port try: remote = int(remote) except ValueError: raise ValueError( "'ports' has a tuple with a non-integer " "component: {}".format(port) ) try: local = int(local) except ValueError: if local.startswith('unix:/'): pass else: if ':' not in local: raise ValueError( "local port must be either an integer" " or start with unix:/ or be an IP:port" ) ip, port = local.split(':') if not _is_non_public_numeric_address(ip): log.msg( "'{}' used as onion port doesn't appear to be a " "local, numeric address".format(ip) ) processed_ports.append( "{} {}".format(remote, local) ) else: processed_ports.append( "{} 127.0.0.1:{}".format(remote, local) ) elif isinstance(port, (six.text_type, str)): _validate_single_port_string(port) processed_ports.append(port) else: try: remote = int(port) except (ValueError, TypeError): raise ValueError( "'ports' has a non-integer entry: {}".format(port) ) local = yield available_tcp_port(reactor) processed_ports.append( "{} 127.0.0.1:{}".format(remote, local) ) defer.returnValue(processed_ports)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle(self, data): """ return next state. May override in a subclass to change behavior or pass a handler method to ctor """
if self.handler: state = self.handler(data) if state is None: return self.next_state return state return self.next_state
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pldist(point, start, end): """ Calculates the distance from ``point`` to the line given by the points ``start`` and ``end``. :param point: a point :type point: numpy array :param start: a point of the line :type start: numpy array :param end: another point of the line :type end: numpy array """
if np.all(np.equal(start, end)): return np.linalg.norm(point - start) return np.divide( np.abs(np.linalg.norm(np.cross(end - start, start - point))), np.linalg.norm(end - start))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rdp(M, epsilon=0, dist=pldist, algo="iter", return_mask=False): """ Simplifies a given array of points using the Ramer-Douglas-Peucker algorithm. Example: [[1, 1], [4, 4]] This is a convenience wrapper around both :func:`rdp.rdp_iter` and :func:`rdp.rdp_rec` that detects if the input is a numpy array in order to adapt the output accordingly. This means that when it is called using a Python list as argument, a Python list is returned, and in case of an invocation using a numpy array, a NumPy array is returned. The parameter ``return_mask=True`` can be used in conjunction with ``algo="iter"`` to return only the mask of points to keep. Example: array([[1, 1], [2, 2], [3, 3], [4, 4]]) array([ True, False, False, True], dtype=bool) array([[1, 1], [4, 4]]) :param M: a series of points :type M: numpy array with shape ``(n,d)`` where ``n`` is the number of points and ``d`` their dimension :param epsilon: epsilon in the rdp algorithm :type epsilon: float :param dist: distance function :type dist: function with signature ``f(point, start, end)`` -- see :func:`rdp.pldist` :param algo: either ``iter`` for an iterative algorithm or ``rec`` for a recursive algorithm :type algo: string :param return_mask: return mask instead of simplified array :type return_mask: bool """
if algo == "iter": algo = partial(rdp_iter, return_mask=return_mask) elif algo == "rec": if return_mask: raise NotImplementedError("return_mask=True not supported with algo=\"rec\"") algo = rdp_rec if "numpy" in str(type(M)): return algo(M, epsilon, dist) return algo(np.array(M), epsilon, dist).tolist()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_start_scene(self, event: StartScene, signal: Callable[[Any], None]): """ Start a new scene. The current scene pauses. """
self.pause_scene() self.start_scene(event.new_scene, event.kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_stop_scene(self, event: events.StopScene, signal: Callable[[Any], None]): """ Stop a running scene. If there's a scene on the stack, it resumes. """
self.stop_scene() if self.current_scene is not None: signal(events.SceneContinued()) else: signal(events.Quit())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_replace_scene(self, event: events.ReplaceScene, signal): """ Replace the running scene with a new one. """
self.stop_scene() self.start_scene(event.new_scene, event.kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(self, event_type: Union[Type, _ellipsis], callback: Callable[[], Any]): """ Register a callback to be applied to an event at time of publishing. Primarily to be used by subsystems. The callback will receive the event. Your code should modify the event in place. It does not need to return it. :param event_type: The class of an event. :param callback: A callable, must accept an event, and return no value. :return: None """
if not isinstance(event_type, type) and event_type is not ...: raise TypeError(f"{type(self)}.register requires event_type to be a type.") if not callable(callback): raise TypeError(f"{type(self)}.register requires callback to be callable.") self.event_extensions[event_type].append(callback)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_index(): """ Rebuild _module_file_index from sys.modules """
global _module_file_index _module_file_index = { mod.__file__: mod.__name__ for mod in sys.modules.values() if hasattr(mod, '__file__') and hasattr(mod, '__name__') }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logger(self): """ The logger for this class. """
# This is internal/CPython only/etc # It's also astonishingly faster than alternatives. frame = sys._getframe(1) file_name = frame.f_code.co_filename module_name = _get_module(file_name) return logging.getLogger(module_name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pause(self): """ Pause the animation. """
if not self._pause_level: self._paused_time = self._clock() + self._offset self._paused_frame = self.current_frame self._pause_level += 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unpause(self): """ Unpause the animation. """
self._pause_level -= 1 if not self._pause_level: self._offset = self._paused_time - self._clock()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(setup: Callable[[BaseScene], None]=None, *, log_level=logging.WARNING, starting_scene=BaseScene): """ Run a small game. The resolution will 800 pixels wide by 600 pixels tall. setup is a callable that accepts a scene and returns None. log_level let's you set the expected log level. Consider logging.DEBUG if something is behaving oddly. starting_scene let's you change the scene used by the engine. """
logging.basicConfig(level=log_level) kwargs = { "resolution": (800, 600), "scene_kwargs": { "set_up": setup, } } with GameEngine(starting_scene, **kwargs) as eng: eng.run()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, game_object: Hashable, tags: Iterable[Hashable]=()) -> None: """ Add a game_object to the container. game_object: Any Hashable 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: container.add(MyObject()) container.add(MyObject(), tags=("red", "blue") """
if isinstance(tags, (str, bytes)): raise TypeError("You passed a string instead of an iterable, this probably isn't what you intended.\n\nTry making it a tuple.") self.all.add(game_object) for kind in type(game_object).mro(): self.kinds[kind].add(game_object) for tag in tags: self.tags[tag].add(game_object)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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") """
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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change(self) -> Tuple[bool, dict]: """ Default case, override in subclass as necessary. """
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}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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") """
self.game_objects.add(game_object, tags)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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") """
return self.game_objects.get(kind=kind, tag=tag, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def requirements(section=None): """Helper for loading dependencies from requirements files."""
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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_hash_key(self, file): """Calculate and store hash key for 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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('y1')), ])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 if _box_in_box(el, el2): return -1 return 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 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())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: # 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.annots) return layout
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 until we need to. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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') # 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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'] - attr['y0'] attr['width'] = attr['x1'] - attr['x0'] return attr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_bool(result, func, args): # pylint: disable=unused-argument """ Used as an error handler for Windows calls Gets last error if call is not successful """
if not result: raise ctypes.WinError(ctypes.get_last_error()) return args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_csbi(filehandle=None): """ Returns a CONSOLE_SCREEN_BUFFER_INFO structure for the given console or stdout """
if filehandle is None: filehandle = msvcrt.get_osfhandle(sys.__stdout__.fileno()) csbi = ConsoleScreenBufferInfo() KERNEL32.GetConsoleScreenBufferInfo(filehandle, ctypes.byref(csbi)) return csbi
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable_vt_mode(filehandle=None): """ Enables virtual terminal processing mode for the given console or stdout """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 """
def func(self, content=''): return self._apply_color(code, content) # pylint: disable=protected-access setattr(Terminal, color, func)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _apply_color(code, content): """ Apply a color code to text """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 """
def func(content=''): return self._apply_color(u'38;5;%d' % code, content) return func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download(): """ Download all files from an FTP share """
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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, block): """ Write to local file and update progress bar """
self.fileobj.write(block) self.status.update(len(block))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_files(): """ Use Manager and Counter as context managers """
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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_spelling_errors(filename, encoding='utf8'): """ Print misspelled words returned by sphinxcontrib-spelling """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initialize(manager, initials=15): """ Simple progress bar example """
# 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _resize_handler(self, *args, **kwarg): # pylint: disable=unused-argument """ Called when a window resize signal is detected Resets the scroll window """
# Make sure only one resize handler is running try: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _at_exit(self): """ Resets terminal to normal configuration """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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`. """
if clear and not self.leave: self.clear() else: self.refresh() self.manager.remove(self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_files(manager): """ Process a random number of files on a random number of systems across multiple data centers """
# 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _state(self, variable, num): """ Generic method to randomly determine if state is reached """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self): """ Reset scroll window and cursor to default """
self.stream.write(self.normal_cursor) self.stream.write(self.csr(0, self.height)) self.stream.write(self.move(self.height, 0))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move_to(self, xpos, ypos): """ Move cursor to specified position """
self.stream.write(self.move(ypos, xpos))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _height_and_width(self): """ Override for blessings.Terminal._height_and_width Adds caching """
try: return self._cache['height_and_width'] except KeyError: handw = self._cache['height_and_width'] = super(Terminal, self)._height_and_width() return handw
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' fname = self._get_file_name(filename) self.assertEqual(fname, name, msg=msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' fname = self._get_file_name(filename) self.assertNotEqual(fname, name, msg=msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' fname = self._get_file_name(filename) self.assertRegex(fname, expected_regex, msg=msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' fname = self._get_file_name(filename) self.assertNotRegex(fname, expected_regex, msg=msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' ftype = self._get_file_type(filename) self.assertEqual(ftype, extension, msg=msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' ftype = self._get_file_type(filename) self.assertNotEqual(ftype, extension, msg=msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' fsize = self._get_file_size(filename) self.assertEqual(fsize, size, msg=msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' fsize = self._get_file_size(filename) self.assertNotEqual(fsize, size, msg=msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' fsize = self._get_file_size(filename) self.assertGreater(fsize, size, msg=msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' fsize = self._get_file_size(filename) self.assertGreaterEqual(fsize, size, msg=msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' fsize = self._get_file_size(filename) self.assertLess(fsize, size, msg=msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' fsize = self._get_file_size(filename) self.assertLessEqual(fsize, size, msg=msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' if not isinstance(levels, collections.Iterable): raise TypeError('Second argument is not iterable') self.assertIn(level, levels, msg=msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' if not isinstance(levels, collections.Iterable): raise TypeError('Second argument is not iterable') self.assertNotIn(level, levels, msg=msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' 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')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' # 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def assertDateTimesLagLessEqual(self, sequence, lag, msg=None): '''Fail if max element in ``sequence`` is separated from the present by more than ``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.assertLessEqual(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.assertLessEqual(target - max(sequence), lag, msg=msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def assertTimeZoneIsNone(self, dt, msg=None): '''Fail if ``dt`` has a non-null ``tzinfo`` attribute. Parameters ---------- dt : datetime msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``dt`` is not a datetime object. ''' if not isinstance(dt, datetime): raise TypeError('First argument is not a datetime object') self.assertIsNone(dt.tzinfo, msg=msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def assertTimeZoneIsNotNone(self, dt, msg=None): '''Fail unless ``dt`` has a non-null ``tzinfo`` attribute. Parameters ---------- dt : datetime msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``dt`` is not a datetime object. ''' if not isinstance(dt, datetime): raise TypeError('First argument is not a datetime object') self.assertIsNotNone(dt.tzinfo, msg=msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def assertTimeZoneEqual(self, dt, tz, msg=None): '''Fail unless ``dt``'s ``tzinfo`` attribute equals ``tz`` as determined by the '==' operator. Parameters ---------- dt : datetime tz : timezone msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``dt`` is not a datetime object. TypeError If ``tz`` is not a timezone object. ''' if not isinstance(dt, datetime): raise TypeError('First argument is not a datetime object') if not isinstance(tz, timezone): raise TypeError('Second argument is not a timezone object') self.assertEqual(dt.tzinfo, tz, msg=msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def assertTimeZoneNotEqual(self, dt, tz, msg=None): '''Fail if ``dt``'s ``tzinfo`` attribute equals ``tz`` as determined by the '!=' operator. Parameters ---------- dt : datetime tz : timezone msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``dt`` is not a datetime object. TypeError If ``tz`` is not a timezone object. ''' if not isinstance(dt, datetime): raise TypeError('First argument is not a datetime object') if not isinstance(tz, timezone): raise TypeError('Second argument is not a timezone object') self.assertNotEqual(dt.tzinfo, tz, msg=msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _class_defining_method(meth): # pragma: no cover '''Gets the name of the class that defines meth. Adapted from http://stackoverflow.com/questions/3589311/get-defining-class-of-unbound-method-object-in-python-3/25959545#25959545. ''' if inspect.ismethod(meth): for cls in inspect.getmro(meth.__self__.__class__): if cls.__dict__.get(meth.__name__) is meth: return '{}.{}'.format(cls.__module__, cls.__name__) meth = meth.__func__ if inspect.isfunction(meth): module = meth.__qualname__.split('.<locals>', 1)[0] cls = getattr(inspect.getmodule(meth), module.rsplit('.', 1)[0]) if isinstance(cls, type): return '{}.{}'.format(cls.__module__, cls.__name__)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def configure(self, **kwargs): '''Configure what assertion logging is done. Settings configured with this method are overridden by environment variables. Parameters ---------- logfile : str or bytes or file object If a string or bytes object, we write to that filename. If an open file object, we just write to it. If None, disable logging. If we open the file, we open it in ``'w'`` mode, so any contents will be overwritten. attrs : list of str Capture these attributes on the TestCase being run when logging an assertion. For example, if you are testing multiple resources, make sure the resource name is a member of your TestCase, and configure marbles logging with that name. These are only captured on failure. verbose_attrs : list of str Similar to attrs, but these attrs are captured even on success. verbose : bool or list of str Fields (within the set {msg, note, locals}) to capture even when the test is successful. By default, those three fields are only captured on failure. ''' if 'logfile' in kwargs: # Note that kwargs['logfile'] might be an open file # object, not a string. We deal with this in # _open_if_needed, but refactoring it so that in that case # it gets set on another attribute would be tricky to # handle the lazy opening semantics that let us override # it with MARBLES_LOGFILE, so instead we choose to let # self._logfilename do double-duty: sometimes it's a name, # sometimes it's sneakily a file object. self._logfilename = kwargs['logfile'] if 'attrs' in kwargs: self._attrs = kwargs['attrs'] if 'verbose_attrs' in kwargs: self._verbose_attrs = kwargs['verbose_attrs'] if 'verbose' in kwargs: self._verbose = kwargs['verbose']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _find_msg_argument(signature): '''Locates the ``msg`` argument in a function signature. We need to determine where we expect to find ``msg`` if it's passed positionally, so we can extract it if the user passed it. Returns ------- tuple The index of the ``msg`` param, the default value for it, and the number of non-``msg`` positional parameters we expect. ''' names = signature.parameters.keys() try: msg_idx = list(names).index('msg') default_msg = signature.parameters['msg'].default except ValueError: # 'msg' is not in list # It's likely that this is a custom assertion that's just # passing all remaining args and kwargs through # (e.g. tests.marbles.ReversingTestCaseMixin). Unfortunately, # we can't inspect its code to find the assert it's wrapping, # so we just have to assume it's of the standard form with msg # in the last position with a default of None. msg_idx = -1 default_msg = None # We also don't want to steal any actually positional arguments if # we can help it. Therefore, we leave the default msg if there are # fewer than this many args passed. We stop counting at a # parameter named 'msg' or when we hit a varargs or keyword-only # parameter. kinds = (inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD) non_msg_params = itertools.takewhile( lambda param: param.name != 'msg' and param.kind in kinds, signature.parameters.values()) non_msg_params = sum(1 for _ in non_msg_params) return msg_idx, default_msg, non_msg_params
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _extract_msg(args, kwargs, msg_idx, default_msg, non_msg_params): '''Extracts the ``msg`` argument from the passed ``args``. Returns ------- tuple The found ``msg``, the args and kwargs with that ``msg`` removed, and any remaining positional args after ``msg``. ''' rem_args = [] if 'msg' in kwargs: msg = kwargs.pop('msg') elif len(args) > non_msg_params and msg_idx < len(args): msg = args[msg_idx] if 0 <= msg_idx: rem_args = args[msg_idx + 1:] args = args[:msg_idx] else: msg = default_msg return msg, args, rem_args, kwargs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def wrap(self, text, **kwargs): '''Wraps each paragraph in ``text`` individually. Parameters ---------- text : str Returns ------- str Single string containing the wrapped paragraphs. ''' pilcrow = re.compile(r'(\n\s*\n)', re.MULTILINE) list_prefix = re.compile(r'\s*(?:\w|[0-9]+)[\.\)]\s+') paragraphs = pilcrow.split(text) wrapped_lines = [] for paragraph in paragraphs: if paragraph.isspace(): wrapped_lines.append('') else: wrapper = textwrap.TextWrapper(**vars(self)) list_item = re.match(list_prefix, paragraph) if list_item: wrapper.subsequent_indent += ' ' * len(list_item.group(0)) wrapped_lines.extend(wrapper.wrap(paragraph)) return wrapped_lines
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def assert_stmt(self): '''Returns a string displaying the whole statement that failed, with a '>' indicator on the line starting the expression. ''' # This will be used by linecache to read the source of this # module. See the docstring for _find_assert_stmt below which # explains how. # We don't have a test for this because automating the # creation of an egg, installation into an environment, # running of tests, and verification that marbles found the # right source and was able to print it is a lot of # automation. We have tested manually, and marbles works with # all check installation mechanisms we know of right now # (setup.py install, setup.py develop, pip install, bdist_egg, # bdist_wheel). module_globals = vars(sys.modules[self.module]) line_range, lineno = self._find_assert_stmt( self.filename, self.linenumber, module_globals=module_globals) source = [linecache.getline(self.filename, x, module_globals=module_globals) for x in line_range] # Dedent the source, removing the final newline added by dedent dedented_lines = textwrap.dedent(''.join(source)).split('\n')[:-1] formatted_lines = [] for i, line in zip(line_range, dedented_lines): prefix = '>' if i == lineno else ' ' formatted_lines.append(' {0} {1:4d} {2}'.format(prefix, i, line)) return '\n'.join(formatted_lines)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _find_assert_stmt(filename, linenumber, leading=1, following=2, module_globals=None): '''Given a Python module name, filename and line number, find the lines that are part of the statement containing that line. Python stacktraces, when reporting which line they're on, always show the last line of the statement. This can be confusing if the statement spans multiple lines. This function helps reconstruct the whole statement, and is used by :meth:`marbles.core.ContextualAssertionError.assert_stmt`. Returns a tuple of the range of lines spanned by the source being returned, the number of the line on which the interesting statement starts. We may need the ``module_globals`` in order to tell :mod:`linecache` how to find the file, if it comes from inside an egg. In that case, ``module_globals`` should contain a key ``__loader__`` which knows how to read from that file. ''' lines = linecache.getlines( filename, module_globals=module_globals) _source = ''.join(lines) _tree = ast.parse(_source) finder = _StatementFinder(linenumber) finder.visit(_tree) line_range = range(finder.found - leading, linenumber + following) return line_range, finder.found
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _validate_annotation(self, annotation): '''Ensures that the annotation has the right fields.''' required_keys = set(self._required_keys) keys = set(key for key, val in annotation.items() if val) missing_keys = required_keys.difference(keys) if missing_keys: error = 'Annotation missing required fields: {0}'.format( missing_keys) raise AnnotationError(error)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _tchelper(tc_deps,evals,deps): """ modifies graph in place """
for e in evals: if e in tc_deps: # we've already included it continue else: if e in deps: # has additional dependnecies tc_deps[e]=deps[e] # add to tc_deps the dependencies of the dependencies _tchelper(tc_deps,deps[e],deps) return tc_deps
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, evals, feed_dict=None, breakpoints=None, break_immediately=False): """ starts the debug session """
if not isinstance(evals,list): evals=[evals] if feed_dict is None: feed_dict={} if breakpoints is None: breakpoints=[] self.state=RUNNING self._original_evals=evals self._original_feed_dict=feed_dict self._exe_order=op_store.compute_exe_order(evals) self._init_evals_bps(evals, breakpoints) # convert cache keys to strings for k,v in feed_dict.items(): if not isinstance(k,str): k=k.name self._cache[k]=v op_store.register_dbsession(self) if break_immediately: return self._break() else: return self.c()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def s(self): """ step to the next node in the execution order """
next_node=self._exe_order[self.step] self._eval(next_node) self.step+=1 if self.step==len(self._exe_order): return self._finish() else: # if stepping, return the value of the node we just # evaled return self._break(value=self._cache.get(next_node.name))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_value(self, node): """ retrieve a node value from the cache """
if isinstance(node,tf.Tensor): return self._cache.get(node.name,None) elif isinstance(node,tf.Operation): return None else: # handle ascii, unicode strings return self._cache.get(node,None)