_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q11900
globalsfilter
train
def globalsfilter(input_dict, check_all=False, filters=None, exclude_private=None, exclude_capitalized=None, exclude_uppercase=None, exclude_unsupported=None, excluded_names=None): """Keep only objects that can be pickled""" output_dict = {} for key, val...
python
{ "resource": "" }
q11901
get_supported_types
train
def get_supported_types(): """ Return a dictionnary containing types lists supported by the namespace browser. Note: If you update this list, don't forget to update variablexplorer.rst in spyder-docs """ from datetime import date, timedelta editable_types = [int, float, complex, lis...
python
{ "resource": "" }
q11902
SpyderKernel._pdb_frame
train
def _pdb_frame(self): """Return current Pdb frame if there is any""" if self._pdb_obj is not None and self._pdb_obj.curframe is not None: return self._pdb_obj.curframe
python
{ "resource": "" }
q11903
SpyderKernel.get_namespace_view
train
def get_namespace_view(self): """ Return the namespace view This is a dictionary with the following structure {'a': {'color': '#800000', 'size': 1, 'type': 'str', 'view': '1'}} Here: * 'a' is the variable name * 'color' is the color used to show it * 's...
python
{ "resource": "" }
q11904
SpyderKernel.get_var_properties
train
def get_var_properties(self): """ Get some properties of the variables in the current namespace """ from spyder_kernels.utils.nsview import get_remote_data settings = self.namespace_view_settings if settings: ns = self._get_current_namespace() ...
python
{ "resource": "" }
q11905
SpyderKernel.send_spyder_msg
train
def send_spyder_msg(self, spyder_msg_type, content=None, data=None): """ Publish custom messages to the Spyder frontend. Parameters ---------- spyder_msg_type: str The spyder message type content: dict The (JSONable) content of the message ...
python
{ "resource": "" }
q11906
SpyderKernel.set_value
train
def set_value(self, name, value, PY2_frontend): """Set the value of a variable""" import cloudpickle ns = self._get_reference_namespace(name) # We send serialized values in a list of one element # from Spyder to the kernel, to be able to send them # at all in Python 2 ...
python
{ "resource": "" }
q11907
SpyderKernel.load_data
train
def load_data(self, filename, ext): """Load data from filename""" from spyder_kernels.utils.iofuncs import iofunctions from spyder_kernels.utils.misc import fix_reference_name glbs = self._mglobals() load_func = iofunctions.load_funcs[ext] data, error_message = load_fun...
python
{ "resource": "" }
q11908
SpyderKernel.save_namespace
train
def save_namespace(self, filename): """Save namespace into filename""" from spyder_kernels.utils.nsview import get_remote_data from spyder_kernels.utils.iofuncs import iofunctions ns = self._get_current_namespace() settings = self.namespace_view_settings data = get_remot...
python
{ "resource": "" }
q11909
SpyderKernel.publish_pdb_state
train
def publish_pdb_state(self): """ Publish Variable Explorer state and Pdb step through send_spyder_msg. """ if self._pdb_obj and self._do_publish_pdb_state: state = dict(namespace_view = self.get_namespace_view(), var_properties = self.get_var_...
python
{ "resource": "" }
q11910
SpyderKernel.is_defined
train
def is_defined(self, obj, force_import=False): """Return True if object is defined in current namespace""" from spyder_kernels.utils.dochelpers import isdefined ns = self._get_current_namespace(with_magics=True) return isdefined(obj, force_import=force_import, namespace=ns)
python
{ "resource": "" }
q11911
SpyderKernel._get_current_namespace
train
def _get_current_namespace(self, with_magics=False): """ Return current namespace This is globals() if not debugging, or a dictionary containing both locals() and globals() for current frame when debugging """ ns = {} glbs = self._mglobals() if self._pdb...
python
{ "resource": "" }
q11912
SpyderKernel._get_reference_namespace
train
def _get_reference_namespace(self, name): """ Return namespace where reference name is defined It returns the globals() if reference has not yet been defined """ glbs = self._mglobals() if self._pdb_frame is None: return glbs else: lcls = ...
python
{ "resource": "" }
q11913
SpyderKernel._set_spyder_breakpoints
train
def _set_spyder_breakpoints(self, breakpoints): """Set all Spyder breakpoints in an active pdb session""" if not self._pdb_obj: return # Breakpoints come serialized from Spyder. We send them # in a list of one element to be able to send them at all # in Python 2 ...
python
{ "resource": "" }
q11914
SpyderKernel._set_mpl_backend
train
def _set_mpl_backend(self, backend, pylab=False): """ Set a backend for Matplotlib. backend: A parameter that can be passed to %matplotlib (e.g. 'inline' or 'tk'). """ import traceback from IPython.core.getipython import get_ipython generic_erro...
python
{ "resource": "" }
q11915
SpyderKernel._load_autoreload_magic
train
def _load_autoreload_magic(self): """Load %autoreload magic.""" from IPython.core.getipython import get_ipython try: get_ipython().run_line_magic('reload_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') except Exception: pass
python
{ "resource": "" }
q11916
SpyderKernel._load_wurlitzer
train
def _load_wurlitzer(self): """Load wurlitzer extension.""" # Wurlitzer has no effect on Windows if not os.name == 'nt': from IPython.core.getipython import get_ipython # Enclose this in a try/except because if it fails the # console will be totally unusable. ...
python
{ "resource": "" }
q11917
import_spydercustomize
train
def import_spydercustomize(): """Import our customizations into the kernel.""" here = osp.dirname(__file__) parent = osp.dirname(here) customize_dir = osp.join(parent, 'customize') # Remove current directory from sys.path to prevent kernel # crashes when people name Python files or modules with...
python
{ "resource": "" }
q11918
varexp
train
def varexp(line): """ Spyder's variable explorer magic Used to generate plots, histograms and images of the variables displayed on it. """ ip = get_ipython() #analysis:ignore funcname, name = line.split() try: import guiqwt.pyplot as pyplot except: import matpl...
python
{ "resource": "" }
q11919
fix_reference_name
train
def fix_reference_name(name, blacklist=None): """Return a syntax-valid Python reference name from an arbitrary name""" name = "".join(re.split(r'[^0-9a-zA-Z_]', name)) while name and not re.match(r'([a-zA-Z]+[0-9a-zA-Z_]*)$', name): if not re.match(r'[a-zA-Z]', name[0]): name = name[1:] ...
python
{ "resource": "" }
q11920
post_mortem_excepthook
train
def post_mortem_excepthook(type, value, tb): """ For post mortem exception handling, print a banner and enable post mortem debugging. """ clear_post_mortem() ipython_shell = get_ipython() ipython_shell.showtraceback((type, value, tb)) p = pdb.Pdb(ipython_shell.colors) if not type ==...
python
{ "resource": "" }
q11921
set_post_mortem
train
def set_post_mortem(): """ Enable the post mortem debugging excepthook. """ def ipython_post_mortem_debug(shell, etype, evalue, tb, tb_offset=None): post_mortem_excepthook(etype, evalue, tb) ipython_shell = get_ipython() ipython_shell.set_custom_exc((Exception,), ipython_p...
python
{ "resource": "" }
q11922
runcell
train
def runcell(cellname, filename): """ Run a code cell from an editor as a file. Currently looks for code in an `ipython` property called `cell_code`. This property must be set by the editor prior to calling this function. This function deletes the contents of `cell_code` upon completion. Parame...
python
{ "resource": "" }
q11923
UserModuleReloader.create_pathlist
train
def create_pathlist(self, initial_pathlist): """ Add to pathlist Python library paths to be skipped from module reloading. """ # Get standard installation paths try: paths = sysconfig.get_paths() standard_paths = [paths['stdlib'], ...
python
{ "resource": "" }
q11924
UserModuleReloader.is_module_reloadable
train
def is_module_reloadable(self, module, modname): """Decide if a module is reloadable or not.""" if self.has_cython: # Don't return cached inline compiled .PYX files return False else: if (self.is_module_in_pathlist(module) or self.is_module...
python
{ "resource": "" }
q11925
UserModuleReloader.is_module_in_pathlist
train
def is_module_in_pathlist(self, module): """Decide if a module can be reloaded or not according to its path.""" modpath = getattr(module, '__file__', None) # Skip module according to different criteria if modpath is None: # *module* is a C module that is statically linked in...
python
{ "resource": "" }
q11926
UserModuleReloader.activate_cython
train
def activate_cython(self): """ Activate Cython support. We need to run this here because if the support is active, we don't to run the UMR at all. """ run_cython = os.environ.get("SPY_RUN_CYTHON") == "True" if run_cython: try: __impor...
python
{ "resource": "" }
q11927
UserModuleReloader.run
train
def run(self): """ Delete user modules to force Python to deeply reload them Do not del modules which are considered as system modules, i.e. modules installed in subdirectories of Python interpreter's binary Do not del C modules """ self.modnames_to_reload = [] ...
python
{ "resource": "" }
q11928
get_matlab_value
train
def get_matlab_value(val): """ Extract a value from a Matlab file From the oct2py project, see https://pythonhosted.org/oct2py/conversions.html """ import numpy as np # Extract each item of a list. if isinstance(val, list): return [get_matlab_value(v) for v in val] # Ignor...
python
{ "resource": "" }
q11929
load_pickle
train
def load_pickle(filename): """Load a pickle file as a dictionary""" try: if pd: return pd.read_pickle(filename), None else: with open(filename, 'rb') as fid: data = pickle.load(fid) return data, None except Exception as err: return ...
python
{ "resource": "" }
q11930
load_json
train
def load_json(filename): """Load a json file as a dictionary""" try: if PY2: args = 'rb' else: args = 'r' with open(filename, args) as fid: data = json.load(fid) return data, None except Exception as err: return None, str(err)
python
{ "resource": "" }
q11931
load_dictionary
train
def load_dictionary(filename): """Load dictionary from .spydata file""" filename = osp.abspath(filename) old_cwd = getcwd() tmp_folder = tempfile.mkdtemp() os.chdir(tmp_folder) data = None error_message = None try: with tarfile.open(filename, "r") as tar: tar.extracta...
python
{ "resource": "" }
q11932
getobj
train
def getobj(txt, last=False): """Return the last valid object name in string""" txt_end = "" for startchar, endchar in ["[]", "()"]: if txt.endswith(endchar): pos = txt.rfind(startchar) if pos: txt_end = txt[pos:] txt = txt[:pos] tokens = re...
python
{ "resource": "" }
q11933
getsource
train
def getsource(obj): """Wrapper around inspect.getsource""" try: try: src = to_text_string(inspect.getsource(obj)) except TypeError: if hasattr(obj, '__class__'): src = to_text_string(inspect.getsource(obj.__class__)) else: # Bin...
python
{ "resource": "" }
q11934
getargs
train
def getargs(obj): """Get the names and default values of a function's arguments""" if inspect.isfunction(obj) or inspect.isbuiltin(obj): func_obj = obj elif inspect.ismethod(obj): func_obj = get_meth_func(obj) elif inspect.isclass(obj) and hasattr(obj, '__init__'): func_obj = get...
python
{ "resource": "" }
q11935
escape_tex
train
def escape_tex(value): """ Make text tex safe """ newval = value for pattern, replacement in LATEX_SUBS: newval = pattern.sub(replacement, newval) return newval
python
{ "resource": "" }
q11936
classnameify
train
def classnameify(s): """ Makes a classname """ return ''.join(w if w in ACRONYMS else w.title() for w in s.split('_'))
python
{ "resource": "" }
q11937
packagenameify
train
def packagenameify(s): """ Makes a package name """ return ''.join(w if w in ACRONYMS else w.title() for w in s.split('.')[-1:])
python
{ "resource": "" }
q11938
get_args
train
def get_args(): """ Get and parse arguments. """ import argparse parser = argparse.ArgumentParser( description="Swift Navigation SBP Example.") parser.add_argument( "-s", "--serial-port", default=[DEFAULT_SERIAL_PORT], nargs=1, help="specify the se...
python
{ "resource": "" }
q11939
convert
train
def convert(value): """Converts to a C language appropriate identifier format. """ s0 = "Sbp" + value if value in COLLISIONS else value s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', s0) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() + "_t"
python
{ "resource": "" }
q11940
mk_id
train
def mk_id(field): """Builds an identifier from a field. """ name = field.type_id if name == "string": return "%s" % ("char") elif name == "array" and field.size: if field.options['fill'].value not in CONSTRUCT_CODE: return "%s" % convert(field.options['fill'].value) else: return "%s" %...
python
{ "resource": "" }
q11941
mk_size
train
def mk_size(field): """Builds an identifier for a container type. """ name = field.type_id if name == "string" and field.options.get('size', None): return "%s[%d];" % (field.identifier, field.options.get('size').value) elif name == "string": return "%s[0];" % field.identifier elif name == "array" an...
python
{ "resource": "" }
q11942
SBP._get_framed
train
def _get_framed(self, buf, offset, insert_payload): """Returns the framed message and updates the CRC. """ header_offset = offset + self._header_len self.length = insert_payload(buf, header_offset, self.payload) struct.pack_into(self._header_fmt, buf, offse...
python
{ "resource": "" }
q11943
SBP.unpack
train
def unpack(d): """Unpack and return a framed binary message. """ p = SBP._parser.parse(d) assert p.preamble == SBP_PREAMBLE, "Invalid preamble 0x%x." % p.preamble return SBP(p.msg_type, p.sender, p.length, p.payload, p.crc)
python
{ "resource": "" }
q11944
SBP.to_json
train
def to_json(self, sort_keys=False): """Produce a JSON-encoded SBP message. """ d = self.to_json_dict() return json.dumps(d, sort_keys=sort_keys)
python
{ "resource": "" }
q11945
SBP.from_json
train
def from_json(s): """Given a JSON-encoded message, build an object. """ d = json.loads(s) sbp = SBP.from_json_dict(d) return sbp
python
{ "resource": "" }
q11946
parse_type
train
def parse_type(field): """ Function to pull a type from the binary payload. """ if field.type_id == 'string': if 'size' in field.options: return "parser.getString(%d)" % field.options['size'].value else: return "parser.getString()" elif field.type_id in JAVA_TYPE_MAP: # Primitive java ...
python
{ "resource": "" }
q11947
build_type
train
def build_type(field): """ Function to pack a type into the binary payload. """ if field.type_id == 'string': if 'size' in field.options: return "builder.putString(%s, %d)" % (field.identifier, field.options['size'].value) else: return "builder.putString(%s)" % field.identifier elif field....
python
{ "resource": "" }
q11948
render_table
train
def render_table(output_dir, packages, jenv=JENV): """ Render and output dispatch table """ destination_filename = output_dir + "/com/swiftnav/sbp/client/MessageTable.java" with open(destination_filename, 'w+') as f: print(destination_filename) f.write(jenv.get_template(TEMPLATE_TABLE_NAME).render...
python
{ "resource": "" }
q11949
construct_format
train
def construct_format(f, type_map=CONSTRUCT_CODE): """ Formats for binary-parser library. """ formatted = "" if type_map.get(f.type_id, None): return "%s('%s')" % (type_map.get(f.type_id), f.identifier) elif f.type_id == 'string' and f.options.get('size', None): return "string('%s', { length: %d })" ...
python
{ "resource": "" }
q11950
js_classnameify
train
def js_classnameify(s): """ Makes a classname. """ if not '_' in s: return s return ''.join(w[0].upper() + w[1:].lower() for w in s.split('_'))
python
{ "resource": "" }
q11951
MsgEphemerisGPSDepF.from_binary
train
def from_binary(self, d): """Given a binary payload d, update the appropriate payload fields of the message. """ p = MsgEphemerisGPSDepF._parser.parse(d) for n in self.__class__.__slots__: setattr(self, n, getattr(p, n))
python
{ "resource": "" }
q11952
Framer._readall
train
def _readall(self, size): """ Read until all bytes are collected. Parameters ---------- size : int Number of bytes to read. """ data = b"" while len(data) < size: d = self._read(size - len(data)) if self._broken: ...
python
{ "resource": "" }
q11953
Framer._receive
train
def _receive(self): """ Read and build SBP message. """ # preamble - not readall(1) to allow breaking before messages, # empty input preamble = self._read(1) if not preamble: return None elif ord(preamble) != SBP_PREAMBLE: if self._...
python
{ "resource": "" }
q11954
dispatch
train
def dispatch(msg, table=_SBP_TABLE): """ Dispatch an SBP message type based on its `msg_type` and parse its payload. Parameters ---------- driver : :class:`SBP` A parsed SBP object. table : dict Any table mapping unique SBP message type IDs to SBP message constructors. Returns ----------...
python
{ "resource": "" }
q11955
Handler._recv_thread
train
def _recv_thread(self): """ Internal thread to iterate over source messages and dispatch callbacks. """ for msg, metadata in self._source: if msg.msg_type: self._call(msg, **metadata) # Break any upstream iterators for sink in self._sinks: ...
python
{ "resource": "" }
q11956
Handler.filter
train
def filter(self, msg_type=None, maxsize=0): """ Get a filtered iterator of messages for synchronous, blocking use in another thread. """ if self._dead: return iter(()) iterator = Handler._SBPQueueIterator(maxsize) # We use a weakref so that the iterato...
python
{ "resource": "" }
q11957
Handler.add_callback
train
def add_callback(self, callback, msg_type=None): """ Add per message type or global callback. Parameters ---------- callback : fn Callback function msg_type : int | iterable Message type to register callback against. Default `None` means global callba...
python
{ "resource": "" }
q11958
Handler.remove_callback
train
def remove_callback(self, callback, msg_type=None): """ Remove per message type of global callback. Parameters ---------- callback : fn Callback function msg_type : int | iterable Message type to remove callback from. Default `None` means global callb...
python
{ "resource": "" }
q11959
Handler._gc_dead_sinks
train
def _gc_dead_sinks(self): """ Remove any dead weakrefs. """ deadsinks = [] for i in self._sinks: if i() is None: deadsinks.append(i) for i in deadsinks: self._sinks.remove(i)
python
{ "resource": "" }
q11960
Handler.wait
train
def wait(self, msg_type, timeout=1.0): """ Wait for a SBP message. Parameters ---------- msg_type : int SBP message type. timeout : float Waiting period """ event = threading.Event() payload = {'data': None} def cb(sbp...
python
{ "resource": "" }
q11961
Handler.wait_callback
train
def wait_callback(self, callback, msg_type=None, timeout=1.0): """ Wait for a SBP message with a callback. Parameters ---------- callback : fn Callback function msg_type : int | iterable Message type to register callback against. Default `None` means ...
python
{ "resource": "" }
q11962
fmt_repr
train
def fmt_repr(obj): """ Return pretty printed string representation of an object. """ items = {k: v for k, v in list(obj.__dict__.items())} return "<%s: {%s}>" % (obj.__class__.__name__, pprint.pformat(items, width=1))
python
{ "resource": "" }
q11963
SettingMonitor.capture_setting
train
def capture_setting(self, sbp_msg, **metadata): """Callback to extract and store setting values from SBP_MSG_SETTINGS_READ_RESP Messages of any type other than SBP_MSG_SETTINGS_READ_RESP are ignored """ if sbp_msg.msg_type == SBP_MSG_SETTINGS_READ_RESP: section, sett...
python
{ "resource": "" }
q11964
SettingMonitor.wait_for_setting_value
train
def wait_for_setting_value(self, section, setting, value, wait_time=5.0): """Function to wait wait_time seconds to see a SBP_MSG_SETTINGS_READ_RESP message with a user-specified value """ expire = time.time() + wait_time ok = False while not ok and time.time() < expire: ...
python
{ "resource": "" }
q11965
construct_format
train
def construct_format(f, type_map=CONSTRUCT_CODE): """ Formats for Construct. """ formatted = "" if type_map.get(f.type_id, None): return "'{identifier}' / {type_id}".format(type_id=type_map.get(f.type_id), identifier=f.identifier) elif f.type_id == 'string' a...
python
{ "resource": "" }
q11966
exclude_fields
train
def exclude_fields(obj, exclude=EXCLUDE): """ Return dict of object without parent attrs. """ return dict([(k, getattr(obj, k)) for k in obj.__slots__ if k not in exclude])
python
{ "resource": "" }
q11967
walk_json_dict
train
def walk_json_dict(coll): """ Flatten a parsed SBP object into a dicts and lists, which are compatible for JSON output. Parameters ---------- coll : dict """ if isinstance(coll, dict): return dict((k, walk_json_dict(v)) for (k, v) in iter(coll.items())) elif isinstance(coll, bytes): return c...
python
{ "resource": "" }
q11968
containerize
train
def containerize(coll): """Walk attribute fields passed from an SBP message and convert to Containers where appropriate. Needed for Construct proper serialization. Parameters ---------- coll : dict """ if isinstance(coll, Container): [setattr(coll, k, containerize(v)) for (k, v) in coll.items()] ...
python
{ "resource": "" }
q11969
fmt_repr
train
def fmt_repr(obj): """Print a orphaned string representation of an object without the clutter of its parent object. """ items = ["%s = %r" % (k, v) for k, v in list(exclude_fields(obj).items())] return "<%s: {%s}>" % (obj.__class__.__name__, ', '.join(items))
python
{ "resource": "" }
q11970
read_spec
train
def read_spec(filename, verbose=False): """ Read an SBP specification. Parameters ---------- filename : str Local filename for specification. verbose : bool Print out some debugging info Returns ---------- Raises ---------- Exception On empty file. yaml.YAMLError On Yaml parsi...
python
{ "resource": "" }
q11971
get_files
train
def get_files(input_file): """ Initializes an index of files to generate, returns the base directory and index. """ file_index = {} base_dir = None if os.path.isfile(input_file): file_index[input_file] = None base_dir = os.path.dirname(input_file) elif os.path.isdir(input_file): base_dir = ...
python
{ "resource": "" }
q11972
resolve_deps
train
def resolve_deps(base_dir, file_index): """ Given a base directory and an initial set of files, retrieves dependencies and adds them to the file_index. """ def flatten(tree, index = {}): for include in tree.get('include', []): fname = base_dir + "/" + include assert os.path.exists(fname), "Fi...
python
{ "resource": "" }
q11973
mk_package
train
def mk_package(contents): """Instantiates a package specification from a parsed "AST" of a package. Parameters ---------- contents : dict Returns ---------- PackageSpecification """ package = contents.get('package', None) description = contents.get('description', None) include = contents.get(...
python
{ "resource": "" }
q11974
mk_definition
train
def mk_definition(defn): """Instantiates a struct or SBP message specification from a parsed "AST" of a struct or message. Parameters ---------- defn : dict Returns ---------- A Definition or a specialization of a definition, like a Struct """ assert len(defn) == 1 identifier, contents = next(i...
python
{ "resource": "" }
q11975
mk_field
train
def mk_field(field): """Instantiates a field specification from a parsed "AST" of a field. Parameters ---------- field : dict Returns ---------- A Field or a specialization of a field, like a bitfield. """ assert len(field) == 1 identifier, contents = next(iter(field.items())) contents = dict...
python
{ "resource": "" }
q11976
to_global
train
def to_global(s): """ Format a global variable name. """ if s.startswith('GPSTime'): s = 'Gps' + s[3:] if '_' in s: s = "".join([i.capitalize() for i in s.split("_")]) return s[0].lower() + s[1:]
python
{ "resource": "" }
q11977
to_data
train
def to_data(s): """ Format a data variable name. """ if s.startswith('GPSTime'): s = 'Gps' + s[3:] if '_' in s: return "".join([i.capitalize() for i in s.split("_")]) return s
python
{ "resource": "" }
q11978
to_type
train
def to_type(f, type_map=CONSTRUCT_CODE): """ Format a the proper type. """ name = f.type_id if name.startswith('GPSTime'): name = 'Gps' + name[3:] if type_map.get(name, None): return type_map.get(name, None) elif name == 'array': fill = f.options['fill'].value f_ = copy.copy(f) f_.type...
python
{ "resource": "" }
q11979
to_identifier
train
def to_identifier(s): """ Convert snake_case to camel_case. """ if s.startswith('GPS'): s = 'Gps' + s[3:] return ''.join([i.capitalize() for i in s.split('_')]) if '_' in s else s
python
{ "resource": "" }
q11980
get_asset_tarball
train
def get_asset_tarball(asset_name, src_dir, dest_project, dest_folder, json_out): """ If the src_dir contains a "resources" directory its contents are archived and the archived file is uploaded to the platform """ if os.path.isdir(os.path.join(src_dir, "resources")): temp_dir = tempfile.mkdte...
python
{ "resource": "" }
q11981
get_user_id
train
def get_user_id(user_id_or_username): """Gets the user ID based on the value `user_id_or_username` specified on the command-line, being extra lenient and lowercasing the value in all cases. """ user_id_or_username = user_id_or_username.lower() if not user_id_or_username.startswith("user-"): ...
python
{ "resource": "" }
q11982
register_parser
train
def register_parser(parser, subparsers_action=None, categories=('other', ), add_help=True): """Attaches `parser` to the global ``parser_map``. If `add_help` is truthy, then adds the helpstring of `parser` into the output of ``dx help...``, for each category in `categories`. :param subparsers_action: A ...
python
{ "resource": "" }
q11983
_is_retryable_exception
train
def _is_retryable_exception(e): """Returns True if the exception is always safe to retry. This is True if the client was never able to establish a connection to the server (for example, name resolution failed or the connection could otherwise not be initialized). Conservatively, if we can't tell w...
python
{ "resource": "" }
q11984
_extract_msg_from_last_exception
train
def _extract_msg_from_last_exception(): ''' Extract a useful error message from the last thrown exception ''' last_exc_type, last_error, last_traceback = sys.exc_info() if isinstance(last_error, exceptions.DXAPIError): # Using the same code path as below would not # produce a useful message ...
python
{ "resource": "" }
q11985
_calculate_retry_delay
train
def _calculate_retry_delay(response, num_attempts): ''' Returns the time in seconds that we should wait. :param num_attempts: number of attempts that have been made to the resource, including the most recent failed one :type num_attempts: int ''' if response is not None and response.sta...
python
{ "resource": "" }
q11986
get_auth_server_name
train
def get_auth_server_name(host_override=None, port_override=None, protocol='https'): """ Chooses the auth server name from the currently configured API server name. Raises DXError if the auth server name cannot be guessed and the overrides are not provided (or improperly provided). """ if host_o...
python
{ "resource": "" }
q11987
append_underlying_workflow_describe
train
def append_underlying_workflow_describe(globalworkflow_desc): """ Adds the "workflowDescribe" field to the config for each region of the global workflow. The value is the description of an underlying workflow in that region. """ if not globalworkflow_desc or \ globalworkflow_desc['cl...
python
{ "resource": "" }
q11988
escape_unicode_string
train
def escape_unicode_string(u): """ Escapes the nonprintable chars 0-31 and 127, and backslash; preferably with a friendly equivalent such as '\n' if available, but otherwise with a Python-style backslashed hex escape. """ def replacer(matchobj): if ord(matchobj.group(1)) == 127: ...
python
{ "resource": "" }
q11989
flatten_json_array
train
def flatten_json_array(json_string, array_name): """ Flattens all arrays with the same name in the JSON string :param json_string: JSON string :type json_string: str :param array_name: Array name to flatten :type array_name: str """ result = re.sub('"{}": \\[\r?\n\\s*'.format(array_nam...
python
{ "resource": "" }
q11990
format_exception
train
def format_exception(e): """Returns a string containing the type and text of the exception. """ from .utils.printing import fill return '\n'.join(fill(line) for line in traceback.format_exception_only(type(e), e))
python
{ "resource": "" }
q11991
DXAPIError.error_message
train
def error_message(self): "Returns a one-line description of the error." output = self.msg + ", code " + str(self.code) output += ". Request Time={}, Request ID={}".format(self.timestamp, self.req_id) if self.name != self.__class__.__name__: output = self.name + ": " + output ...
python
{ "resource": "" }
q11992
DXGlobalWorkflow.publish
train
def publish(self, **kwargs): """ Publishes the global workflow, so all users can find it and use it on the platform. The current user must be a developer of the workflow. """ if self._dxid is not None: return dxpy.api.global_workflow_publish(self._dxid, **kwargs) ...
python
{ "resource": "" }
q11993
DXGlobalWorkflow._get_run_input
train
def _get_run_input(self, workflow_input, project=None, **kwargs): """ Checks the region in which the global workflow is run and returns the input associated with the underlying workflow from that region. """ region = dxpy.api.project_describe(project, ...
python
{ "resource": "" }
q11994
build
train
def build(src_dir, parallel_build=True): """ Runs any build scripts that are found in the specified directory. In particular, runs ``./configure`` if it exists, followed by ``make -jN`` if it exists (building with as many parallel tasks as there are CPUs on the system). """ # TODO: use Gent...
python
{ "resource": "" }
q11995
_create_or_update_version
train
def _create_or_update_version(app_name, version, app_spec, try_update=True): """ Creates a new version of the app. Returns an app_id, or None if the app has already been created and published. """ # This has a race condition since the app could have been created or # published since we last look...
python
{ "resource": "" }
q11996
_update_version
train
def _update_version(app_name, version, app_spec, try_update=True): """ Updates a version of the app in place. Returns an app_id, or None if the app has already been published. """ if not try_update: return None try: app_id = dxpy.api.app_update("app-" + app_name, version, app_spe...
python
{ "resource": "" }
q11997
create_app
train
def create_app(applet_id, applet_name, src_dir, publish=False, set_default=False, billTo=None, try_versions=None, try_update=True, confirm=True, regional_options=None): """ Creates a new app object from the specified applet. .. deprecated:: 0.204.0 Use :func:`create_app_multi_region()...
python
{ "resource": "" }
q11998
get_enabled_regions
train
def get_enabled_regions(app_spec, from_command_line): """Returns a list of the regions in which the app should be enabled. Also validates that app_spec['regionalOptions'], if supplied, is well-formed. :param app_spec: app specification :type app_spec: dict :param from_command_line: The regions...
python
{ "resource": "" }
q11999
get_implicit_depends_on
train
def get_implicit_depends_on(input_hash, depends_on): ''' Add DNAnexus links to non-closed data objects in input_hash to depends_on ''' q = [] for field in input_hash: possible_dep = get_nonclosed_data_obj_link(input_hash[field]) if possible_dep is not None: depends_on.ap...
python
{ "resource": "" }