code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _on_dynamodb_exception(self, error): """Dynamically handle DynamoDB exceptions, returning HTTP error responses. :param exceptions.DynamoDBException error: """ if isinstance(error, exceptions.ConditionalCheckFailedException): raise web.HTTPError(409, reason='Cond...
Dynamically handle DynamoDB exceptions, returning HTTP error responses. :param exceptions.DynamoDBException error:
def moveToReplayContext(self, r): 'set the sheet/row/col to the values in the replay row. return sheet' if not r.sheet: # assert not r.col and not r.row return self # any old sheet should do, row/column don't matter try: sheetidx = int(r.sheet) v...
set the sheet/row/col to the values in the replay row. return sheet
def overdrive(self, gain_db=20.0, colour=20.0): '''Apply non-linear distortion. Parameters ---------- gain_db : float, default=20 Controls the amount of distortion (dB). colour : float, default=20 Controls the amount of even harmonic content in the output...
Apply non-linear distortion. Parameters ---------- gain_db : float, default=20 Controls the amount of distortion (dB). colour : float, default=20 Controls the amount of even harmonic content in the output (dB).
def recursive_map(func, data): """ Apply func to data, and any collection items inside data (using map_collection). Define func so that it only applies to the type of value that you want it to apply to. """ def recurse(item): return recursive_map(func, item) items_mapped = map_collection...
Apply func to data, and any collection items inside data (using map_collection). Define func so that it only applies to the type of value that you want it to apply to.
async def _heartbeat_callback(self): """如果设置了心跳,则调用这个协程.""" query = { "MPRPC": self.VERSION, "HEARTBEAT": "ping" } queryb = self.encoder(query) while True: await asyncio.sleep(self.heart_beat) self.writer.write(queryb) i...
如果设置了心跳,则调用这个协程.
def container( state, host, name, present=True, image='ubuntu:16.04', ): ''' Add/remove LXD containers. Note: does not check if an existing container is based on the specified image. + name: name of the container + image: image to base the container on + present: whether the contai...
Add/remove LXD containers. Note: does not check if an existing container is based on the specified image. + name: name of the container + image: image to base the container on + present: whether the container should be present or absent
def system_call(cmd, **kwargs): """Call cmd and return (stdout, stderr, return_value). Parameters ---------- cmd: str Can be either a string containing the command to be run, or a sequence of strings that are the tokens of the command. kwargs : dict, optional Ignored. Availa...
Call cmd and return (stdout, stderr, return_value). Parameters ---------- cmd: str Can be either a string containing the command to be run, or a sequence of strings that are the tokens of the command. kwargs : dict, optional Ignored. Available so that this function is compatible...
def geom_symm_match(g, atwts, ax, theta, do_refl): """ [Revised match factor calculation] .. todo:: Complete geom_symm_match docstring """ # Imports import numpy as np from scipy import linalg as spla # Convert g and atwts to n-D vectors g = make_nd_vec(g, nd=None, t=np.float64, norm...
[Revised match factor calculation] .. todo:: Complete geom_symm_match docstring
def query_transactions(self, initial_date, final_date, page=None, max_results=None): """ query transaction by date range """ last_page = False results = [] while last_page is False: search_result = self._consume_query_tran...
query transaction by date range
def mouseMoveEvent(self, event): """Determines if a drag is taking place, and initiates it""" if (event.pos() - self.dragStartPosition).manhattanLength() < 10: return QtGui.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.ClosedHandCursor)) factory = self.factoryclass()...
Determines if a drag is taking place, and initiates it
def get_file_path(self, name, relative_path): """ Return the path to a resource file. """ dist = self.get_distribution(name) if dist is None: raise LookupError('no distribution named %r found' % name) return dist.get_resource_path(relative_path)
Return the path to a resource file.
def create_model(self): """Create model from reader. Returns: :class:`psamm.datasource.native.NativeModel`. """ properties = { 'name': self.name, 'default_flux_limit': 1000 } # Load objective as biomass reaction objective = se...
Create model from reader. Returns: :class:`psamm.datasource.native.NativeModel`.
def read_cstring(self, terminator=b'\x00'): """Reads a single null termianted string :return: string without bytes :rtype: :class:`bytes` """ null_index = self.data.find(terminator, self.offset) if null_index == -1: raise RuntimeError("Reached end of buffer")...
Reads a single null termianted string :return: string without bytes :rtype: :class:`bytes`
def _calc_recip(self): """ Perform the reciprocal space summation. Calculates the quantity E_recip = 1/(2PiV) sum_{G < Gmax} exp(-(G.G/4/eta))/(G.G) S(G)S(-G) where S(G) = sum_{k=1,N} q_k exp(-i G.r_k) S(G)S(-G) = |S(G)|**2 This method is heavily vectorized to ut...
Perform the reciprocal space summation. Calculates the quantity E_recip = 1/(2PiV) sum_{G < Gmax} exp(-(G.G/4/eta))/(G.G) S(G)S(-G) where S(G) = sum_{k=1,N} q_k exp(-i G.r_k) S(G)S(-G) = |S(G)|**2 This method is heavily vectorized to utilize numpy's C backend for speed.
def run(self): """ Run the given command and yield each line(s) one by one. .. note:: The difference between this method and :code:`self.execute()` is that :code:`self.execute()` wait for the process to end in order to return its output. """ ...
Run the given command and yield each line(s) one by one. .. note:: The difference between this method and :code:`self.execute()` is that :code:`self.execute()` wait for the process to end in order to return its output.
def get_interval(ticker, session) -> Session: """ Get interval from defined session Args: ticker: ticker session: session Returns: Session of start_time and end_time Examples: >>> get_interval('005490 KS Equity', 'day_open_30') Session(start_time='09:00', e...
Get interval from defined session Args: ticker: ticker session: session Returns: Session of start_time and end_time Examples: >>> get_interval('005490 KS Equity', 'day_open_30') Session(start_time='09:00', end_time='09:30') >>> get_interval('005490 KS Equit...
def writes(nb, format, **kwargs): """Write a notebook to a string in a given format in the current nbformat version. This function always writes the notebook in the current nbformat version. Parameters ---------- nb : NotebookNode The notebook to write. format : (u'json', u'ipynb', u'p...
Write a notebook to a string in a given format in the current nbformat version. This function always writes the notebook in the current nbformat version. Parameters ---------- nb : NotebookNode The notebook to write. format : (u'json', u'ipynb', u'py') The format to write the noteb...
def applet_run(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /applet-xxxx/run API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Applets-and-Entry-Points#API-method%3A-%2Fapplet-xxxx%2Frun """ input_params_cp = Nonce.update_nonce(input_par...
Invokes the /applet-xxxx/run API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Applets-and-Entry-Points#API-method%3A-%2Fapplet-xxxx%2Frun
def ensureBones(self,data): """ Helper method ensuring per-entity bone data has been properly initialized. Should be called at the start of every method accessing per-entity data. ``data`` is the entity to check in dictionary form. """ if "_bones" not in...
Helper method ensuring per-entity bone data has been properly initialized. Should be called at the start of every method accessing per-entity data. ``data`` is the entity to check in dictionary form.
def format_search(q, **kwargs): '''Formats the results of a search''' m = search(q, **kwargs) count = m['count'] if not count: raise DapiCommError('Could not find any DAP packages for your query.') return for mdap in m['results']: mdap = mdap['content_object'] return ...
Formats the results of a search
def update_column(self, header, column): """Update a column named `header` in the table. If length of column is smaller than number of rows, lets say `k`, only the first `k` values in the column is updated. Parameters ---------- header : str Header of the co...
Update a column named `header` in the table. If length of column is smaller than number of rows, lets say `k`, only the first `k` values in the column is updated. Parameters ---------- header : str Header of the column column : iterable Any iter...
def insert(self, item, safe=None): # pragma: nocover ''' [DEPRECATED] Please use save() instead. This actually calls the underlying save function, so the name is confusing. Insert an item into the work queue and flushes.''' warnings.warn('Insert will be deprecated soon and removed in 1.0. Please use insert',...
[DEPRECATED] Please use save() instead. This actually calls the underlying save function, so the name is confusing. Insert an item into the work queue and flushes.
def _detect_encoding(data=None): """Return the default system encoding. If data is passed, try to decode the data with the default system encoding or from a short list of encoding types to test. Args: data - list of lists Returns: enc - system encoding """ import locale ...
Return the default system encoding. If data is passed, try to decode the data with the default system encoding or from a short list of encoding types to test. Args: data - list of lists Returns: enc - system encoding
def hash(self): """Hash value based on file name and .ini file content""" if self._hash is None: # Only hash _camera.ini and _para.ini fsh = [self.path.with_name(self._mid + "_camera.ini"), self.path.with_name(self._mid + "_para.ini")] tohash = [has...
Hash value based on file name and .ini file content
def _on_closed(self): """Invoked by connections when they are closed.""" self._connected.clear() if not self._closing: if self._on_close_callback: self._on_close_callback() else: raise exceptions.ConnectionError('closed')
Invoked by connections when they are closed.
def t_STRING(t): r"'([^'\\]+|\\'|\\\\)*'" t.value = t.value.replace(r'\\', chr(92)).replace(r"\'", r"'")[1:-1] return t
r"'([^'\\]+|\\'|\\\\)*
def trk50(msg): """True track angle, BDS 5,0 message Args: msg (String): 28 bytes hexadecimal message (BDS50) string Returns: float: angle in degrees to true north (from 0 to 360) """ d = hex2bin(data(msg)) if d[11] == '0': return None sign = int(d[12]) # 1 -> w...
True track angle, BDS 5,0 message Args: msg (String): 28 bytes hexadecimal message (BDS50) string Returns: float: angle in degrees to true north (from 0 to 360)
def list_build_configurations_for_project(id=None, name=None, page_size=200, page_index=0, sort="", q=""): """ List all BuildConfigurations associated with the given Project. """ data = list_build_configurations_for_project_raw(id, name, page_size, page_index, sort, q) if data: return utils....
List all BuildConfigurations associated with the given Project.
def rgb2rgba(rgb): """Take a row of RGB bytes, and convert to a row of RGBA bytes.""" rgba = [] for i in range(0, len(rgb), 3): rgba += rgb[i:i+3] rgba.append(255) return rgba
Take a row of RGB bytes, and convert to a row of RGBA bytes.
def _labels_cost(Xnum, Xcat, centroids, num_dissim, cat_dissim, gamma, membship=None): """Calculate labels and cost function given a matrix of points and a list of centroids for the k-prototypes algorithm. """ n_points = Xnum.shape[0] Xnum = check_array(Xnum) cost = 0. labels = np.empty(n_...
Calculate labels and cost function given a matrix of points and a list of centroids for the k-prototypes algorithm.
def set_cookie(self, name: str, value: str, *, expires: Optional[str]=None, domain: Optional[str]=None, max_age: Optional[Union[int, str]]=None, path: str='/', secure: Optional[str]=None, httponly: Optional...
Set or update response cookie. Sets new cookie or updates existent with new value. Also updates only those params which are not None.
def getReadNoise(self, exten): """ Method for returning the readnoise of a detector (in counts). Returns ------- readnoise : float The readnoise of the detector in **units of counts/electrons**. """ rn = self._image[exten]._rdnoise if self.pr...
Method for returning the readnoise of a detector (in counts). Returns ------- readnoise : float The readnoise of the detector in **units of counts/electrons**.
def remove_license_requests(cursor, uuid_, uids): """Given a ``uuid`` and list of ``uids`` (user identifiers) remove the identified users' license acceptance entries. """ if not isinstance(uids, (list, set, tuple,)): raise TypeError("``uids`` is an invalid type: {}".format(type(uids))) acce...
Given a ``uuid`` and list of ``uids`` (user identifiers) remove the identified users' license acceptance entries.
def ip_address_delete(session, ifname, ifaddr): """ Deletes an IP address from interface record identified with the given "ifname". The arguments are similar to "ip address delete" command of iproute2. :param session: Session instance connecting to database. :param ifname: Name of interface. ...
Deletes an IP address from interface record identified with the given "ifname". The arguments are similar to "ip address delete" command of iproute2. :param session: Session instance connecting to database. :param ifname: Name of interface. :param ifaddr: IPv4 or IPv6 address. :return: Instanc...
def update(self, iterable): """ Update bag with all elements in iterable. >>> s = pbag([1]) >>> s.update([1, 2]) pbag([1, 1, 2]) """ if iterable: return PBag(reduce(_add_to_counters, iterable, self._counts)) return self
Update bag with all elements in iterable. >>> s = pbag([1]) >>> s.update([1, 2]) pbag([1, 1, 2])
def getBlockParams(ws): """ Auxiliary method to obtain ``ref_block_num`` and ``ref_block_prefix``. Requires a websocket connection to a witness node! """ dynBCParams = ws.get_dynamic_global_properties() ref_block_num = dynBCParams["head_block_number"] & 0xFFFF ref_block_prefix = stru...
Auxiliary method to obtain ``ref_block_num`` and ``ref_block_prefix``. Requires a websocket connection to a witness node!
def instance_default(self, obj): ''' Get the default value that will be used for a specific instance. Args: obj (HasProps) : The instance to get the default value for. Returns: object ''' return self.property.themed_default(obj.__class__, self.name, obj...
Get the default value that will be used for a specific instance. Args: obj (HasProps) : The instance to get the default value for. Returns: object
def predict(self, x, batch_size=None, verbose=None, is_distributed=False): """Generates output predictions for the input samples, processing the samples in a batched way. # Arguments x: the input data, as a Numpy array or list of Numpy array for local mode. as RDD[Sam...
Generates output predictions for the input samples, processing the samples in a batched way. # Arguments x: the input data, as a Numpy array or list of Numpy array for local mode. as RDD[Sample] for distributed mode is_distributed: used to control run in local or ...
def parse_alignment_summary_metrics(fn): """ Parse the output from Picard's CollectAlignmentSummaryMetrics and return as pandas Dataframe. Parameters ---------- filename : str of filename or file handle Filename of the Picard output you want to parse. Returns ------- df : p...
Parse the output from Picard's CollectAlignmentSummaryMetrics and return as pandas Dataframe. Parameters ---------- filename : str of filename or file handle Filename of the Picard output you want to parse. Returns ------- df : pandas.DataFrame Data from output file.
def download_results(self, savedir=None, raw=True, calib=False, index=None): """Download the previously found and stored Opus obsids. Parameters ========== savedir: str or pathlib.Path, optional If the database root folder as defined by the config.ini should not be used, ...
Download the previously found and stored Opus obsids. Parameters ========== savedir: str or pathlib.Path, optional If the database root folder as defined by the config.ini should not be used, provide a different savedir here. It will be handed to PathManager.
def get_or_create_exh_obj(full_cname=False, exclude=None, callables_fname=None): r""" Return global exception handler if set, otherwise create a new one and return it. :param full_cname: Flag that indicates whether fully qualified function/method/class property names are obtained for...
r""" Return global exception handler if set, otherwise create a new one and return it. :param full_cname: Flag that indicates whether fully qualified function/method/class property names are obtained for functions/methods/class properties that use the ...
def user_exists(self, username): """ Returns whether a user with username ``username`` exists. :param str username: username of user :return: whether a user with the specified username exists :rtype: bool :raises NetworkFailure: if there is an error communicating with th...
Returns whether a user with username ``username`` exists. :param str username: username of user :return: whether a user with the specified username exists :rtype: bool :raises NetworkFailure: if there is an error communicating with the server :return:
def p_configure_sentence(self, t): """configure_sentence : CONFIGURE VAR | CONFIGURE VAR LPAREN RECIPE_BEGIN recipe RECIPE_END RPAREN""" if len(t) == 3: t[0] = configure(t[2], reference=True, line=t.lineno(1)) else: t[0] = configure(t[2], t[...
configure_sentence : CONFIGURE VAR | CONFIGURE VAR LPAREN RECIPE_BEGIN recipe RECIPE_END RPAREN
def get_cached(self): """ Get items from feed cache while trying to emulate how API handles offset/since/before parameters """ def id_in_list(list, id): if id: if [i for i in list if i.id == id]: return True else: ...
Get items from feed cache while trying to emulate how API handles offset/since/before parameters
def _wrapper(self, q, start): """ _wrapper checks return status of Probe.fnc and provides the result for process managing :param q: Queue for function results :param start: Time of function run (used for logging) :return: Return value or Exception """ tr...
_wrapper checks return status of Probe.fnc and provides the result for process managing :param q: Queue for function results :param start: Time of function run (used for logging) :return: Return value or Exception
def draw(self, tree, bar_desc=None, save_cursor=True, flush=True): """Draw ``tree`` to the terminal :type tree: dict :param tree: ``tree`` should be a tree representing a hierarchy; each key should be a string describing that hierarchy level and value should also be ``d...
Draw ``tree`` to the terminal :type tree: dict :param tree: ``tree`` should be a tree representing a hierarchy; each key should be a string describing that hierarchy level and value should also be ``dict`` except for leaves which should be ``BarDescriptors``. See ``...
def get_reports(): """ Returns energy data from 1960 to 2014 across various factors. """ if False: # If there was a Test version of this method, it would go here. But alas. pass else: rows = _Constants._DATABASE.execute("SELECT data FROM energy".format( hardw...
Returns energy data from 1960 to 2014 across various factors.
def _execute(self, workdir, with_mpirun=False, exec_args=None): """ Execute the executable in a subprocess inside workdir. Some executables fail if we try to launch them with mpirun. Use with_mpirun=False to run the binary without it. """ qadapter = self.manager.qadapter...
Execute the executable in a subprocess inside workdir. Some executables fail if we try to launch them with mpirun. Use with_mpirun=False to run the binary without it.
def _handleClassAttr(self): ''' _handleClassAttr - Hack to ensure "class" and "style" show up in attributes when classes are set, and doesn't when no classes are present on associated tag. TODO: I don't like this hack. ''' if len(self.tag._classNames)...
_handleClassAttr - Hack to ensure "class" and "style" show up in attributes when classes are set, and doesn't when no classes are present on associated tag. TODO: I don't like this hack.
def commit(self) -> None: """ Attempt to commit all changes to LDAP database. i.e. forget all rollbacks. However stay inside transaction management. """ if len(self._transactions) == 0: raise RuntimeError("commit called outside transaction") # If we have nes...
Attempt to commit all changes to LDAP database. i.e. forget all rollbacks. However stay inside transaction management.
def Many2ManyThroughModel(field): '''Create a Many2Many through model with two foreign key fields and a CompositeFieldId depending on the two foreign keys.''' from stdnet.odm import ModelType, StdModel, ForeignKey, CompositeIdField name_model = field.model._meta.name name_relmodel = field.relmodel....
Create a Many2Many through model with two foreign key fields and a CompositeFieldId depending on the two foreign keys.
def get_decomp_and_e_above_hull(self, entry, allow_negative=False): """ Provides the decomposition and energy above convex hull for an entry. Due to caching, can be much faster if entries with the same composition are processed together. Args: entry: A PDEntry like o...
Provides the decomposition and energy above convex hull for an entry. Due to caching, can be much faster if entries with the same composition are processed together. Args: entry: A PDEntry like object allow_negative: Whether to allow negative e_above_hulls. Used to ...
def error(self, message, *args, **kwargs): """Log error event. Compatible with logging.error signature. """ self.system.error(message, *args, **kwargs)
Log error event. Compatible with logging.error signature.
def _get_dump_item_context(self, index, name, opts): """ Return a formated dict context """ c = { 'item_no': index, 'label': name, 'name': name, 'models': ' '.join(opts['models']), 'natural_key': '', } if opts.ge...
Return a formated dict context
def link(self): """str: full path of the linked file entry.""" if not self.IsLink(): return '' location = getattr(self.path_spec, 'location', None) if location is None: return '' return self._file_system.GetDataByPath(location)
str: full path of the linked file entry.
def set_motor_position(self, motor_name, position): """ Sets the motor target position. """ self.call_remote_api('simxSetJointTargetPosition', self.get_object_handle(motor_name), position, sending=True)
Sets the motor target position.
def _get_possible_circular_ref_contigs(self, nucmer_hits, log_fh=None, log_outprefix=None): '''Returns a dict ref name => tuple(hit at start, hit at end) for each ref sequence in the hash nucmer_hits (each value is a list of nucmer hits)''' writing_log_file = None not in [log_fh, log_outprefix] ...
Returns a dict ref name => tuple(hit at start, hit at end) for each ref sequence in the hash nucmer_hits (each value is a list of nucmer hits)
def AD(frame, high_col='high', low_col='low', close_col='close', vol_col='Volume'): """Chaikin A/D Line""" return _frame_to_series(frame, [high_col, low_col, close_col, vol_col], talib.AD)
Chaikin A/D Line
def parse_navigation_html_to_tree(html, id): """Parse the given ``html`` (an etree object) to a tree. The ``id`` is required in order to assign the top-level tree id value. """ def xpath(x): return html.xpath(x, namespaces=HTML_DOCUMENT_NAMESPACES) try: value = xpath('//*[@data-type=...
Parse the given ``html`` (an etree object) to a tree. The ``id`` is required in order to assign the top-level tree id value.
def system_listMethods(self): """system.listMethods() => ['add', 'subtract', 'multiple'] Returns a list of the methods supported by the server.""" methods = set(self.funcs.keys()) if self.instance is not None: # Instance can implement _listMethod to return a list of ...
system.listMethods() => ['add', 'subtract', 'multiple'] Returns a list of the methods supported by the server.
def source_title_header_element(feature, parent): """Retrieve source title header string from definitions.""" _ = feature, parent # NOQA header = source_title_header['string_format'] return header.capitalize()
Retrieve source title header string from definitions.
def get_cache_item(self): '''Gets the cached item. Raises AttributeError if it hasn't been set.''' if settings.DEBUG: raise AttributeError('Caching disabled in DEBUG mode') return getattr(self.template, self.options['template_cache_key'])
Gets the cached item. Raises AttributeError if it hasn't been set.
def as_obj(func): """ A decorator used to return a JSON response with a dict representation of the model instance. It expects the decorated function to return a Model instance. It then converts the instance to dicts and serializes it into a json response Examples: >>> ...
A decorator used to return a JSON response with a dict representation of the model instance. It expects the decorated function to return a Model instance. It then converts the instance to dicts and serializes it into a json response Examples: >>> @app.route('/api/shipments...
def AllBalancesZeroOrLess(self): """ Flag indicating if all balances are 0 or less. Returns: bool: True if all balances are <= 0. False, otherwise. """ for key, fixed8 in self.Balances.items(): if fixed8.value > 0: return False ret...
Flag indicating if all balances are 0 or less. Returns: bool: True if all balances are <= 0. False, otherwise.
def wait_for_lock(self, lockname, locktime=60, auto_renewal=False): ''' Gets a lock or waits until it is able to get it ''' pid = os.getpid() caller = inspect.stack()[0][3] try: # rl = redlock.Redlock([{"host": settings.REDIS_SERVERS['std_redis']['host'], "port": setting...
Gets a lock or waits until it is able to get it
def _log_sum_sq(x, axis=None): """Computes log(sum(x**2)).""" return tf.reduce_logsumexp( input_tensor=2. * tf.math.log(tf.abs(x)), axis=axis)
Computes log(sum(x**2)).
def send(self, config, log, obs_id, beam_id): """ Send the pulsar data to the ftp server Args: config (dict): Dictionary of settings log (logging.Logger): Python logging object obs_id: observation id beam_id: beam id """ log.info('...
Send the pulsar data to the ftp server Args: config (dict): Dictionary of settings log (logging.Logger): Python logging object obs_id: observation id beam_id: beam id
def _find_plugin_dir(module_type): '''Find the directory containing the plugin definition for the given type. Do this by searching all the paths where plugins can live for a dir that matches the type name.''' for install_dir in _get_plugin_install_dirs(): candidate = os.path.join(install_dir, m...
Find the directory containing the plugin definition for the given type. Do this by searching all the paths where plugins can live for a dir that matches the type name.
def read_vensim(mdl_file): """ Construct a model from Vensim `.mdl` file. Parameters ---------- mdl_file : <string> The relative path filename for a raw Vensim `.mdl` file Returns ------- model: a PySD class object Elements from the python model are loaded into the PySD...
Construct a model from Vensim `.mdl` file. Parameters ---------- mdl_file : <string> The relative path filename for a raw Vensim `.mdl` file Returns ------- model: a PySD class object Elements from the python model are loaded into the PySD class and ready to run Examples ...
def _update_conda_devel(): """Update to the latest development conda package. """ conda_bin = _get_conda_bin() channels = _get_conda_channels(conda_bin) assert conda_bin, "Could not find anaconda distribution for upgrading bcbio" subprocess.check_call([conda_bin, "install", "--quiet", "--yes"] +...
Update to the latest development conda package.
def from_json_str(cls, json_str): """Convert json string representation into class instance. Args: json_str: json representation as string. Returns: New instance of the class with data loaded from json string. """ return cls.from_json(json.loads(json_str, cls=JsonDecoder))
Convert json string representation into class instance. Args: json_str: json representation as string. Returns: New instance of the class with data loaded from json string.
def allocate_IPv6( self, name, id_network_type, id_environment, description, id_environment_vip=None): """Inserts a new VLAN. :param name: Name of Vlan. String with a maximum of 50 characters. :param id_network_type: Identi...
Inserts a new VLAN. :param name: Name of Vlan. String with a maximum of 50 characters. :param id_network_type: Identifier of the Netwok Type. Integer value and greater than zero. :param id_environment: Identifier of the Environment. Integer value and greater than zero. :param descriptio...
def _parse_remote_response(self, response): """ Parse JWKS from the HTTP response. Should be overriden by subclasses for adding support of e.g. signed JWKS. :param response: HTTP response from the 'jwks_uri' endpoint :return: response parsed as JSON """ #...
Parse JWKS from the HTTP response. Should be overriden by subclasses for adding support of e.g. signed JWKS. :param response: HTTP response from the 'jwks_uri' endpoint :return: response parsed as JSON
def order_events(events, d=False): """ Group events that occur on the same day, then sort them alphabetically by title, then sort by day. Returns a list of tuples that looks like [(day: [events])], where day is the day of the event(s), and [events] is an alphabetically sorted list of the events for ...
Group events that occur on the same day, then sort them alphabetically by title, then sort by day. Returns a list of tuples that looks like [(day: [events])], where day is the day of the event(s), and [events] is an alphabetically sorted list of the events for the day.
def softDeactivate(rh): """ Deactivate a virtual machine by first shutting down Linux and then log it off. Input: Request Handle with the following properties: function - 'POWERVM' subfunction - 'SOFTOFF' userid - userid of the virtual machine parm...
Deactivate a virtual machine by first shutting down Linux and then log it off. Input: Request Handle with the following properties: function - 'POWERVM' subfunction - 'SOFTOFF' userid - userid of the virtual machine parms['maxQueries'] - Maximum number...
def _completion_move(self, p_step, p_size): """ Visually selects completion specified by p_step (positive numbers forwards, negative numbers backwards) and inserts it into edit_text. If p_step results in value out of range of currently evaluated completion candidates, list is re...
Visually selects completion specified by p_step (positive numbers forwards, negative numbers backwards) and inserts it into edit_text. If p_step results in value out of range of currently evaluated completion candidates, list is rewinded to the start (if cycling forwards) or to the end ...
def optimize(thumbnail_file, jpg_command=None, png_command=None, gif_command=None): """ A post processing function to optimize file size. Accepts commands to optimize JPG, PNG and GIF images as arguments. Example: THUMBNAILS = { # Other options... 'POST_PROCESSORS': [ ...
A post processing function to optimize file size. Accepts commands to optimize JPG, PNG and GIF images as arguments. Example: THUMBNAILS = { # Other options... 'POST_PROCESSORS': [ { 'processor': 'thumbnails.post_processors.optimize', 'png_command': '...
def wait_any(futures, timeout=None): '''Wait for the completion of any (the first) one of multiple futures :param list futures: A list of :class:`Future`\s :param timeout: The maximum time to wait. With ``None``, will block indefinitely. :type timeout: float or None :returns: One o...
Wait for the completion of any (the first) one of multiple futures :param list futures: A list of :class:`Future`\s :param timeout: The maximum time to wait. With ``None``, will block indefinitely. :type timeout: float or None :returns: One of the futures from the provided list -- the ...
def on_queue_declareok(self, method_frame): """Method invoked by pika when the Queue.Declare RPC call made in setup_queue has completed. In this method we will bind the queue and exchange together with the routing key by issuing the Queue.Bind RPC command. When this command is complete, ...
Method invoked by pika when the Queue.Declare RPC call made in setup_queue has completed. In this method we will bind the queue and exchange together with the routing key by issuing the Queue.Bind RPC command. When this command is complete, the on_bindok method will be invoked by pika. ...
def f_add_result_group(self, *args, **kwargs): """Adds an empty result group under the current node. Adds the full name of the current node as prefix to the name of the group. If current node is a single run (root) adds the prefix `'results.runs.run_08%d%'` to the full name where `'08%d...
Adds an empty result group under the current node. Adds the full name of the current node as prefix to the name of the group. If current node is a single run (root) adds the prefix `'results.runs.run_08%d%'` to the full name where `'08%d'` is replaced by the index of the current run. T...
def render_chart_to_file(self, template_name: str, chart: Any, path: str): """ Render a chart or page to local html files. :param chart: A Chart or Page object :param path: The destination file which the html code write to :param template_name: The name of template file. ...
Render a chart or page to local html files. :param chart: A Chart or Page object :param path: The destination file which the html code write to :param template_name: The name of template file.
def _CreateIndexIfNotExists(self, index_name, mappings): """Creates an Elasticsearch index if it does not exist. Args: index_name (str): mame of the index. mappings (dict[str, object]): mappings of the index. Raises: RuntimeError: if the Elasticsearch index cannot be created. """ ...
Creates an Elasticsearch index if it does not exist. Args: index_name (str): mame of the index. mappings (dict[str, object]): mappings of the index. Raises: RuntimeError: if the Elasticsearch index cannot be created.
def get_client_cache_key(request_or_attempt: Union[HttpRequest, Any], credentials: dict = None) -> str: """ Build cache key name from request or AccessAttempt object. :param request_or_attempt: HttpRequest or AccessAttempt object :param credentials: credentials containing user information :return c...
Build cache key name from request or AccessAttempt object. :param request_or_attempt: HttpRequest or AccessAttempt object :param credentials: credentials containing user information :return cache_key: Hash key that is usable for Django cache backends
def gpg_encrypt( fd_in, path_out, sender_key_info, recipient_key_infos, passphrase=None, config_dir=None ): """ Encrypt a stream of data for a set of keys. @sender_key_info should be a dict with { 'key_id': ... 'key_data': ... 'app_name'; ... } Return {'status': True} on ...
Encrypt a stream of data for a set of keys. @sender_key_info should be a dict with { 'key_id': ... 'key_data': ... 'app_name'; ... } Return {'status': True} on success Return {'error': ...} on error
def _wordAfterCursor(self): """Get word, which is located before cursor """ cursor = self._qpart.textCursor() textAfterCursor = cursor.block().text()[cursor.positionInBlock():] match = _wordAtStartRegExp.search(textAfterCursor) if match: return match.group(0) ...
Get word, which is located before cursor
def enable_reporting(self): """Call this method to explicitly enable reporting. The current report will be uploaded, plus the previously recorded ones, and the configuration will be updated so that future runs also upload automatically. """ if self.status == Stats.ENABLE...
Call this method to explicitly enable reporting. The current report will be uploaded, plus the previously recorded ones, and the configuration will be updated so that future runs also upload automatically.
def get_content(self, url, params=None, limit=0, place_holder=None, root_field='data', thing_field='children', after_field='after', object_filter=None, **kwargs): """A generator method to return reddit content from a URL. Starts at the initial url, and fetches co...
A generator method to return reddit content from a URL. Starts at the initial url, and fetches content using the `after` JSON data until `limit` entries have been fetched, or the `place_holder` has been reached. :param url: the url to start fetching content from :param params: ...
def delete_split(self, split_name): """ Delete a split of the dataset. Parameters ---------- split_name : str name of the split to delete """ if self.has_split(split_name): shutil.rmtree(os.path.join(self.split_dir, split_name))
Delete a split of the dataset. Parameters ---------- split_name : str name of the split to delete
def readline(self, prompt='', use_raw=None): """Read a line of input. Prompt and use_raw exist to be compatible with other input routines and are ignored. EOFError will be raised on EOF. """ line = self.input.readline() if not line: raise EOFError return line.rstr...
Read a line of input. Prompt and use_raw exist to be compatible with other input routines and are ignored. EOFError will be raised on EOF.
def ReadFile(self, filename): """Reads artifact definitions from a file. Args: filename (str): name of the file to read from. Yields: ArtifactDefinition: an artifact definition. """ with io.open(filename, 'r', encoding='utf-8') as file_object: for artifact_definition in self.Read...
Reads artifact definitions from a file. Args: filename (str): name of the file to read from. Yields: ArtifactDefinition: an artifact definition.
def add_to_message(data, indent_level=0) -> list: """Adds data to the message object""" message = [] if isinstance(data, str): message.append(indent( dedent(data.strip('\n')).strip(), indent_level * ' ' )) return message for line in data: offset...
Adds data to the message object
def saml_name_id_format_to_hash_type(name_format): """ Translate pySAML2 name format to satosa format :type name_format: str :rtype: satosa.internal_data.UserIdHashType :param name_format: SAML2 name format :return: satosa format """ msg = "saml_name_id_format_to_hash_type is deprecated...
Translate pySAML2 name format to satosa format :type name_format: str :rtype: satosa.internal_data.UserIdHashType :param name_format: SAML2 name format :return: satosa format
def grant_user_access(self, user, db_names, strict=True): """ Gives access to the databases listed in `db_names` to the user. """ return self._user_manager.grant_user_access(user, db_names, strict=strict)
Gives access to the databases listed in `db_names` to the user.
def get_exchanges(self, vhost=None): """ :returns: A list of dicts :param string vhost: A vhost to query for exchanges, or None (default), which triggers a query for all exchanges in all vhosts. """ if vhost: vhost = quote(vhost, '') path = Cl...
:returns: A list of dicts :param string vhost: A vhost to query for exchanges, or None (default), which triggers a query for all exchanges in all vhosts.
async def rollback(self): """Roll back this transaction.""" if not self._parent._is_active: return await self._do_rollback() self._is_active = False
Roll back this transaction.
def _get_initial_args(objective_function, initial_population, initial_position, population_size, population_stddev, max_iterations, func_tolerance, position_tolerance...
Processes initial args.
def _generate_ffmpeg_cmd( self, cmd: List[str], input_source: Optional[str], output: Optional[str], extra_cmd: Optional[str] = None, ) -> None: """Generate ffmpeg command line.""" self._argv = [self._ffmpeg] # start command init if input_sourc...
Generate ffmpeg command line.
def sc_cuts_alg(self, viewer, event, msg=True): """Adjust cuts algorithm interactively. """ if self.cancut: direction = self.get_direction(event.direction) self._cycle_cuts_alg(viewer, msg, direction=direction) return True
Adjust cuts algorithm interactively.
def end_experience_collection_timer(self): """ Inform Metrics class that experience collection is done. """ if self.time_start_experience_collection: curr_delta = time() - self.time_start_experience_collection if self.delta_last_experience_collection is None: ...
Inform Metrics class that experience collection is done.
def register_hooked(self, hooks, # type: Union[Type[Hook], Sequence[Type[Hook]]] func, # type: Hooked args_gen=None # type: Optional[ArgsGen] ): # type: (Type[Hook], Callable, Optional[Callable]) -> None "...
Register func to be run when any of the hooks are run by parent Args: hooks: A Hook class or list of Hook classes of interest func: The callable that should be run on that Hook args_gen: Optionally specify the argument names that should be passed to func. If ...