INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
sync relevant results from self. client to our results attribute.
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...
call spin after the method.
def spin_after(f, self, *args, **kwargs): """call spin after the method.""" ret = f(self, *args, **kwargs) self.spin() return ret
Add a new Task Record by msg_id.
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)
Get a specific Task Record by msg_id.
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
Update the data in an existing record.
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})
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 strs [ optional ] if specified the subset of keys to extract. msg_id will * always * be included.
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...
get all msg_ids ordered by time submitted.
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 ]
Get all messages that are currently ready.
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
Gets a message if there is one that is ready.
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)
prop is a sugar for property.
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...
get_onlys is a sugar for multi - property.
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...
Parses a database URL.
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({ ...
Return the list containing the names of the modules available in the given folder.
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) ...
Returns a list containing the names of all the modules available in the folders of the pythonpath.
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) ...
Easily create a trivial completer for a command.
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...
Returns a list containing the completion possibilities for an import line.
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...
Complete files that end in. py or. ipy for the %run command.
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...
Completer function for cd which only returns directories.
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...
This should call display ( Javascript ( jscode )).
def interact(self): """This should call display(Javascript(jscode)).""" jscode = self.render() display(Javascript(data=jscode,lib=self.jslibs))
Escape an XML attribute. Value can be unicode.
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)
Configures the xunit plugin.
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, ...
Writes an Xunit - formatted XML file
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...
Add error output to Xunit report.
def addError(self, test, err, capt=None): """Add error output to Xunit report. """ taken = self._timeTaken() if issubclass(err[0], SkipTest): type = 'skipped' self.stats['skipped'] += 1 else: type = 'error' self.stats['errors'] += ...
Add failure output to Xunit report.
def addFailure(self, test, err, capt=None, tb_info=None): """Add failure output to Xunit report. """ taken = self._timeTaken() tb = ''.join(traceback.format_exception(*err)) self.stats['failures'] += 1 id = test.id() self.errorlist.append( '<testcase c...
Add success output to Xunit report.
def addSuccess(self, test, capt=None): """Add success output to Xunit report. """ taken = self._timeTaken() self.stats['passes'] += 1 id = test.id() self.errorlist.append( '<testcase classname=%(cls)s name=%(name)s ' 'time="%(taken).3f" />' % ...
Pick two at random use the LRU of the two.
def twobin(loads): """Pick two at random, use the LRU of the two. The content of loads is ignored. Assumes LRU ordering of loads, with oldest first. """ n = len(loads) a = randint(0,n-1) b = randint(0,n-1) return min(a,b)
Pick two at random using inverse load as weight.
def weighted(loads): """Pick two at random using inverse load as weight. Return the less loaded of the two. """ # weight 0 a million times more than 1: weights = 1./(1e-6+numpy.array(loads)) sums = weights.cumsum() t = sums[-1] x = random()*t y = random()*t idx = 0 idy = 0 ...
dispatch register/ unregister events.
def dispatch_notification(self, msg): """dispatch register/unregister events.""" try: idents,msg = self.session.feed_identities(msg) except ValueError: self.log.warn("task::Invalid Message: %r",msg) return try: msg = self.session.unserializ...
New engine with ident uid became available.
def _register_engine(self, uid): """New engine with ident `uid` became available.""" # head of the line: self.targets.insert(0,uid) self.loads.insert(0,0) # initialize sets self.completed[uid] = set() self.failed[uid] = set() self.pending[uid] = {} ...
Existing engine with ident uid became unavailable.
def _unregister_engine(self, uid): """Existing engine with ident `uid` became unavailable.""" if len(self.targets) == 1: # this was our only engine pass # handle any potentially finished tasks: self.engine_stream.flush() # don't pop destinations, because...
Deal with jobs resident in an engine that died.
def handle_stranded_tasks(self, engine): """Deal with jobs resident in an engine that died.""" lost = self.pending[engine] for msg_id in lost.keys(): if msg_id not in self.pending[engine]: # prevent double-handling of messages continue raw...
Dispatch job submission to appropriate handlers.
def dispatch_submission(self, raw_msg): """Dispatch job submission to appropriate handlers.""" # ensure targets up to date: self.notifier_stream.flush() try: idents, msg = self.session.feed_identities(raw_msg, copy=False) msg = self.session.unserialize(msg, conten...
Audit all waiting tasks for expired timeouts.
def audit_timeouts(self): """Audit all waiting tasks for expired timeouts.""" now = datetime.now() for msg_id in self.depending.keys(): # must recheck, in case one failure cascaded to another: if msg_id in self.depending: job = self.depending[msg_id] ...
a task has become unreachable send a reply with an ImpossibleDependency error.
def fail_unreachable(self, msg_id, why=error.ImpossibleDependency): """a task has become unreachable, send a reply with an ImpossibleDependency error.""" if msg_id not in self.depending: self.log.error("msg %r already failed!", msg_id) return job = self.depending....
check location dependencies and run if they are met.
def maybe_run(self, job): """check location dependencies, and run if they are met.""" msg_id = job.msg_id self.log.debug("Attempting to assign task %s", msg_id) if not self.targets: # no engines, definitely can't run return False if job.follow or ...
Save a message for later submission when its dependencies are met.
def save_unmet(self, job): """Save a message for later submission when its dependencies are met.""" msg_id = job.msg_id self.depending[msg_id] = job # track the ids in follow or after, but not those already finished for dep_id in job.after.union(job.follow).difference(self.all_do...
Submit a task to any of a subset of our targets.
def submit_task(self, job, indices=None): """Submit a task to any of a subset of our targets.""" if indices: loads = [self.loads[i] for i in indices] else: loads = self.loads idx = self.scheme(loads) if indices: idx = indices[idx] targe...
dispatch method for result replies
def dispatch_result(self, raw_msg): """dispatch method for result replies""" try: idents,msg = self.session.feed_identities(raw_msg, copy=False) msg = self.session.unserialize(msg, content=False, copy=False) engine = idents[0] try: idx = se...
handle a real task result either success or failure
def handle_result(self, idents, parent, raw_msg, success=True): """handle a real task result, either success or failure""" # first, relay result to client engine = idents[0] client = idents[1] # swap_ids for ROUTER-ROUTER mirror raw_msg[:2] = [client,engine] # pri...
handle an unmet dependency
def handle_unmet_dependency(self, idents, parent): """handle an unmet dependency""" engine = idents[0] msg_id = parent['msg_id'] job = self.pending[engine].pop(msg_id) job.blacklist.add(engine) if job.blacklist == job.targets: self.depending[msg_id] = job ...
dep_id just finished. Update our dependency graph and submit any jobs that just became runable.
def update_graph(self, dep_id=None, success=True): """dep_id just finished. Update our dependency graph and submit any jobs that just became runable. Called with dep_id=None to update entire graph for hwm, but without finishing a task. """ # print ("\n\n***********") ...
Called after self. targets [ idx ] just got the job with header. Override with subclasses. The default ordering is simple LRU. The default loads are the number of outstanding jobs.
def add_job(self, idx): """Called after self.targets[idx] just got the job with header. Override with subclasses. The default ordering is simple LRU. The default loads are the number of outstanding jobs.""" self.loads[idx] += 1 for lis in (self.targets, self.loads): ...
Generate a new log - file with a default header.
def logstart(self, logfname=None, loghead=None, logmode=None, log_output=False, timestamp=False, log_raw_input=False): """Generate a new log-file with a default header. Raises RuntimeError if the log has already been started""" if self.logfile is not None: raise Ru...
Switch logging on/ off. val should be ONLY a boolean.
def switch_log(self,val): """Switch logging on/off. val should be ONLY a boolean.""" if val not in [False,True,0,1]: raise ValueError, \ 'Call switch_log ONLY with a boolean argument, not with:',val label = {0:'OFF',1:'ON',False:'OFF',True:'ON'} if self.l...
Print a status message about the logger.
def logstate(self): """Print a status message about the logger.""" if self.logfile is None: print 'Logging has not been activated.' else: state = self.log_active and 'active' or 'temporarily suspended' print 'Filename :',self.logfname print '...
Write the sources to a log.
def log(self, line_mod, line_ori): """Write the sources to a log. Inputs: - line_mod: possibly modified input, such as the transformations made by input prefilters or input handlers of various kinds. This should always be valid Python. - line_ori: unmodified input lin...
Write data to the log file if active
def log_write(self, data, kind='input'): """Write data to the log file, if active""" #print 'data: %r' % data # dbg if self.log_active and data: write = self.logfile.write if kind=='input': if self.timestamp: write(str_to_unicode(time....
Fully stop logging and close log file.
def logstop(self): """Fully stop logging and close log file. In order to start logging again, a new logstart() call needs to be made, possibly (though not necessarily) with a new filename, mode and other options.""" if self.logfile is not None: self.logfile.close() ...
Create a worksheet by name with with a list of cells.
def new_worksheet(name=None, cells=None): """Create a worksheet by name with with a list of cells.""" ws = NotebookNode() if name is not None: ws.name = unicode(name) if cells is None: ws.cells = [] else: ws.cells = list(cells) return ws
Create a notebook by name id and a list of worksheets.
def new_notebook(metadata=None, worksheets=None): """Create a notebook by name, id and a list of worksheets.""" nb = NotebookNode() nb.nbformat = 2 if worksheets is None: nb.worksheets = [] else: nb.worksheets = list(worksheets) if metadata is None: nb.metadata = new_meta...
Adds a target string for dispatching
def add_s(self, s, obj, priority= 0 ): """ Adds a target 'string' for dispatching """ chain = self.strs.get(s, CommandChainDispatcher()) chain.add(obj,priority) self.strs[s] = chain
Adds a target regexp for dispatching
def add_re(self, regex, obj, priority= 0 ): """ Adds a target regexp for dispatching """ chain = self.regexs.get(regex, CommandChainDispatcher()) chain.add(obj,priority) self.regexs[regex] = chain
Get a seq of Commandchain objects that match key
def dispatch(self, key): """ Get a seq of Commandchain objects that match key """ if key in self.strs: yield self.strs[key] for r, obj in self.regexs.items(): if re.match(r, key): yield obj else: #print "nomatch",key # dbg ...
Yield all value targets without priority
def flat_matches(self, key): """ Yield all 'value' targets, without priority """ for val in self.dispatch(key): for el in val: yield el[1] # only value, no priority return
do a bit of validation of the notebook dir
def _notebook_dir_changed(self, name, old, new): """do a bit of validation of the notebook dir""" if os.path.exists(new) and not os.path.isdir(new): raise TraitError("notebook dir %r is not a directory" % new) if not os.path.exists(new): self.log.info("Creating notebook d...
List all notebooks in the notebook dir.
def list_notebooks(self): """List all notebooks in the notebook dir. This returns a list of dicts of the form:: dict(notebook_id=notebook,name=name) """ names = glob.glob(os.path.join(self.notebook_dir, '*' + self.filename_ext)) ...
Generate a new notebook_id for a name and store its mappings.
def new_notebook_id(self, name): """Generate a new notebook_id for a name and store its mappings.""" # TODO: the following will give stable urls for notebooks, but unless # the notebooks are immediately redirected to their new urls when their # filemname changes, nasty inconsistencies re...
Delete a notebook s id only. This doesn t delete the actual notebook.
def delete_notebook_id(self, notebook_id): """Delete a notebook's id only. This doesn't delete the actual notebook.""" name = self.mapping[notebook_id] del self.mapping[notebook_id] del self.rev_mapping[name]
Does a notebook exist?
def notebook_exists(self, notebook_id): """Does a notebook exist?""" if notebook_id not in self.mapping: return False path = self.get_path_by_name(self.mapping[notebook_id]) return os.path.isfile(path)
Return a full path to a notebook given its notebook_id.
def find_path(self, notebook_id): """Return a full path to a notebook given its notebook_id.""" try: name = self.mapping[notebook_id] except KeyError: raise web.HTTPError(404, u'Notebook does not exist: %s' % notebook_id) return self.get_path_by_name(name)
Return a full path to a notebook given its name.
def get_path_by_name(self, name): """Return a full path to a notebook given its name.""" filename = name + self.filename_ext path = os.path.join(self.notebook_dir, filename) return path
Get the representation of a notebook in format by notebook_id.
def get_notebook(self, notebook_id, format=u'json'): """Get the representation of a notebook in format by notebook_id.""" format = unicode(format) if format not in self.allowed_formats: raise web.HTTPError(415, u'Invalid notebook format: %s' % format) last_modified, nb = self...
Get the NotebookNode representation of a notebook by notebook_id.
def get_notebook_object(self, notebook_id): """Get the NotebookNode representation of a notebook by notebook_id.""" path = self.find_path(notebook_id) if not os.path.isfile(path): raise web.HTTPError(404, u'Notebook does not exist: %s' % notebook_id) info = os.stat(path) ...
Save a new notebook and return its notebook_id.
def save_new_notebook(self, data, name=None, format=u'json'): """Save a new notebook and return its notebook_id. If a name is passed in, it overrides any values in the notebook data and the value in the data is updated to use that value. """ if format not in self.allowed_formats...
Save an existing notebook by notebook_id.
def save_notebook(self, notebook_id, data, name=None, format=u'json'): """Save an existing notebook by notebook_id.""" if format not in self.allowed_formats: raise web.HTTPError(415, u'Invalid notebook format: %s' % format) try: nb = current.reads(data.decode('utf-8'), f...
Save an existing notebook object by notebook_id.
def save_notebook_object(self, notebook_id, nb): """Save an existing notebook object by notebook_id.""" if notebook_id not in self.mapping: raise web.HTTPError(404, u'Notebook does not exist: %s' % notebook_id) old_name = self.mapping[notebook_id] try: new_name = ...
Delete notebook by notebook_id.
def delete_notebook(self, notebook_id): """Delete notebook by notebook_id.""" path = self.find_path(notebook_id) if not os.path.isfile(path): raise web.HTTPError(404, u'Notebook does not exist: %s' % notebook_id) os.unlink(path) self.delete_notebook_id(notebook_id)
Return a non - used filename of the form basename<int >. This searches through the filenames ( basename0 basename1... ) until is find one that is not already being used. It is used to create Untitled and Copy names that are unique.
def increment_filename(self, basename): """Return a non-used filename of the form basename<int>. This searches through the filenames (basename0, basename1, ...) until is find one that is not already being used. It is used to create Untitled and Copy names that are unique. ...
Create a new notebook and return its notebook_id.
def new_notebook(self): """Create a new notebook and return its notebook_id.""" path, name = self.increment_filename('Untitled') notebook_id = self.new_notebook_id(name) metadata = current.new_metadata(name=name) nb = current.new_notebook(metadata=metadata) with open(path...
Copy an existing notebook and return its notebook_id.
def copy_notebook(self, notebook_id): """Copy an existing notebook and return its notebook_id.""" last_mod, nb = self.get_notebook_object(notebook_id) name = nb.metadata.name + '-Copy' path, name = self.increment_filename(name) nb.metadata.name = name notebook_id = self.n...
Return all physical tokens even line continuations.
def phys_tokens(toks): """Return all physical tokens, even line continuations. tokenize.generate_tokens() doesn't return a token for the backslash that continues lines. This wrapper provides those tokens so that we can re-create a faithful representation of the original source. Returns the same v...
Generate a series of lines one for each line in source.
def source_token_lines(source): """Generate a series of lines, one for each line in `source`. Each line is a list of pairs, each pair is a token:: [('key', 'def'), ('ws', ' '), ('nam', 'hello'), ('op', '('), ... ] Each pair has a token class, and the token text. If you concatenate all the to...
Determine the encoding for source ( a string ) according to PEP 263.
def source_encoding(source): """Determine the encoding for `source` (a string), according to PEP 263. Returns a string, the name of the encoding. """ # Note: this function should never be called on Python 3, since py3 has # built-in tools to do this. assert sys.version_info < (3, 0) # Thi...
Load the default config file from the default ipython_dir.
def load_default_config(ipython_dir=None): """Load the default config file from the default ipython_dir. This is useful for embedded shells. """ if ipython_dir is None: ipython_dir = get_ipython_dir() profile_dir = os.path.join(ipython_dir, 'profile_default') cl = PyFileConfigLoader(def...
Return a string containing a crash report.
def make_report(self,traceback): """Return a string containing a crash report.""" sec_sep = self.section_sep # Start with parent report report = [super(IPAppCrashHandler, self).make_report(traceback)] # Add interactive-specific info we may have rpt_add = report.append ...
This has to be in a method for TerminalIPythonApp to be available.
def _classes_default(self): """This has to be in a method, for TerminalIPythonApp to be available.""" return [ InteractiveShellApp, # ShellApp comes before TerminalApp, because self.__class__, # it will also affect subclasses (e.g. QtConsole) TerminalInteractiveS...
override to allow old - pylab flag with deprecation warning
def parse_command_line(self, argv=None): """override to allow old '-pylab' flag with deprecation warning""" argv = sys.argv[1:] if argv is None else argv if '-pylab' in argv: # deprecated `-pylab` given, # warn and transform into current syntax argv = argv[:...
Do actions after construct but before starting the app.
def initialize(self, argv=None): """Do actions after construct, but before starting the app.""" super(TerminalIPythonApp, self).initialize(argv) if self.subapp is not None: # don't bother initializing further, starting subapp return if not self.ignore_old_config: ...
initialize the InteractiveShell instance
def init_shell(self): """initialize the InteractiveShell instance""" # Create an InteractiveShell instance. # shell.display_banner should always be False for the terminal # based app, because we call shell.show_banner() by hand below # so the banner shows *before* all extension l...
optionally display the banner
def init_banner(self): """optionally display the banner""" if self.display_banner and self.interact: self.shell.show_banner() # Make sure there is a space below the banner. if self.log_level <= logging.INFO: print
Replace -- pylab = inline with -- pylab = auto
def _pylab_changed(self, name, old, new): """Replace --pylab='inline' with --pylab='auto'""" if new == 'inline': warn.warn("'inline' not available as pylab backend, " "using 'auto' instead.\n") self.pylab = 'auto'
Returns a string containing the class name of an object with the correct indefinite article ( a or an ) preceding it ( e. g. an Image a PlotValue ).
def class_of ( object ): """ Returns a string containing the class name of an object with the correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image', 'a PlotValue'). """ if isinstance( object, basestring ): return add_article( object ) return add_article( object.__class...
Return a string representation of a value and its type for readable error messages.
def repr_type(obj): """ Return a string representation of a value and its type for readable error messages. """ the_type = type(obj) if (not py3compat.PY3) and the_type is InstanceType: # Old-style class. the_type = obj.__class__ msg = '%r %r' % (obj, the_type) return msg
Convert the name argument to a list of names.
def parse_notifier_name(name): """Convert the name argument to a list of names. Examples -------- >>> parse_notifier_name('a') ['a'] >>> parse_notifier_name(['a','b']) ['a', 'b'] >>> parse_notifier_name(None) ['anytrait'] """ if isinstance(name, str): return [name] ...
Set the default value on a per instance basis.
def set_default_value(self, obj): """Set the default value on a per instance basis. This method is called by :meth:`instance_init` to create and validate the default value. The creation and validation of default values must be delayed until the parent :class:`HasTraits` class h...
Setup a handler to be called when a trait changes.
def on_trait_change(self, handler, name=None, remove=False): """Setup a handler to be called when a trait changes. This is used to setup dynamic notifications of trait changes. Static handlers can be created by creating methods on a HasTraits subclass with the naming convention '_[trai...
Get a list of all the traits of this class.
def class_traits(cls, **metadata): """Get a list of all the traits of this class. This method is just like the :meth:`traits` method, but is unbound. The TraitTypes returned don't know anything about the values that the various HasTrait's instances are holding. This follows th...
Get metadata values for trait by key.
def trait_metadata(self, traitname, key): """Get metadata values for trait by key.""" try: trait = getattr(self.__class__, traitname) except AttributeError: raise TraitError("Class %s does not have a trait named %s" % (self.__class__.__name...
Validates that the value is a valid object instance.
def validate(self, obj, value): """Validates that the value is a valid object instance.""" try: if issubclass(value, self.klass): return value except: if (value is None) and (self._allow_none): return value self.error(obj, value)
Returns a description of the trait.
def info(self): """ Returns a description of the trait.""" if isinstance(self.klass, basestring): klass = self.klass else: klass = self.klass.__name__ result = 'a subclass of ' + klass if self._allow_none: return result + ' or None' ret...
Instantiate a default value instance.
def get_default_value(self): """Instantiate a default value instance. This is called when the containing HasTraits classes' :meth:`__new__` method is called to ensure that a unique instance is created for each HasTraits instance. """ dv = self.default_value if i...
Returns a description of the trait.
def info(self): """ Returns a description of the trait.""" result = 'any of ' + repr(self.values) if self._allow_none: return result + ' or None' return result
Helper for
def _require(*names): """Helper for @require decorator.""" from IPython.parallel.error import UnmetDependency user_ns = globals() for name in names: if name in user_ns: continue try: exec 'import %s'%name in user_ns except ImportError: raise Un...
Simple decorator for requiring names to be importable. Examples -------- In [ 1 ]:
def require(*mods): """Simple decorator for requiring names to be importable. Examples -------- In [1]: @require('numpy') ...: def norm(a): ...: import numpy ...: return numpy.linalg.norm(a,2) """ names = [] for mod in mods: if isinstance(mod, M...
check whether our dependencies have been met.
def check(self, completed, failed=None): """check whether our dependencies have been met.""" if len(self) == 0: return True against = set() if self.success: against = completed if failed is not None and self.failure: against = against.union(fai...
return whether this dependency has become impossible.
def unreachable(self, completed, failed=None): """return whether this dependency has become impossible.""" if len(self) == 0: return False against = set() if not self.success: against = completed if failed is not None and not self.failure: agai...
Represent this dependency as a dict. For json compatibility.
def as_dict(self): """Represent this dependency as a dict. For json compatibility.""" return dict( dependencies=list(self), all=self.all, success=self.success, failure=self.failure )
Returns a Solver instance
def Ainv(self): 'Returns a Solver instance' if not hasattr(self, '_Ainv'): self._Ainv = self.Solver(self.A) return self._Ainv
Returns a Solver instance
def Ainv(self): 'Returns a Solver instance' if getattr(self, '_Ainv', None) is None: self._Ainv = self.Solver(self.A, 13) self._Ainv.run_pardiso(12) return self._Ainv
construct { child: parent } dict representation of a binary tree keys are the nodes in the tree and values are the parent of each node. The root node has parent parent default: None. >>> tree = bintree ( range ( 7 )) >>> tree { 0: None 1: 0 2: 1 3: 1 4: 0 5: 4 6: 4 } >>> print_bintree ( tree ) 0 1 2 3 4 5 6
def bintree(ids, parent=None): """construct {child:parent} dict representation of a binary tree keys are the nodes in the tree, and values are the parent of each node. The root node has parent `parent`, default: None. >>> tree = bintree(range(7)) >>> tree {0: None, 1: 0, 2: 1, 3: ...