code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def putcellslice(self, rownr, value, blc, trc, inc=[]): """Put into a slice of a table cell holding an array. (see :func:`table.putcellslice`)""" return self._table.putcellslice(self._column, rownr, value, blc, trc, inc)
Put into a slice of a table cell holding an array. (see :func:`table.putcellslice`)
def is_external_url(self, url, site_url): """ Check if the URL is an external URL. """ url_splitted = urlsplit(url) if not url_splitted.netloc: return False return url_splitted.netloc != urlsplit(site_url).netloc
Check if the URL is an external URL.
def insert(self, iterable, index=0, data=None, weight=1.0): """Insert new node into tree Args: iterable(hashable): key used to find in the future. data(object): data associated with the key index(int): an index used for insertion. weight(float): the wait ...
Insert new node into tree Args: iterable(hashable): key used to find in the future. data(object): data associated with the key index(int): an index used for insertion. weight(float): the wait given for the item added.
def wait( self, timeout: Union[int, float] = None, safe: bool = False ) -> List[Union[Any, Exception]]: """ Call :py:meth:`~Process.wait()` on all the Processes in this list. :param timeout: Same as :py:meth:`~Process.wait()`. This parameter controls the tim...
Call :py:meth:`~Process.wait()` on all the Processes in this list. :param timeout: Same as :py:meth:`~Process.wait()`. This parameter controls the timeout for all the Processes combined, not a single :py:meth:`~Process.wait()` call. :param safe: Suppress...
def generate_sources_zip(milestone_id=None, output=None): """ Generate a sources archive for given milestone id. """ if not is_input_valid(milestone_id, output): logging.error("invalid input") return 1 create_work_dir(output) download_sources_artifacts(milestone_id, output) ...
Generate a sources archive for given milestone id.
def get_departures(self, stop_id, route, destination, api_key): """Get the latest data from Transport NSW.""" self.stop_id = stop_id self.route = route self.destination = destination self.api_key = api_key # Build the URL including the STOP_ID and the API key url...
Get the latest data from Transport NSW.
def freeze(self): """ Freeze all settings so they cannot be altered """ self.app.disable() self.clear.disable() self.nod.disable() self.led.disable() self.dummy.disable() self.readSpeed.disable() self.expose.disable() self.number.di...
Freeze all settings so they cannot be altered
def appliance_device_snmp_v1_trap_destinations(self): """ Gets the ApplianceDeviceSNMPv1TrapDestinations API client. Returns: ApplianceDeviceSNMPv1TrapDestinations: """ if not self.__appliance_device_snmp_v1_trap_destinations: self.__appliance_device_snmp...
Gets the ApplianceDeviceSNMPv1TrapDestinations API client. Returns: ApplianceDeviceSNMPv1TrapDestinations:
def in_config(self, key): """Check to see if the given key (or an alias) is in the config file. """ # if the requested key is an alias, then return the proper key key = self._real_key(key) exists = self._config.get(key) return exists
Check to see if the given key (or an alias) is in the config file.
def _newConsole(cls, console): """Make a Console instance, from a console ctype""" self = cls.__new__(cls) _BaseConsole.__init__(self) self.console_c = console self.console = self self.width = _lib.TCOD_console_get_width(console) self.height = _lib.TCOD_console_ge...
Make a Console instance, from a console ctype
def on_lstCanvasExpLayers_itemSelectionChanged(self): """Update layer description label .. note:: This is an automatic Qt slot executed when the category selection changes. """ self.parent.exposure_layer = self.selected_canvas_explayer() lblText = self.parent.get_laye...
Update layer description label .. note:: This is an automatic Qt slot executed when the category selection changes.
def golden_images(self): """ Gets the Golden Images API client. Returns: GoldenImages: """ if not self.__golden_images: self.__golden_images = GoldenImages(self.__connection) return self.__golden_images
Gets the Golden Images API client. Returns: GoldenImages:
def delete_servers(self, server_id): """ Requires: account ID, server ID Input should be server id Returns: list of failed deletions (if any) Endpoint: api.newrelic.com Errors: 403 Invalid API Key Method: Delete """ endpoint = "https://api.newrelic...
Requires: account ID, server ID Input should be server id Returns: list of failed deletions (if any) Endpoint: api.newrelic.com Errors: 403 Invalid API Key Method: Delete
def to_iter(obj): """Convert an object to a list if it is not already an iterable. Nones are returned unaltered. This is an awful function that proliferates an explosion of types, please do not use anymore. """ if isinstance(obj, type(None)): return None elif isinstance(obj, six.string...
Convert an object to a list if it is not already an iterable. Nones are returned unaltered. This is an awful function that proliferates an explosion of types, please do not use anymore.
def get_global_cache_dir(appname='default', ensure=False): """ Returns (usually) writable directory for an application cache """ if appname is None or appname == 'default': appname = get_default_appname() global_cache_dir = util_cplat.get_app_resource_dir(appname, ...
Returns (usually) writable directory for an application cache
def cubehelix_pal(start=0, rot=.4, gamma=1.0, hue=0.8, light=.85, dark=.15, reverse=False): """ Utility for creating continuous palette from the cubehelix system. This produces a colormap with linearly-decreasing (or increasing) brightness. That means that information will be preserve...
Utility for creating continuous palette from the cubehelix system. This produces a colormap with linearly-decreasing (or increasing) brightness. That means that information will be preserved if printed to black and white or viewed by someone who is colorblind. Parameters ---------- start : flo...
def evaluate(self, verbose=True, passes=None): """Summary Returns: TYPE: Description """ if self.is_pivot: index, pivot, columns = LazyOpResult( self.expr, self.weld_type, 0 ).evaluate(verbose=verbose, p...
Summary Returns: TYPE: Description
def list_folder_content(self, folder, name=None, entity_type=None, content_type=None, page_size=DEFAULT_PAGE_SIZE, page=None, ordering=None): '''List files and folders (not recursively) contained in the folder. This function does not retrieve all ...
List files and folders (not recursively) contained in the folder. This function does not retrieve all results, pages have to be manually retrieved by the caller. Args: folder (str): The UUID of the requested folder. name (str): Optional filter on entity name. ...
def get_data_and_shared_column_widths(self, data_kwargs, width_kwargs): """ :param data_kwargs: kwargs used for converting data to strings :param width_kwargs: kwargs used for determining column widths :return: tuple(list of list of strings, list of int) """ list_of_list...
:param data_kwargs: kwargs used for converting data to strings :param width_kwargs: kwargs used for determining column widths :return: tuple(list of list of strings, list of int)
def check(self, cfg, state, peek_blocks): """ Check if the specified address will be executed :param cfg: :param state: :param int peek_blocks: :return: :rtype: bool """ # Get the current CFGNode from the CFG node = self._get_cfg_node(cfg...
Check if the specified address will be executed :param cfg: :param state: :param int peek_blocks: :return: :rtype: bool
def close(self): """ Closes the connection to the database for this connection. :return <bool> closed """ for pool in self.__pool.values(): while not pool.empty(): conn = pool.get_nowait() try: self._close(conn)...
Closes the connection to the database for this connection. :return <bool> closed
def trisolve(dl, d, du, b, inplace=False): """ The tridiagonal matrix (Thomas) algorithm for solving tridiagonal systems of equations: a_{i}x_{i-1} + b_{i}x_{i} + c_{i}x_{i+1} = y_{i} in matrix form: Mx = b TDMA is O(n), whereas standard Gaussian elimination is O(n^3). Argume...
The tridiagonal matrix (Thomas) algorithm for solving tridiagonal systems of equations: a_{i}x_{i-1} + b_{i}x_{i} + c_{i}x_{i+1} = y_{i} in matrix form: Mx = b TDMA is O(n), whereas standard Gaussian elimination is O(n^3). Arguments: ----------- dl: (n - 1,) vector ...
def estimate_bitstring_probs(results): """ Given an array of single shot results estimate the probability distribution over all bitstrings. :param np.array results: A 2d array where the outer axis iterates over shots and the inner axis over bits. :return: An array with as many axes as there are...
Given an array of single shot results estimate the probability distribution over all bitstrings. :param np.array results: A 2d array where the outer axis iterates over shots and the inner axis over bits. :return: An array with as many axes as there are qubit and normalized such that it sums to one. ...
def apply_mask(img, mask): """Return the image with the given `mask` applied.""" from .mask import apply_mask vol, _ = apply_mask(img, mask) return vector_to_volume(vol, read_img(mask).get_data().astype(bool))
Return the image with the given `mask` applied.
def _set_rspan_access(self, v, load=False): """ Setter method for rspan_access, mapped from YANG variable /interface/fortygigabitethernet/switchport/access/rspan_access (container) If this variable is read-only (config: false) in the source YANG file, then _set_rspan_access is considered as a private ...
Setter method for rspan_access, mapped from YANG variable /interface/fortygigabitethernet/switchport/access/rspan_access (container) If this variable is read-only (config: false) in the source YANG file, then _set_rspan_access is considered as a private method. Backends looking to populate this variable sho...
def add_directory(self, *args, **kwargs): """ Add directory or directories list to bundle :param exclusions: List of excluded paths :type path: str|unicode :type exclusions: list """ exc = kwargs.get('exclusions', None) for path in args: self...
Add directory or directories list to bundle :param exclusions: List of excluded paths :type path: str|unicode :type exclusions: list
def add_region_location(self, region, locations=None, use_live=True): # type: (str, Optional[List[str]], bool) -> bool """Add all countries in a region. If a 3 digit UNStats M49 region code is not provided, value is parsed as a region name. If any country is already added, it is ignored. ...
Add all countries in a region. If a 3 digit UNStats M49 region code is not provided, value is parsed as a region name. If any country is already added, it is ignored. Args: region (str): M49 region, intermediate region or subregion to add locations (Optional[List[str]]): Valid l...
def setup_actions(self): """ Connects slots to signals """ self.actionOpen.triggered.connect(self.on_open) self.actionNew.triggered.connect(self.on_new) self.actionSave.triggered.connect(self.on_save) self.actionSave_as.triggered.connect(self.on_save_as) self.actionQuit.t...
Connects slots to signals
def normalizeToTag(val): """Converts tags or full names to 2 character tags, case insensitive # Parameters _val_: `str` > A two character string giving the tag or its full name # Returns `str` > The short name of _val_ """ try: val = val.upper() except AttributeErro...
Converts tags or full names to 2 character tags, case insensitive # Parameters _val_: `str` > A two character string giving the tag or its full name # Returns `str` > The short name of _val_
def autocorrplot(trace, vars=None, fontmap = None, max_lag=100): """Bar plot of the autocorrelation function for a trace""" try: # MultiTrace traces = trace.traces except AttributeError: # NpTrace traces = [trace] if fontmap is None: fontmap = {1:10, 2:8, 3:6, 4:5, 5:...
Bar plot of the autocorrelation function for a trace
def fromurl(url): """ Parse patch from an URL, return False if an error occured. Note that this also can throw urlopen() exceptions. """ ps = PatchSet( urllib_request.urlopen(url) ) if ps.errors == 0: return ps return False
Parse patch from an URL, return False if an error occured. Note that this also can throw urlopen() exceptions.
def binarize(netin, threshold_type, threshold_level, sign='pos', axis='time'): """ Binarizes a network, returning the network. General wrapper function for different binarization functions. Parameters ---------- netin : array or dict Network (graphlet or contact representation), thresh...
Binarizes a network, returning the network. General wrapper function for different binarization functions. Parameters ---------- netin : array or dict Network (graphlet or contact representation), threshold_type : str What type of thresholds to make binarization. Options: 'rdp', 'perce...
def count_rows(self, table_name): """Return the number of entries in a table by counting them.""" self.table_must_exist(table_name) query = "SELECT COUNT (*) FROM `%s`" % table_name.lower() self.own_cursor.execute(query) return int(self.own_cursor.fetchone()[0])
Return the number of entries in a table by counting them.
def _create_window_info(self, window, wm_title: str, wm_class: str): """ Creates a WindowInfo object from the window title and WM_CLASS. Also checks for the Java XFocusProxyWindow workaround and applies it if needed: Workaround for Java applications: Java AWT uses a XFocusProxyWindow cl...
Creates a WindowInfo object from the window title and WM_CLASS. Also checks for the Java XFocusProxyWindow workaround and applies it if needed: Workaround for Java applications: Java AWT uses a XFocusProxyWindow class, so to get usable information, the parent window needs to be queried. Credits...
def retrieve_page(self, method, path, post_params={}, headers={}, status=200, username=None, password=None, *args, **kwargs): """ Makes the actual request. This will also go through and generate the needed steps to make the request, i.e. basic auth. ...
Makes the actual request. This will also go through and generate the needed steps to make the request, i.e. basic auth. ``method``: Any supported HTTP methods defined in :rfc:`2616`. ``path``: Absolute or relative path. See :meth:`_prepare_uri` for more deta...
def _run(self): '''Continually poll TWS''' stop = self._stop_evt connected = self._connected_evt tws = self._tws fd = tws.fd() pollfd = [fd] while not stop.is_set(): while (not connected.is_set() or not tws.isConnected()) and not stop.is_set(): ...
Continually poll TWS
def slice_shift(self, periods=1, axis=0): """ Equivalent to `shift` without copying data. The shifted data will not include the dropped periods and the shifted axis will be smaller than the original. Parameters ---------- periods : int Number of perio...
Equivalent to `shift` without copying data. The shifted data will not include the dropped periods and the shifted axis will be smaller than the original. Parameters ---------- periods : int Number of periods to move, can be positive or negative Returns ...
def sync(self, videoQuality, client=None, clientId=None, limit=None, unwatched=False, title=None): """ Add current video (movie, tv-show, season or episode) as sync item for specified device. See :func:`plexapi.myplex.MyPlexAccount.sync()` for possible exceptions. Parameters: ...
Add current video (movie, tv-show, season or episode) as sync item for specified device. See :func:`plexapi.myplex.MyPlexAccount.sync()` for possible exceptions. Parameters: videoQuality (int): idx of quality of the video, one of VIDEO_QUALITY_* values defined in ...
def rdf_catalog(): '''Root RDF endpoint with content negociation handling''' format = RDF_EXTENSIONS[negociate_content()] url = url_for('site.rdf_catalog_format', format=format) return redirect(url)
Root RDF endpoint with content negociation handling
async def _formulate_body(self): ''' Takes user supplied data / files and forms it / them appropriately, returning the contents type, len, and the request body its self. Returns: The str mime type for the Content-Type header. The len of the body. ...
Takes user supplied data / files and forms it / them appropriately, returning the contents type, len, and the request body its self. Returns: The str mime type for the Content-Type header. The len of the body. The body as a str.
def pipe_uniq(context=None, _INPUT=None, conf=None, **kwargs): """An operator that filters out non unique items according to the specified field. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipe2py.modules pipe like object (iterable of items) kwargs -- othe...
An operator that filters out non unique items according to the specified field. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipe2py.modules pipe like object (iterable of items) kwargs -- other inputs, e.g. to feed terminals for rule values conf : {'field': ...
def _set_intf_isis(self, v, load=False): """ Setter method for intf_isis, mapped from YANG variable /routing_system/interface/ve/intf_isis (container) If this variable is read-only (config: false) in the source YANG file, then _set_intf_isis is considered as a private method. Backends looking to pop...
Setter method for intf_isis, mapped from YANG variable /routing_system/interface/ve/intf_isis (container) If this variable is read-only (config: false) in the source YANG file, then _set_intf_isis is considered as a private method. Backends looking to populate this variable should do so via calling this...
def create_post(self, title, body, board, category, username): '''create a Discourse post, given a title, body, board, and token. Parameters ========== title: the issue title body: the issue body board: the discourse board to post to ''' category_url = "%s/categories.js...
create a Discourse post, given a title, body, board, and token. Parameters ========== title: the issue title body: the issue body board: the discourse board to post to
def head(self, lines=10): """\ Return the top lines of the file. """ self.seek(0) for i in range(lines): if not self.seek_line_forward(): break end_pos = self.file.tell() self.seek(0) data = self.file.read(end_pos...
\ Return the top lines of the file.
def serialize_to_normalized_compact_json(py_obj): """Serialize a native object to normalized, compact JSON. The JSON string is normalized by sorting any dictionary keys. It will be on a single line without whitespace between elements. Args: py_obj: object Any object that can be represent...
Serialize a native object to normalized, compact JSON. The JSON string is normalized by sorting any dictionary keys. It will be on a single line without whitespace between elements. Args: py_obj: object Any object that can be represented in JSON. Some types, such as datetimes are aut...
def save_experiment(self, name, variants): """ Persist an experiment and its variants (unless they already exist). :param name a unique string name for the experiment :param variants a list of strings, each with a unique variant name """ try: model.Experiment...
Persist an experiment and its variants (unless they already exist). :param name a unique string name for the experiment :param variants a list of strings, each with a unique variant name
def clear_dcnm_in_part(self, tenant_id, fw_dict, is_fw_virt=False): """Clear the DCNM in partition service information. Clear the In partition service node IP address in DCNM and update the result. """ res = fw_const.DCNM_IN_PART_UPDDEL_SUCCESS tenant_name = fw_dict.get(...
Clear the DCNM in partition service information. Clear the In partition service node IP address in DCNM and update the result.
def get_firmware(self): """Get the current firmware version.""" self.get_status() try: self.firmware = self.data['fw_version'] except TypeError: self.firmware = 'Unknown' return self.firmware
Get the current firmware version.
def getPotential(self, columnIndex, potential): """ :param columnIndex: (int) column index to get potential for. :param potential: (list) will be overwritten with column potentials. Must match the number of inputs. """ assert(columnIndex < self._numColumns) potential[:] = self._poten...
:param columnIndex: (int) column index to get potential for. :param potential: (list) will be overwritten with column potentials. Must match the number of inputs.
def workspace_backup_restore(ctx, choose_first, bak): """ Restore backup BAK """ backup_manager = WorkspaceBackupManager(Workspace(ctx.resolver, directory=ctx.directory, mets_basename=ctx.mets_basename, automatic_backup=ctx.automatic_backup)) backup_manager.restore(bak, choose_first)
Restore backup BAK
def execute(self): """ execute Webhook :return: """ if bool(self.files) is False: response = requests.post(self.url, json=self.json, proxies=self.proxies) else: self.files['payload_json'] = (None, json.dumps(self.json)) response = reque...
execute Webhook :return:
def get_correctness(self, question_id): """get measure of correctness for the question""" response = self.get_response(question_id) if response.is_answered(): item = self._get_item(response.get_item_id()) return item.get_correctness_for_response(response) raise er...
get measure of correctness for the question
def section_term_lengths(neurites, neurite_type=NeuriteType.all): '''Termination section lengths in a collection of neurites''' return map_sections(_section_length, neurites, neurite_type=neurite_type, iterator_type=Tree.ileaf)
Termination section lengths in a collection of neurites
def validate_all_values_for_key_in_obj(obj, key, validation_fun): """Validate value for all (nested) occurrence of `key` in `obj` using `validation_fun`. Args: obj (dict): dictionary object. key (str): key whose value is to be validated. validation_fun (function)...
Validate value for all (nested) occurrence of `key` in `obj` using `validation_fun`. Args: obj (dict): dictionary object. key (str): key whose value is to be validated. validation_fun (function): function used to validate the value of `key`. Rais...
def absdeg(deg): '''Change from signed degrees to 0-180 or 0-360 ranges deg: ndarray Movement data in pitch, roll, yaw (degrees) Returns ------- deg_abs: ndarray Movement translated from -180:180/-90:90 degrees to 0:360/0:180 degrees Example ------- deg = numpy.array([...
Change from signed degrees to 0-180 or 0-360 ranges deg: ndarray Movement data in pitch, roll, yaw (degrees) Returns ------- deg_abs: ndarray Movement translated from -180:180/-90:90 degrees to 0:360/0:180 degrees Example ------- deg = numpy.array([-170, -120, 0, 90]) ...
def match_classes(self, el, classes): """Match element's classes.""" current_classes = self.get_classes(el) found = True for c in classes: if c not in current_classes: found = False break return found
Match element's classes.
def _fit_newton(self, fitcache=None, ebin=None, **kwargs): """Fast fitting method using newton fitter.""" tol = kwargs.get('tol', self.config['optimizer']['tol']) max_iter = kwargs.get('max_iter', self.config['optimizer']['max_iter']) init_lambda = kwargs.g...
Fast fitting method using newton fitter.
def update(self): """ Stops and starts the framework, if the framework is active. :raise BundleException: Something wrong occurred while stopping or starting the framework. """ with self._lock: if self._state == Bundle.ACTIVE: ...
Stops and starts the framework, if the framework is active. :raise BundleException: Something wrong occurred while stopping or starting the framework.
def install_lib(url, replace_existing=False, fix_wprogram=True): """install library from web or local files system. :param url: web address or file path :param replace_existing: bool :rtype: None """ d = tmpdir(tmpdir()) f = download(url) Archive(f).extractall(d) clean_dir(d) ...
install library from web or local files system. :param url: web address or file path :param replace_existing: bool :rtype: None
def intervals_to_fragment_list(self, text_file, time_values): """ Transform a list of at least 4 time values (corresponding to at least 3 intervals) into a sync map fragment list and store it internally. The first interval is a HEAD, the last is a TAIL. For example: ...
Transform a list of at least 4 time values (corresponding to at least 3 intervals) into a sync map fragment list and store it internally. The first interval is a HEAD, the last is a TAIL. For example: time_values=[0.000, 1.000, 2.000, 3.456] => [(0.000, 1.000), (1.000, 2.00...
def active(self, include=None): """ Return all active views. """ return self._get(self._build_url(self.endpoint.active(include=include)))
Return all active views.
def find_module(module, paths=None): """Just like 'imp.find_module()', but with package support""" parts = module.split('.') while parts: part = parts.pop(0) f, path, (suffix, mode, kind) = info = imp.find_module(part, paths) if kind == PKG_DIRECTORY: parts = parts or ...
Just like 'imp.find_module()', but with package support
def db_create(name, character_set=None, collate=None, **connection_args): ''' Adds a databases to the MySQL server. name The name of the database to manage character_set The character set, if left empty the MySQL default will be used collate The collation, if left empty th...
Adds a databases to the MySQL server. name The name of the database to manage character_set The character set, if left empty the MySQL default will be used collate The collation, if left empty the MySQL default will be used CLI Example: .. code-block:: bash salt...
def getSets(self, **kwargs): ''' A way to get different sets from a query. All parameters are optional, but you should probably use some (so that you get results) :param str query: The thing you're searching for. :param str theme: The theme of the set. :param str subthem...
A way to get different sets from a query. All parameters are optional, but you should probably use some (so that you get results) :param str query: The thing you're searching for. :param str theme: The theme of the set. :param str subtheme: The subtheme of the set. :param str se...
def convert_complexFaultSource(self, node): """ Convert the given node into a complex fault object. :param node: a node with tag areaGeometry :returns: a :class:`openquake.hazardlib.source.ComplexFaultSource` instance """ geom = node.complexFaultGeometr...
Convert the given node into a complex fault object. :param node: a node with tag areaGeometry :returns: a :class:`openquake.hazardlib.source.ComplexFaultSource` instance
def get_workflow_info(func_list): """Return function info, go through lists recursively.""" funcs = [] for item in func_list: if item is None: continue if isinstance(item, list): funcs.append(get_workflow_info(item)) else: funcs.append(get_func_inf...
Return function info, go through lists recursively.
def instance_from_str(instance_str): """ Given an instance string in the form "app.Model:pk", returns a tuple of ``(model, instance)``. If the pk part is empty, ``instance`` will be ``None``. Raises ``ValueError`` on invalid model strings or missing instances. """ match = instance_str_re.mat...
Given an instance string in the form "app.Model:pk", returns a tuple of ``(model, instance)``. If the pk part is empty, ``instance`` will be ``None``. Raises ``ValueError`` on invalid model strings or missing instances.
def delete_subtree(self, nodes): # noqa: D302 r""" Delete nodes (and their sub-trees) from the tree. :param nodes: Node(s) to delete :type nodes: :ref:`NodeName` or list of :ref:`NodeName` :raises: * RuntimeError (Argument \`nodes\` is not valid) * RuntimeE...
r""" Delete nodes (and their sub-trees) from the tree. :param nodes: Node(s) to delete :type nodes: :ref:`NodeName` or list of :ref:`NodeName` :raises: * RuntimeError (Argument \`nodes\` is not valid) * RuntimeError (Node *[node_name]* not in tree) Using th...
def table_repr(columns, rows, data, padding=2): """Generate a table for cli output""" padding = ' ' * padding column_lengths = [len(column) for column in columns] for row in rows: for i, column in enumerate(columns): item = str(data[row][column]) column_lengths[i] = max(l...
Generate a table for cli output
def get_object(self, view_name, view_args, view_kwargs): """ Return the object corresponding to a matched URL. Takes the matched URL conf arguments, and should return an object instance, or raise an `ObjectDoesNotExist` exception. """ lookup_value = view_kwargs.get(self....
Return the object corresponding to a matched URL. Takes the matched URL conf arguments, and should return an object instance, or raise an `ObjectDoesNotExist` exception.
def BVV(value, size=None, **kwargs): """ Creates a bit-vector value (i.e., a concrete value). :param value: The value. Either an integer or a string. If it's a string, it will be interpreted as the bytes of a big-endian constant. :param size: The size (in bits) of the bit-vecto...
Creates a bit-vector value (i.e., a concrete value). :param value: The value. Either an integer or a string. If it's a string, it will be interpreted as the bytes of a big-endian constant. :param size: The size (in bits) of the bit-vector. Optional if you provide a string, required for...
def reset(self): '''Resets the stream pointer to the beginning of the file.''' if self.__row_number > self.__sample_size: self.__parser.reset() self.__extract_sample() self.__extract_headers() self.__row_number = 0
Resets the stream pointer to the beginning of the file.
def _pre_job_handling(self, job): # pylint:disable=arguments-differ """ Some pre job-processing tasks, like update progress bar. :param CFGJob job: The CFGJob instance. :return: None """ if self._low_priority: self._release_gil(len(self._nodes), 20, 0.0001)...
Some pre job-processing tasks, like update progress bar. :param CFGJob job: The CFGJob instance. :return: None
def __get_doc_block_parts_wrapper(self): """ Generates the DocBlock parts to be used by the wrapper generator. """ self.__get_doc_block_parts_source() helper = self._get_data_type_helper() parameters = list() for parameter_info in self._parameters: p...
Generates the DocBlock parts to be used by the wrapper generator.
def deprecated(function): # pylint: disable=invalid-name """Decorator to mark functions or methods as deprecated.""" def IssueDeprecationWarning(*args, **kwargs): """Issue a deprecation warning.""" warnings.simplefilter('default', DeprecationWarning) warnings.warn('Call to deprecated function: {0:s}.'...
Decorator to mark functions or methods as deprecated.
def _proc_sparse(self, tarfile): """Process a GNU sparse header plus extra headers. """ # We already collected some sparse structures in frombuf(). structs, isextended, origsize = self._sparse_structs del self._sparse_structs # Collect sparse structures from extended hea...
Process a GNU sparse header plus extra headers.
def get(self, artifact): """Gets the coordinate with the correct version for the given artifact coordinate. :param M2Coordinate artifact: the coordinate to lookup. :return: a coordinate which is the same as the input, but with the correct pinned version. If this artifact set does not pin a version fo...
Gets the coordinate with the correct version for the given artifact coordinate. :param M2Coordinate artifact: the coordinate to lookup. :return: a coordinate which is the same as the input, but with the correct pinned version. If this artifact set does not pin a version for the input artifact, this just ...
def backdate(res, date=None, as_datetime=False, fmt='%Y-%m-%d'): """ get past date based on currect date """ if res is None: return None if date is None: date = datetime.datetime.now() else: try: date = parse_date(date) except Exception as e: pass...
get past date based on currect date
def pause_and_wait_for_user(self, timeout=None, prompt_text='Click to resume (WebDriver is paused)'): """Injects a radio button into the page and waits for the user to click it; will raise an exception if the radio to resume is never checked @return: None """ timeout = timeout i...
Injects a radio button into the page and waits for the user to click it; will raise an exception if the radio to resume is never checked @return: None
def verify_order(self, hostname, domain, location, hourly, flavor, router=None): """Verifies an order for a dedicated host. See :func:`place_order` for a list of available options. """ create_options = self._generate_create_dict(hostname=hostname, ...
Verifies an order for a dedicated host. See :func:`place_order` for a list of available options.
async def pulse(self, *args, **kwargs): """ Publish a Pulse Message Publish a message on pulse with the given `routingKey`. This method takes input: ``v1/pulse-request.json#`` This method is ``experimental`` """ return await self._makeApiCall(self.funcinfo["pu...
Publish a Pulse Message Publish a message on pulse with the given `routingKey`. This method takes input: ``v1/pulse-request.json#`` This method is ``experimental``
def copy(self, name=None, description=None, meta=None): """ Create a copy of the current object (may alter the container's name, description, and update the metadata if needed). """ cls = self.__class__ kwargs = self._rel(copy=True) kwargs.update(self._data(copy=T...
Create a copy of the current object (may alter the container's name, description, and update the metadata if needed).
def _merge_objects(tref, merged, obj): """ Merge the snapshot size information of multiple tracked objects. The tracked object `obj` is scanned for size information at time `tref`. The sizes are merged into **Asized** instance `merged`. """ size = None for (timestamp, tsize) in obj.snapshot...
Merge the snapshot size information of multiple tracked objects. The tracked object `obj` is scanned for size information at time `tref`. The sizes are merged into **Asized** instance `merged`.
def H(self, H): """ Set the enthalpy of the package to the specified value, and recalculate it's temperature. :param H: The new enthalpy value. [kWh] """ self._H = H self._T = self._calculate_T(H)
Set the enthalpy of the package to the specified value, and recalculate it's temperature. :param H: The new enthalpy value. [kWh]
def dict(self, **kwargs): """ Dictionary representation """ return dict( time = self.timestamp, event_data = self.event_data, event_type = self.event_type, partition = self.partition, ...
Dictionary representation
def parse_unifrac_v1_8(unifrac, file_data): """ Function to parse data from older version of unifrac file obtained from Qiime version 1.8 and earlier. :type unifrac: dict :param unifracFN: The path to the unifrac results file :type file_data: list :param file_data: Unifrac data lines after...
Function to parse data from older version of unifrac file obtained from Qiime version 1.8 and earlier. :type unifrac: dict :param unifracFN: The path to the unifrac results file :type file_data: list :param file_data: Unifrac data lines after stripping whitespace characters.
def login(team=None): """ Authenticate. Launches a web browser and asks the user for a token. """ _check_team_id(team) _check_team_exists(team) _check_team_login(team) login_url = "%s/login" % get_registry_url(team) print("Launching a web browser...") print("If that didn't wor...
Authenticate. Launches a web browser and asks the user for a token.
def normalize_key_phrases (path, ranks, stopwords=None, spacy_nlp=None, skip_ner=True): """ collect keyphrases, named entities, etc., while removing stop words """ global STOPWORDS, SPACY_NLP # set up the stop words if (type(stopwords) is list) or (type(stopwords) is set): # explicit co...
collect keyphrases, named entities, etc., while removing stop words
def provides_defaults_for(self, rule: 'Rule', **values: Any) -> bool: """Returns true if this rule provides defaults for the argument and values.""" defaults_match = all( values[key] == self.defaults[key] for key in self.defaults if key in values # noqa: S101, E501 ) return ...
Returns true if this rule provides defaults for the argument and values.
def mutex(func): """use a thread lock on current method, if self.lock is defined""" def wrapper(*args, **kwargs): """Decorator Wrapper""" lock = args[0].lock lock.acquire(True) try: return func(*args, **kwargs) except: raise finally: ...
use a thread lock on current method, if self.lock is defined
def address_exists(name, addressname=None, vsys=1, ipnetmask=None, iprange=None, fqdn=None, description=None, commit=False): ''' Ensures that an address object exists in the confi...
Ensures that an address object exists in the configured state. If it does not exist or is not configured with the specified attributes, it will be adjusted to match the specified values. This module will only process a single address type (ip-netmask, ip-range, or fqdn). It will process the specified value...
def list_cards(self, *args, **kwargs): """ List the cards of the customer. :param page: the page number :type page: int|None :param per_page: number of customers per page. It's a good practice to increase this number if you know that you will need a lot of payments. ...
List the cards of the customer. :param page: the page number :type page: int|None :param per_page: number of customers per page. It's a good practice to increase this number if you know that you will need a lot of payments. :type per_page: int|None :return: The cards of ...
def get_pages(self, include_draft=False): """ Get all custom pages (supported formats, excluding other files like '.js', '.css', '.html'). :param include_draft: return draft page or not :return: an iterable of Page objects """ def pages_generator(pages_root_path...
Get all custom pages (supported formats, excluding other files like '.js', '.css', '.html'). :param include_draft: return draft page or not :return: an iterable of Page objects
def threshold(self, messy_data, recall_weight=1.5): # pragma: no cover """ Returns the threshold that maximizes the expected F score, a weighted average of precision and recall for a sample of data. Arguments: messy_data -- Dictionary of records from messy dataset, wher...
Returns the threshold that maximizes the expected F score, a weighted average of precision and recall for a sample of data. Arguments: messy_data -- Dictionary of records from messy dataset, where the keys are record_ids and the values are dictionaries with ...
def get_child_books(self, book_id): """Gets the child books of the given ``id``. arg: book_id (osid.id.Id): the ``Id`` of the ``Book`` to query return: (osid.commenting.BookList) - the child books of the ``id`` raise: NotFound - a ``Book`` identified ...
Gets the child books of the given ``id``. arg: book_id (osid.id.Id): the ``Id`` of the ``Book`` to query return: (osid.commenting.BookList) - the child books of the ``id`` raise: NotFound - a ``Book`` identified by ``Id is`` not found raise: NullArgu...
def list_extensions(): ''' List up available extensions. Note: It may not work on some platforms/environments since it depends on the directory structure of the namespace packages. Returns: list of str Names of available extensions. ''' import nnabla_ext.cpu from o...
List up available extensions. Note: It may not work on some platforms/environments since it depends on the directory structure of the namespace packages. Returns: list of str Names of available extensions.
def ReadTriggers(self, collection_link, options=None): """Reads all triggers in a collection. :param str collection_link: The link to the document collection. :param dict options: The request options for the request. :return: Query Iterable of Trigge...
Reads all triggers in a collection. :param str collection_link: The link to the document collection. :param dict options: The request options for the request. :return: Query Iterable of Triggers. :rtype: query_iterable.QueryIterable
def _handleSmsStatusReport(self, notificationLine): """ Handler for SMS status reports """ self.log.debug('SMS status report received') cdsiMatch = self.CDSI_REGEX.match(notificationLine) if cdsiMatch: msgMemory = cdsiMatch.group(1) msgIndex = cdsiMatch.group(2) ...
Handler for SMS status reports
def ndim(self): """Number of dimensions of the grid.""" try: return self.__ndim except AttributeError: ndim = len(self.coord_vectors) self.__ndim = ndim return ndim
Number of dimensions of the grid.
def remove(args): """ Remove the feed given in <args> """ session = c.Session(args) if not args["name"] in session.feeds: sys.exit("You don't have a feed with that name.") inputtext = ("Are you sure you want to remove the {} " " feed? (y/N) ").format(args["name"]) re...
Remove the feed given in <args>