Search is not available for this dataset
text
stringlengths
75
104k
def _glob_to_regexp(pat): """Compile a glob pattern into a regexp. We need to do this because fnmatch allows * to match /, which we don't want. E.g. an MANIFEST.in exclude of 'dirname/*css' should match 'dirname/foo.css' but not 'dirname/subdir/bar.css'. """ pat = fnmatch.translate(pat) # ...
def file_matches(filename, patterns): """Does this filename match any of the patterns?""" return any(fnmatch.fnmatch(filename, pat) for pat in patterns)
def get_versioned_files(): """List all files versioned by git in the current directory.""" # Git for Windows uses UTF-8 instead of the locale encoding. # Regular Git on sane POSIX systems uses the locale encoding encoding = 'UTF-8' if sys.platform == 'win32' else None output = ru...
def start_kernel(self, **kwargs): """Start a new kernel.""" kernel_id = unicode(uuid.uuid4()) # use base KernelManager for each Kernel km = self.kernel_manager_factory(connection_file=os.path.join( self.connection_dir, "kernel-%s.json" % kernel_id), ...
def shutdown_kernel(self, kernel_id): """Shutdown a kernel by its kernel uuid. Parameters ========== kernel_id : uuid The id of the kernel to shutdown. """ self.get_kernel(kernel_id).shutdown_kernel() del self._kernels[kernel_id]
def kill_kernel(self, kernel_id): """Kill a kernel by its kernel uuid. Parameters ========== kernel_id : uuid The id of the kernel to kill. """ self.get_kernel(kernel_id).kill_kernel() del self._kernels[kernel_id]
def get_kernel(self, kernel_id): """Get the single KernelManager object for a kernel by its uuid. Parameters ========== kernel_id : uuid The id of the kernel. """ km = self._kernels.get(kernel_id) if km is not None: return km else:...
def get_kernel_ports(self, kernel_id): """Return a dictionary of ports for a kernel. Parameters ========== kernel_id : uuid The id of the kernel. Returns ======= port_dict : dict A dict of key, value pairs where the keys are the names ...
def notebook_for_kernel(self, kernel_id): """Return the notebook_id for a kernel_id or None.""" notebook_ids = [k for k, v in self._notebook_mapping.iteritems() if v == kernel_id] if len(notebook_ids) == 1: return notebook_ids[0] else: return None
def delete_mapping_for_kernel(self, kernel_id): """Remove the kernel/notebook mapping for kernel_id.""" notebook_id = self.notebook_for_kernel(kernel_id) if notebook_id is not None: del self._notebook_mapping[notebook_id]
def start_kernel(self, notebook_id=None, **kwargs): """Start a kernel for a notebok an return its kernel_id. Parameters ---------- notebook_id : uuid The uuid of the notebook to associate the new kernel with. If this is not None, this kernel will be persistent wh...
def shutdown_kernel(self, kernel_id): """Shutdown a kernel and remove its notebook association.""" self._check_kernel_id(kernel_id) super(MappingKernelManager, self).shutdown_kernel(kernel_id) self.delete_mapping_for_kernel(kernel_id) self.log.info("Kernel shutdown: %s" % kernel_...
def interrupt_kernel(self, kernel_id): """Interrupt a kernel.""" self._check_kernel_id(kernel_id) super(MappingKernelManager, self).interrupt_kernel(kernel_id) self.log.info("Kernel interrupted: %s" % kernel_id)
def restart_kernel(self, kernel_id): """Restart a kernel while keeping clients connected.""" self._check_kernel_id(kernel_id) km = self.get_kernel(kernel_id) km.restart_kernel() self.log.info("Kernel restarted: %s" % kernel_id) return kernel_id # the foll...
def create_iopub_stream(self, kernel_id): """Create a new iopub stream.""" self._check_kernel_id(kernel_id) return super(MappingKernelManager, self).create_iopub_stream(kernel_id)
def create_shell_stream(self, kernel_id): """Create a new shell stream.""" self._check_kernel_id(kernel_id) return super(MappingKernelManager, self).create_shell_stream(kernel_id)
def create_hb_stream(self, kernel_id): """Create a new hb stream.""" self._check_kernel_id(kernel_id) return super(MappingKernelManager, self).create_hb_stream(kernel_id)
def configure(self, options, conf): """Configure plugin. """ if not self.can_configure: return self.conf = conf disable = getattr(options, 'noDeprecated', False) if disable: self.enabled = False
def reset(self): """Reset all OneTimeProperty attributes that may have fired already.""" instdict = self.__dict__ classdict = self.__class__.__dict__ # To reset them, we simply remove them from the instance dict. At that # point, it's as if they had never been computed. On the next acces...
def iseq(start=0, stop=None, inc=1): """ Generate integers from start to (and including!) stop, with increment of inc. Alternative to range/xrange. """ if stop is None: # allow isequence(3) to be 0, 1, 2, 3 # take 1st arg as stop, start as 0, and inc=1 stop = start; start = 0; inc = ...
def export_html(html, filename, image_tag = None, inline = True): """ Export the contents of the ConsoleWidget as HTML. Parameters: ----------- html : str, A utf-8 encoded Python string containing the Qt HTML to export. filename : str The file to be saved. image_tag : callable...
def export_xhtml(html, filename, image_tag=None): """ Export the contents of the ConsoleWidget as XHTML with inline SVGs. Parameters: ----------- html : str, A utf-8 encoded Python string containing the Qt HTML to export. filename : str The file to be saved. image_tag : callab...
def ensure_utf8(image_tag): """wrapper for ensuring image_tag returns utf8-encoded str on Python 2""" if py3compat.PY3: # nothing to do on Python 3 return image_tag def utf8_image_tag(*args, **kwargs): s = image_tag(*args, **kwargs) if isinstance(s, unicode): ...
def fix_html(html): """ Transforms a Qt-generated HTML string into a standards-compliant one. Parameters: ----------- html : str, A utf-8 encoded Python string containing the Qt HTML. """ # A UTF-8 declaration is needed for proper rendering of some characters # (e.g., indented comma...
def export(self): """ Displays a dialog for exporting HTML generated by Qt's rich text system. Returns ------- The name of the file that was saved, or None if no file was saved. """ parent = self.control.window() dialog = QtGui.QFileDialog(parent, 'Save a...
def get_unique_or_none(klass, *args, **kwargs): """ Returns a unique instance of `klass` or None """ try: return klass.objects.get(*args, **kwargs) except klass.DoesNotExist: return None except klass.MultipleObjectsReturned: return None return None
def get_or_create_unique(klass, defaults, unique_fields): """ Returns a tuple of (instance, created), where `instance` is the retrieved or created instance of `klass` and `created` is a boolean specifying whether a new object was created. The value for the unique fields must be present in the defaul...
def get_text_tokenizer(query_string): """ Tokenize the input string and return two lists, exclude list is for words that start with a dash (ex: -word) and include list is for all other words """ # Regex to split on double-quotes, single-quotes, and continuous non-whitespace characters. split_pat...
def get_query_includes(tokenized_terms, search_fields): """ Builds a query for included terms in a text search. """ query = None for term in tokenized_terms: or_query = None for field_name in search_fields: q = Q(**{"%s__icontains" % field_name: term}) if or_q...
def get_text_query(query_string, search_fields): """ Builds a query for both included & excluded terms in a text search. """ include_terms, exclude_terms = get_text_tokenizer(query_string) include_q = get_query_includes(include_terms, search_fields) exclude_q = get_query_excludes(exclude_terms, ...
def get_date_greater_query(days, date_field): """ Query for if date_field is within number of "days" ago. """ query = None days = get_integer(days) if days: past = get_days_ago(days) query = Q(**{"%s__gte" % date_field: past.isoformat()}) return query
def get_date_less_query(days, date_field): """ Query for if date_field is within number of "days" from now. """ query = None days = get_integer(days) if days: future = get_days_from_now(days) query = Q(**{"%s__lte" % date_field: future.isoformat()}) return query
def get_null_or_blank_query(field=None): """ Query for null or blank field. """ if not field: return field null_q = get_null_query(field) blank_q = get_blank_query(field) return (null_q | blank_q)
def case_insensitive(self, fields_dict): """ Converts queries to case insensitive for special fields. """ if hasattr(self.model, 'CASE_INSENSITIVE_FIELDS'): for field in self.model.CASE_INSENSITIVE_FIELDS: if field in fields_dict: fields_di...
def attr(*args, **kwargs): """Decorator that adds attributes to classes or functions for use with the Attribute (-a) plugin. """ def wrap_ob(ob): for name in args: setattr(ob, name, True) for name, value in kwargs.iteritems(): setattr(ob, name, value) retu...
def get_method_attr(method, cls, attr_name, default = False): """Look up an attribute on a method/ function. If the attribute isn't found there, looking it up in the method's class, if any. """ Missing = object() value = getattr(method, attr_name, Missing) if value is Missing and cls is not...
def options(self, parser, env): """Register command line options""" parser.add_option("-a", "--attr", dest="attr", action="append", default=env.get('NOSE_ATTR'), metavar="ATTR", help="Run only tests t...
def configure(self, options, config): """Configure the plugin and system, based on selected options. attr and eval_attr may each be lists. self.attribs will be a list of lists of tuples. In that list, each list is a group of attributes, all of which must match for the rule to m...
def validateAttrib(self, method, cls = None): """Verify whether a method has the required attributes The method is considered a match if it matches all attributes for any attribute group. .""" # TODO: is there a need for case-sensitive value comparison? any = False ...
def wantMethod(self, method): """Accept the method if its attributes match. """ try: cls = method.im_class except AttributeError: return False return self.validateAttrib(method, cls)
def rotate(self): """ Rotate the kill ring, then yank back the new top. """ if self._prev_yank: text = self._ring.rotate() if text: self._skip_cursor = True cursor = self._text_edit.textCursor() cursor.movePosition(QtGui.QTe...
def patch_pyzmq(): """backport a few patches from newer pyzmq These can be removed as we bump our minimum pyzmq version """ import zmq # ioloop.install, introduced in pyzmq 2.1.7 from zmq.eventloop import ioloop def install(): import tornado.ioloop tornado...
def version_from_schema(schema_el): """ returns: API version number <str> raises: <VersionNotFound> NOTE: relies on presence of comment tags in the XSD, which are currently present for both ebaySvc.xsd (TradingAPI) and ShoppingService.xsd (ShoppingAPI) """ vc_el = schema_el while Tr...
def _default_ns_prefix(nsmap): """ XML doc may have several prefix:namespace_url pairs, can also specify a namespace_url as default, tags in that namespace don't need a prefix NOTE: we rely on default namespace also present in prefixed form, I'm not sure if this is an XML certainty or a quirk of...
def version_from_wsdl(wsdl_tree): """ returns: API version number <str> raises: <VersionNotFound> NOTE: relies on presence of documentation node in the WSDLs: <wsdl:documentation> <Version>1.0.0</Version> </wsdl:documentation> """ prefix = _default_ns_prefix(wsdl...
def parser_from_schema(schema_url, require_version=True): """ Returns an XSD-schema-enabled lxml parser from a WSDL or XSD `schema_url` can of course be local path via file:// url """ schema_tree = etree.parse(schema_url) def get_version(element, getter): try: return getter...
def askQuestion(question, required = True, answers = dict(), tries = 3): """Ask a question to STDOUT and return answer from STDIN Args: question: A string question that will be printed to stdout Kwargs: required: True indicates the question must be answered answers: A seque...
def authenticate_unless_readonly(f, self, *args, **kwargs): """authenticate this page *unless* readonly view is active. In read-only mode, the notebook list and print view should be accessible without authentication. """ @web.authenticated def auth_f(self, *args, **kwargs): ret...
def ws_url(self): """websocket url matching the current request turns http[s]://host[:port] into ws[s]://host[:port] """ proto = self.request.protocol.replace('http', 'ws') host = self.application.ipython_app.websocket_host # default to config value if ho...
def _reserialize_reply(self, msg_list): """Reserialize a reply message using JSON. This takes the msg list from the ZMQ socket, unserializes it using self.session and then serializes the result using JSON. This method should be used by self._on_zmq_reply to build messages that can ...
def _inject_cookie_message(self, msg): """Inject the first message, which is the document cookie, for authentication.""" if isinstance(msg, unicode): # Cookie can't constructor doesn't accept unicode strings for some reason msg = msg.encode('utf8', 'replace') try:...
def start_hb(self, callback): """Start the heartbeating and call the callback if the kernel dies.""" if not self._beating: self._kernel_alive = True def ping_or_dead(): self.hb_stream.flush() if self._kernel_alive: self._kernel...
def _really_start_hb(self): """callback for delayed heartbeat start Only start the hb loop if we haven't been closed during the wait. """ if self._beating and not self.hb_stream.closed(): self._hb_periodic_callback.start()
def stop_hb(self): """Stop the heartbeating and cancel all related callbacks.""" if self._beating: self._beating = False self._hb_periodic_callback.stop() if not self.hb_stream.closed(): self.hb_stream.on_recv(None)
def fload(self): """Load file object.""" # read data and parse into blocks if hasattr(self, 'fobj') and self.fobj is not None: self.fobj.close() if hasattr(self.src, "read"): # It seems to be a file or a file-like object self.fobj = self.src el...
def reload(self): """Reload source from disk and initialize state.""" self.fload() self.src = self.fobj.read() src_b = [b.strip() for b in self.re_stop.split(self.src) if b] self._silent = [bool(self.re_silent.findall(b)) for b in src_b] self._auto = [bool(s...
def _get_index(self,index): """Get the current block index, validating and checking status. Returns None if the demo is finished""" if index is None: if self.finished: print >>io.stdout, 'Demo finished. Use <demo_name>.reset() if you want to rerun it.' ...
def seek(self,index): """Move the current seek pointer to the given block. You can use negative indices to seek from the end, with identical semantics to those of Python lists.""" if index<0: index = self.nblocks + index self._validate_index(index) self.block...
def edit(self,index=None): """Edit a block. If no number is given, use the last block executed. This edits the in-memory copy of the demo, it does NOT modify the original source file. If you want to do that, simply open the file in an editor and use reload() when you make chan...
def show(self,index=None): """Show a single block on screen""" index = self._get_index(index) if index is None: return print >>io.stdout, self.marquee('<%s> block # %s (%s remaining)' % (self.title,index,self.nblocks-index-1)) print >>io.s...
def show_all(self): """Show entire demo on screen, block by block""" fname = self.title title = self.title nblocks = self.nblocks silent = self._silent marquee = self.marquee for index,block in enumerate(self.src_blocks_colored): if silent[index]: ...
def reload(self): """Reload source from disk and initialize state.""" # read data and parse into blocks self.fload() lines = self.fobj.readlines() src_b = [l for l in lines if l.strip()] nblocks = len(src_b) self.src = ''.join(li...
def series(collection, method, prints = 15, *args, **kwargs): ''' Processes a collection in series Parameters ---------- collection : list list of Record objects method : method to call on each Record prints : int number of timer prints to the screen Returns ------...
def batch(collection, method, processes=None, batch_size=None, quiet=False, kwargs_to_dump=None, args=None, **kwargs): '''Processes a collection in parallel batches, each batch processes in series on a single process. Running batches in parallel can be more effficient that splitting a list across...
def thread(function, sequence, cores=None, runSeries=False, quiet=False): '''sets up the threadpool with map for parallel processing''' # Make the Pool of workes if cores is None: pool = ThreadPool() else: pool = ThreadPool(cores) # Operate on the list of subjects with the requeste...
def parallel(collection, method, processes=None, args=None, **kwargs): '''Processes a collection in parallel. Parameters ---------- collection : list i.e. list of Record objects method : method to call on each Record processes : int number of processes to run on [defaults to num...
def install_mathjax(tag='v1.1', replace=False): """Download and install MathJax for offline use. This will install mathjax to the 'static' dir in the IPython notebook package, so it will fail if the caller does not have write access to that location. MathJax is a ~15MB download, and ~150MB...
def with_it(obj): ''' wrap `with obj` out of func. example: ``` py @with_it(Lock()) def func(): pass ``` ''' def _wrap(func): @functools.wraps(func) def wrapper(*args, **kwargs): with obj: return func(*args, **kwargs) return wr...
def with_objattr(name): ''' wrap `with getattr(self, name)` out of func. usage: ``` py class A: def __init__(self): self._lock = RLock() @with_objattr('_lock') # so easy to make a sync instance method ! def func(): pass ``` ''' def _wra...
def with_objattrs(*names): ''' like `with_objattr` but enter context one by one. ''' def _wrap(func): @functools.wraps(func) def wrapper(self, *args, **kwargs): with contextlib.ExitStack() as stack: for name in names: stack.enter_context(...
def inspect_traceback(tb): """Inspect a traceback and its frame, returning source for the expression where the exception was raised, with simple variable replacement performed and the line on which the exception was raised marked with '>>' """ log.debug('inspect traceback %s', tb) # we only wan...
def tbsource(tb, context=6): """Get source from a traceback object. A tuple of two things is returned: a list of lines of context from the source code, and the index of the current line within that list. The optional second argument specifies the number of lines of context to return, which are cen...
def find_inspectable_lines(lines, pos): """Find lines in home that are inspectable. Walk back from the err line up to 3 lines, but don't walk back over changes in indent level. Walk forward up to 3 lines, counting \ separated lines as 1. Don't walk over changes in indent level (unless part of ...
def countdown(name, date, description='', id='', granularity='sec', start=None, progressbar=False, progressbar_inversed=False, showpct=False): ''' Create a countdown. ''' end_date = dateparse.parse_datetime(date) end = dateformat.format(end_date, 'U') content = '<div class="name">' + name + ...
def cleanup(controller, engines): """Cleanup routine to shut down all subprocesses we opened.""" import signal, time print('Starting cleanup') print('Stopping engines...') for e in engines: e.send_signal(signal.SIGINT) print('Stopping controller...') # so it can shut down its qu...
def pre_call(self, ctxt, pre_mod, post_mod, action): """ A modifier hook function. This is called in priority order prior to invoking the ``Action`` for the step. This allows a modifier to alter the context, or to take over subsequent action invocation. :param ctxt: Th...
def post_call(self, ctxt, result, action, post_mod, pre_mod): """ A modifier hook function. This is called in reverse-priority order after invoking the ``Action`` for the step. This allows a modifier to inspect or alter the result of the step. :param ctxt: The context object. ...
def save_ids(f, self, *args, **kwargs): """Keep our history and outstanding attributes up to date after a method call.""" n_previous = len(self.client.history) try: ret = f(self, *args, **kwargs) finally: nmsgs = len(self.client.history) - n_previous msg_ids = self.client.history...
def sync_results(f, self, *args, **kwargs): """sync relevant results from self.client to our results attribute.""" ret = f(self, *args, **kwargs) delta = self.outstanding.difference(self.client.outstanding) completed = self.outstanding.intersection(delta) self.outstanding = self.outstanding.differen...
def spin_after(f, self, *args, **kwargs): """call spin after the method.""" ret = f(self, *args, **kwargs) self.spin() return ret
def add_record(self, msg_id, rec): """Add a new Task Record, by msg_id.""" # print rec rec = self._binary_buffers(rec) self._records.insert(rec)
def get_record(self, msg_id): """Get a specific Task Record, by msg_id.""" r = self._records.find_one({'msg_id': msg_id}) if not r: # r will be '' if nothing is found raise KeyError(msg_id) return r
def update_record(self, msg_id, rec): """Update the data in an existing record.""" rec = self._binary_buffers(rec) self._records.update({'msg_id':msg_id}, {'$set': rec})
def find_records(self, check, keys=None): """Find records matching a query dict, optionally extracting subset of keys. Returns list of matching records. Parameters ---------- check: dict mongodb-style query argument keys: list of str...
def get_history(self): """get all msg_ids, ordered by time submitted.""" cursor = self._records.find({},{'msg_id':1}).sort('submitted') return [ rec['msg_id'] for rec in cursor ]
def get_msgs(self): """Get all messages that are currently ready.""" msgs = [] while True: try: msgs.append(self.get_msg(block=False)) except Empty: break return msgs
def get_msg(self, block=True, timeout=None): "Gets a message if there is one that is ready." return self._in_queue.get(block, timeout)
def prop(func=None, *, field = _UNSET, get: bool = True, set: bool = True, del_: bool = False, default = _UNSET, types: tuple = _UNSET): ''' `prop` is a sugar for `property`. ``` py @prop def value(self): pass # equals: @property def value(s...
def get_onlys(*fields): ''' `get_onlys` is a sugar for multi-`property`. ``` py name, age = get_onlys('_name', '_age') # equals: @property def name(self): return getattr(self, '_name') @property def age(self): return getattr(self, '_age') ``` ''' retur...
def parse(url): """Parses a database URL.""" config = {} if not isinstance(url, six.string_types): url = '' url = urlparse.urlparse(url) # Remove query strings. path = url.path[1:] path = path.split('?', 2)[0] # Update with environment configuration. config.update({ ...
def module_list(path): """ Return the list containing the names of the modules available in the given folder. """ # sys.path has the cwd as an empty string, but isdir/listdir need it as '.' if path == '': path = '.' if os.path.isdir(path): folder_list = os.listdir(path) ...
def get_root_modules(): """ Returns a list containing the names of all the modules available in the folders of the pythonpath. """ ip = get_ipython() if 'rootmodules' in ip.db: return ip.db['rootmodules'] t = time() store = False modules = list(sys.builtin_module_names) ...
def quick_completer(cmd, completions): """ Easily create a trivial completer for a command. Takes either a list of completions, or all completions in string (that will be split on whitespace). Example:: [d:\ipython]|1> import ipy_completers [d:\ipython]|2> ipy_completers.quick_complet...
def module_completion(line): """ Returns a list containing the completion possibilities for an import line. The line looks like this : 'import xml.d' 'from xml.dom import' """ words = line.split(' ') nwords = len(words) # from whatever <tab> -> 'import ' if nwords == 3 and wor...
def magic_run_completer(self, event): """Complete files that end in .py or .ipy for the %run command. """ comps = arg_split(event.line, strict=False) relpath = (len(comps) > 1 and comps[-1] or '').strip("'\"") #print("\nev=", event) # dbg #print("rp=", relpath) # dbg #print('comps=', comp...
def cd_completer(self, event): """Completer function for cd, which only returns directories.""" ip = get_ipython() relpath = event.symbol #print(event) # dbg if event.line.endswith('-b') or ' -b ' in event.line: # return only bookmark completions bkms = self.db.get('bookmarks', None...
def interact(self): """This should call display(Javascript(jscode)).""" jscode = self.render() display(Javascript(data=jscode,lib=self.jslibs))
def _quoteattr(self, attr): """Escape an XML attribute. Value can be unicode.""" attr = xml_safe(attr) if isinstance(attr, unicode) and not UNICODE_STRINGS: attr = attr.encode(self.encoding) return saxutils.quoteattr(attr)
def configure(self, options, config): """Configures the xunit plugin.""" Plugin.configure(self, options, config) self.config = config if self.enabled: self.stats = {'errors': 0, 'failures': 0, 'passes': 0, ...
def report(self, stream): """Writes an Xunit-formatted XML file The file includes a report of test errors and failures. """ self.stats['encoding'] = self.encoding self.stats['total'] = (self.stats['errors'] + self.stats['failures'] + self.stats['p...