code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def proxy_uri(self, value): """ Set the Proxy-Uri option of a request. :param value: the Proxy-Uri value """ option = Option() option.number = defines.OptionRegistry.PROXY_URI.number option.value = str(value) self.add_option(option)
Set the Proxy-Uri option of a request. :param value: the Proxy-Uri value
def stereo_bm_preset(self, value): """Set private ``_stereo_bm_preset`` and reset ``_block_matcher``.""" if value in (cv2.STEREO_BM_BASIC_PRESET, cv2.STEREO_BM_FISH_EYE_PRESET, cv2.STEREO_BM_NARROW_PRESET): self._bm_preset = value else: ...
Set private ``_stereo_bm_preset`` and reset ``_block_matcher``.
def add_val(self, subj: Node, pred: URIRef, json_obj: JsonObj, json_key: str, valuetype: Optional[URIRef] = None) -> Optional[BNode]: """ Add the RDF representation of val to the graph as a target of subj, pred. Note that FHIR lists are represented as a list of BNODE objects wit...
Add the RDF representation of val to the graph as a target of subj, pred. Note that FHIR lists are represented as a list of BNODE objects with a fhir:index discrimanant :param subj: graph subject :param pred: predicate :param json_obj: object containing json_key :param json_key:...
def run_dssp(pdb, path=True, outfile=None): """Uses DSSP to find helices and extracts helices from a pdb file or string. Parameters ---------- pdb : str Path to pdb file or string. path : bool, optional Indicates if pdb is a path or a string. outfile : str, optional File...
Uses DSSP to find helices and extracts helices from a pdb file or string. Parameters ---------- pdb : str Path to pdb file or string. path : bool, optional Indicates if pdb is a path or a string. outfile : str, optional Filepath for storing the dssp output. Returns ...
def resolve(self, obj): """ Resolve a reference to an entry point or a variable in a module. If ``obj`` is a ``module:varname`` reference to an object, :func:`resolve_reference` is used to resolve it. If it is a string of any other kind, the named entry point is loaded from this...
Resolve a reference to an entry point or a variable in a module. If ``obj`` is a ``module:varname`` reference to an object, :func:`resolve_reference` is used to resolve it. If it is a string of any other kind, the named entry point is loaded from this container's namespace. Otherwise, ``obj`` i...
def get_amount_of_tweets(self): """ Returns current amount of tweets available within this instance :returns: The amount of tweets currently available :raises: TwitterSearchException """ if not self.__response: raise TwitterSearchException(1013) return (len...
Returns current amount of tweets available within this instance :returns: The amount of tweets currently available :raises: TwitterSearchException
def format(self, formatter, subset=None): """ Format the text display value of cells. .. versionadded:: 0.18.0 Parameters ---------- formatter : str, callable, or dict subset : IndexSlice An argument to ``DataFrame.loc`` that restricts which elements...
Format the text display value of cells. .. versionadded:: 0.18.0 Parameters ---------- formatter : str, callable, or dict subset : IndexSlice An argument to ``DataFrame.loc`` that restricts which elements ``formatter`` is applied to. Returns ...
def archive(self): """ Archives (soft delete) all the records matching the query. This assumes that the model allows archiving (not many do - especially transactional documents). Internal implementation sets the active field to False. """ ids = self.rpc_model.se...
Archives (soft delete) all the records matching the query. This assumes that the model allows archiving (not many do - especially transactional documents). Internal implementation sets the active field to False.
def get_window(window, Nx, fftbins=True): '''Compute a window function. This is a wrapper for `scipy.signal.get_window` that additionally supports callable or pre-computed windows. Parameters ---------- window : string, tuple, number, callable, or list-like The window specification: ...
Compute a window function. This is a wrapper for `scipy.signal.get_window` that additionally supports callable or pre-computed windows. Parameters ---------- window : string, tuple, number, callable, or list-like The window specification: - If string, it's the name of the window f...
def _read_opt_ilnp(self, code, *, desc): """Read HOPOPT ILNP Nonce option. Structure of HOPOPT ILNP Nonce option [RFC 6744]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-...
Read HOPOPT ILNP Nonce option. Structure of HOPOPT ILNP Nonce option [RFC 6744]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ...
def _populate_user(self): """ Populates our User object with information from the LDAP directory. """ self._populate_user_from_attributes() self._populate_user_from_group_memberships() self._populate_user_from_dn_regex() self._populate_user_from_dn_regex_negation(...
Populates our User object with information from the LDAP directory.
def etree_write(tree, stream): """ Write XML ElementTree 'root' content into 'stream'. :param tree: XML ElementTree object :param stream: File or file-like object can write to """ try: tree.write(stream, encoding="utf-8", xml_declaration=True) except TypeError: tree.write(st...
Write XML ElementTree 'root' content into 'stream'. :param tree: XML ElementTree object :param stream: File or file-like object can write to
def artist_update(self, artist_id, name=None, urls=None, alias=None, group=None): """Function to update artists (Requires Login) (UNTESTED). Only the artist_id parameter is required. The other parameters are optional. Parameters: artist_id (int): The i...
Function to update artists (Requires Login) (UNTESTED). Only the artist_id parameter is required. The other parameters are optional. Parameters: artist_id (int): The id of thr artist to update (Type: INT). name (str): The artist's name. urls (str): A list of...
def get_connection_info(connection_file=None, unpack=False, profile=None): """Return the connection information for the current Kernel. Parameters ---------- connection_file : str [optional] The connection file to be used. Can be given by absolute path, or IPython will search in the...
Return the connection information for the current Kernel. Parameters ---------- connection_file : str [optional] The connection file to be used. Can be given by absolute path, or IPython will search in the security directory of a given profile. If run from IPython, ...
def process(self, now): """Perform connection state processing.""" if self._pn_connection is None: LOG.error("Connection.process() called on destroyed connection!") return 0 # do nothing until the connection has been opened if self._pn_connection.state & proton.E...
Perform connection state processing.
def lookupAll(data, configFields, lookupType, db, histObj={}): """ Return a record after having cleaning rules of specified type applied to all fields in the config :param dict data: single record (dictionary) to which cleaning rules should be applied :param dict configFields: "fields" object from DWM ...
Return a record after having cleaning rules of specified type applied to all fields in the config :param dict data: single record (dictionary) to which cleaning rules should be applied :param dict configFields: "fields" object from DWM config (see DataDictionary) :param string lookupType: Type of lookup to...
def hdb_disk_interface(self, hdb_disk_interface): """ Sets the hda disk interface for this QEMU VM. :param hdb_disk_interface: QEMU hdb disk interface """ self._hdb_disk_interface = hdb_disk_interface log.info('QEMU VM "{name}" [{id}] has set the QEMU hdb disk interface...
Sets the hda disk interface for this QEMU VM. :param hdb_disk_interface: QEMU hdb disk interface
def choices(self): """ Retrieve choices from API if possible""" if not self._choices: gandi = self.gandi or GandiContextHelper() self._choices = self._get_choices(gandi) if not self._choices: api = gandi.get_api_connector() gandi.echo('...
Retrieve choices from API if possible
def read(self, file_p): """Reads an OVF file into the appliance object. This method succeeds if the OVF is syntactically valid and, by itself, without errors. The mere fact that this method returns successfully does not mean that VirtualBox supports all features requested by the...
Reads an OVF file into the appliance object. This method succeeds if the OVF is syntactically valid and, by itself, without errors. The mere fact that this method returns successfully does not mean that VirtualBox supports all features requested by the appliance; this can only be examin...
def get_Tsys(calON_obs,calOFF_obs,calflux,calfreq,spec_in,oneflux=False,**kwargs): ''' Returns frequency dependent system temperature given observations on and off a calibrator source Parameters ---------- (See diode_spec()) ''' return diode_spec(calON_obs,calOFF_obs,calflux,calfreq,spec_in...
Returns frequency dependent system temperature given observations on and off a calibrator source Parameters ---------- (See diode_spec())
def get_celery_app( name=os.getenv( "CELERY_NAME", "worker"), auth_url=os.getenv( "BROKER_URL", "redis://localhost:6379/9"), backend_url=os.getenv( "BACKEND_URL", "redis://localhost:6379/10"), include_tasks=[], ...
get_celery_app :param name: name for this app :param auth_url: celery broker :param backend_url: celery backend :param include_tasks: list of modules containing tasks to add :param ssl_options: security options dictionary :param trasport_options: transport options dictionary :param path_to_...
def get_option_lists(self): """ A hook to override the option lists used to generate option names and defaults. """ return [self.get_option_list()] + \ [option_list for name, description, option_list in self.get_option_groups()...
A hook to override the option lists used to generate option names and defaults.
def _get_imports_h(self, data_types): """Emits all necessary header file imports for the given Stone data type.""" if not isinstance(data_types, list): data_types = [data_types] import_classes = [] for data_type in data_types: if is_user_defined_type(data_type)...
Emits all necessary header file imports for the given Stone data type.
def p_term_var(self, p): ''' term : VAR ''' _LOGGER.debug("term -> VAR") # TODO: determine the type of the var if p[1] not in self._VAR_VALUES: if self._autodefine_vars: self._VAR_VALUES[p[1]] = TypedClass(None, TypedClass.UNKNOWN) ...
term : VAR
def split(pattern, string, maxsplit=0, flags=0): """Split the source string by the occurrences of the pattern, returning a list containing the resulting substrings.""" return _compile(pattern, flags).split(string, maxsplit)
Split the source string by the occurrences of the pattern, returning a list containing the resulting substrings.
def align_texts(source_blocks, target_blocks, params = LanguageIndependent): """Creates the sentence alignment of two texts. Texts can consist of several blocks. Block boundaries cannot be crossed by sentence alignment links. Each block consists of a list that contains the lengths (in characters) of...
Creates the sentence alignment of two texts. Texts can consist of several blocks. Block boundaries cannot be crossed by sentence alignment links. Each block consists of a list that contains the lengths (in characters) of the sentences in this block. @param source_blocks: The list of blocks ...
def make_graph_pygraphviz(self, recs, nodecolor, edgecolor, dpi, draw_parents=True, draw_children=True): """Draw AMIGO style network, lineage containing one query record.""" import pygraphviz as pgv grph = pgv.AGraph(name="GO tree") ...
Draw AMIGO style network, lineage containing one query record.
def mean_min_time_distance(item_a, item_b, max_value): """ Calculate the mean time difference among the time steps in each object. Args: item_a: STObject from the first set in TrackMatcher item_b: STObject from the second set in TrackMatcher max_value: Maximum distance value used as...
Calculate the mean time difference among the time steps in each object. Args: item_a: STObject from the first set in TrackMatcher item_b: STObject from the second set in TrackMatcher max_value: Maximum distance value used as scaling value and upper constraint. Returns: Distance...
def do_dir(self, args, unknown): """List contents of current directory.""" # No arguments for this command if unknown: self.perror("dir does not take any positional arguments:", traceback_war=False) self.do_help('dir') self._last_result = cmd2.CommandResult(''...
List contents of current directory.
def resolve_dotted_attribute(obj, attr, allow_dotted_names=True): """resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d Resolves a dotted attribute name to an object. Raises an AttributeError if any attribute in the chain starts with a '_'. If the optional allow_dotted_names argument is false, dots are ...
resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d Resolves a dotted attribute name to an object. Raises an AttributeError if any attribute in the chain starts with a '_'. If the optional allow_dotted_names argument is false, dots are not supported and this function operates similar to getattr(obj, attr...
def get_rendered_objects(self): """Render objects""" objects = self.objects if isinstance(objects, str): objects = getattr(self.object, objects).all() return [ self.get_rendered_object(obj) for obj in objects ]
Render objects
def set(self, document_data, merge=False): """Replace the current document in the Firestore database. A write ``option`` can be specified to indicate preconditions of the "set" operation. If no ``option`` is specified and this document doesn't exist yet, this method will create it. ...
Replace the current document in the Firestore database. A write ``option`` can be specified to indicate preconditions of the "set" operation. If no ``option`` is specified and this document doesn't exist yet, this method will create it. Overwrites all content for the document with the ...
def _dict_from_terse_tabular( names: List[str], inp: str, transformers: Dict[str, Callable[[str], Any]] = {})\ -> List[Dict[str, Any]]: """ Parse NMCLI terse tabular output into a list of Python dict. ``names`` is a list of strings of field names to apply to the input data, ...
Parse NMCLI terse tabular output into a list of Python dict. ``names`` is a list of strings of field names to apply to the input data, which is assumed to be colon separated. ``inp`` is the input as a string (i.e. already decode()d) from nmcli ``transformers`` is a dict mapping field names to callabl...
def resnet_v2(inputs, block_fn, layer_blocks, filters, data_format="channels_first", is_training=False, is_cifar=False, use_td=False, targeting_rate=None, keep_prob=None): """Resnet model. ...
Resnet model. Args: inputs: `Tensor` images. block_fn: `function` for the block to use within the model. Either `residual_block` or `bottleneck_block`. layer_blocks: list of 3 or 4 `int`s denoting the number of blocks to include in each of the 3 or 4 block groups. Each group consists of blo...
def help_center_articles_search(self, category=None, label_names=None, locale=None, query=None, section=None, updated_after=None, updated_before=None, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/search#search-articles" api_path = "/api/v2/help_center/articles/search.json" ...
https://developer.zendesk.com/rest_api/docs/help_center/search#search-articles
def select_many_with_correspondence( self, collection_selector=identity, result_selector=KeyedElement): '''Projects each element of a sequence to an intermediate new sequence, and flattens the resulting sequence, into one sequence and uses a selector function ...
Projects each element of a sequence to an intermediate new sequence, and flattens the resulting sequence, into one sequence and uses a selector function to incorporate the corresponding source for each item in the result sequence. Note: This method uses deferred execution. Args...
def gfuds(udfuns, udqdec, relate, refval, adjust, step, nintvls, cnfine, result): """ Perform a GF search on a user defined scalar quantity. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfuds_c.html :param udfuns: Name of the routine that computes the scalar quantity of interest at some ti...
Perform a GF search on a user defined scalar quantity. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfuds_c.html :param udfuns: Name of the routine that computes the scalar quantity of interest at some time. :type udfuns: ctypes.CFunctionType :param udqdec: Name of the routine that compute...
def all(self, axis=None, *args, **kwargs): """ Tests whether all elements evaluate True Returns ------- all : bool See Also -------- numpy.all """ nv.validate_all(args, kwargs) values = self.sp_values if len(values) != l...
Tests whether all elements evaluate True Returns ------- all : bool See Also -------- numpy.all
def setValues(nxG, nyG, iBeg, iEnd, jBeg, jEnd, data): """ Set setValues @param nxG number of global cells in x @param nyG number of global cells in y @param iBeg global starting index in x @param iEnd global ending index in x @param jBeg global starting index in y @param jEnd global end...
Set setValues @param nxG number of global cells in x @param nyG number of global cells in y @param iBeg global starting index in x @param iEnd global ending index in x @param jBeg global starting index in y @param jEnd global ending index in y @param data local array
def find_children(self, linespec): """Find lines and immediate children that match the linespec regex. :param linespec: regular expression of line to match :returns: list of lines. These correspond to the lines that were matched and their immediate children """ res =...
Find lines and immediate children that match the linespec regex. :param linespec: regular expression of line to match :returns: list of lines. These correspond to the lines that were matched and their immediate children
def GET_AUTH(self, courseid): # pylint: disable=arguments-differ """ GET request """ course, __ = self.get_course_and_check_rights(courseid) return self.page(course)
GET request
def translate_bit_for_bit(data): """ Translates data where data["Type"]=="Bit for Bit" """ headers = sorted(data.get("Headers", [])) table = '\\FloatBarrier \n \\section{$NAME} \n'.replace('$NAME', data.get("Title", "table")) table += '\\begin{table}[!ht] \n \\begin{center}' # Set the number of colu...
Translates data where data["Type"]=="Bit for Bit"
def ring(surf, xy, r, width, color): """Draws a ring""" r2 = r - width x0, y0 = xy x = r2 y = 0 err = 0 # collect points of the inner circle right = {} while x >= y: right[x] = y right[y] = x right[-x] = y right[-y] = x y += 1 if er...
Draws a ring
def put_property(elt, key, value, ttl=None, ctx=None): """Put properties in elt. :param elt: properties elt to put. Not None methods. :param number ttl: If not None, property time to leave. :param ctx: elt ctx from where put properties. Equals elt if None. It allows to get function properties r...
Put properties in elt. :param elt: properties elt to put. Not None methods. :param number ttl: If not None, property time to leave. :param ctx: elt ctx from where put properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is d...
def _request(self, lat_min, lon_min, lat_max, lon_max, start, end, picture_size=None, set_=None, map_filter=None): """ Internal method to send requests to the Panoramio data API. :param lat_min: Minimum latitude of the bounding box :type lat_min: float :param lon_min...
Internal method to send requests to the Panoramio data API. :param lat_min: Minimum latitude of the bounding box :type lat_min: float :param lon_min: Minimum longitude of the bounding box :type lon_min: float :param lat_max: Maximum latitude o...
def send_custom_host_notification(self, host, options, author, comment): """DOES NOTHING (Should send a custom notification) Format of the line that triggers function call:: SEND_CUSTOM_HOST_NOTIFICATION;<host_name>;<options>;<author>;<comment> :param host: host to send notif for ...
DOES NOTHING (Should send a custom notification) Format of the line that triggers function call:: SEND_CUSTOM_HOST_NOTIFICATION;<host_name>;<options>;<author>;<comment> :param host: host to send notif for :type host: alignak.object.host.Host :param options: notification options...
def delta(self, signature): "Generates delta for remote file via API using local file's signature." return self.api.post('path/sync/delta', self.path, signature=signature)
Generates delta for remote file via API using local file's signature.
def run_gatk(self, params, tmp_dir=None, log_error=True, data=None, region=None, memscale=None, parallel_gc=False, ld_preload=False): """Top level interface to running a GATK command. ld_preload injects required libraries for Java JNI calls: https://gatkforums.broadinstitute.or...
Top level interface to running a GATK command. ld_preload injects required libraries for Java JNI calls: https://gatkforums.broadinstitute.org/gatk/discussion/8810/something-about-create-pon-workflow
def reset(self, document, parent, level): """Reset the state of state machine. After reset, self and self.state can be used to passed to docutils.parsers.rst.Directive.run Parameters ---------- document: docutils document Current document of the node. ...
Reset the state of state machine. After reset, self and self.state can be used to passed to docutils.parsers.rst.Directive.run Parameters ---------- document: docutils document Current document of the node. parent: parent node Parent node that wi...
def _writeGpoScript(psscript=False): ''' helper function to write local GPO startup/shutdown script scripts are stored in scripts.ini and psscripts.ini files in ``WINDIR\\System32\\GroupPolicy\\Machine|User\\Scripts`` these files have the hidden attribute set files have following format: ...
helper function to write local GPO startup/shutdown script scripts are stored in scripts.ini and psscripts.ini files in ``WINDIR\\System32\\GroupPolicy\\Machine|User\\Scripts`` these files have the hidden attribute set files have following format: empty line [Startup] 0CmdLine...
def addResourceFile(self, pid, resource_file, resource_filename=None, progress_callback=None): """ Add a new file to an existing resource :param pid: The HydroShare ID of the resource :param resource_file: a read-only binary file-like object (i.e. opened with the flag 'rb') or a string ...
Add a new file to an existing resource :param pid: The HydroShare ID of the resource :param resource_file: a read-only binary file-like object (i.e. opened with the flag 'rb') or a string representing path to file to be uploaded as part of the new resource :param resource_filename: ...
def _repos_checked(self, worker, output, error): """Callback for _check_repos.""" if worker.repo in self._checking_repos: self._checking_repos.remove(worker.repo) if output: self._valid_repos.append(worker.repo) if len(self._checking_repos) == 0: sel...
Callback for _check_repos.
def do_update(pool,request,models): "unlike *_check() below, update doesn't worry about missing children" return {k:fkapply(models,pool,process_update,missing_update,k,v) for k,v in request.items()}
unlike *_check() below, update doesn't worry about missing children
def combinations(iterable, r): """Calculate combinations >>> list(combinations('ABCD',2)) [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']] >>> list(combinations(range(4), 3)) [[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]] Args: iterable: Any iterable object. ...
Calculate combinations >>> list(combinations('ABCD',2)) [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']] >>> list(combinations(range(4), 3)) [[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]] Args: iterable: Any iterable object. r: Size of combination. Yield...
def get_generated_project_files(self, tool): """ Get generated project files, the content depends on a tool. Look at tool implementation """ exporter = ToolsSupported().get_tool(tool) return exporter(self.generated_files[tool], self.settings).get_generated_project_files()
Get generated project files, the content depends on a tool. Look at tool implementation
def destroy(self, eip_or_aid, disassociate=False): """Release an EIP. If the EIP was allocated for a VPC instance, an AllocationId(aid) must be provided instead of a PublicIp. Setting disassociate to True will attempt to disassociate the IP before releasing it (required for associated no...
Release an EIP. If the EIP was allocated for a VPC instance, an AllocationId(aid) must be provided instead of a PublicIp. Setting disassociate to True will attempt to disassociate the IP before releasing it (required for associated nondefault VPC instances).
def compute_toc_line_indentation_spaces( header_type_curr: int = 1, header_type_prev: int = 0, no_of_indentation_spaces_prev: int = 0, parser: str = 'github', ordered: bool = False, list_marker: str = '-', list_marker_log: list = build_list_marker_log('github', '....
r"""Compute the number of indentation spaces for the TOC list element. :parameter header_type_curr: the current type of header (h[1-Inf]). Defaults to ``1``. :parameter header_type_prev: the previous type of header (h[1-Inf]). Defaults to ``0``. :parameter no_of_indentation_spaces_prev: t...
def realimag_files(xscript=0, yscript="d[1]+1j*d[2]", eyscript=None, exscript=None, paths=None, g=None, **kwargs): """ This will load a bunch of data files, generate data based on the supplied scripts, and then plot the ydata's real and imaginary parts versus xdata. Parameters ---------- xscrip...
This will load a bunch of data files, generate data based on the supplied scripts, and then plot the ydata's real and imaginary parts versus xdata. Parameters ---------- xscript=0 Script for x data yscript='d[1]+1j*d[2]' Script for y data eyscript=None Script for y ...
def create_cloud_integration(self, **kwargs): # noqa: E501 """Create a cloud integration # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_cloud_integrat...
Create a cloud integration # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_cloud_integration(async_req=True) >>> result = thread.get() :param a...
def get(self, url, params=None): 'Make a GET request for url and return the response content as a generic lxml.objectify object' url = self.escapeUrl(url) content = six.BytesIO(self.raw(url, params=params)) # We need to make sure that the xml fits in available memory before we parse ...
Make a GET request for url and return the response content as a generic lxml.objectify object
def delete(self, r=None, w=None, dw=None, pr=None, pw=None, timeout=None): """ Delete this object from Riak. :param r: R-value, wait for this many partitions to read object before performing the put :type r: integer :param w: W-value, wait for this many p...
Delete this object from Riak. :param r: R-value, wait for this many partitions to read object before performing the put :type r: integer :param w: W-value, wait for this many partitions to respond before returning to client. :type w: integer :param dw: DW-value...
def saveWallet(self, wallet, fpath): """Save wallet into specified localtion. Returns the canonical path for the ``fpath`` where ``wallet`` has been stored. Error cases: - ``fpath`` is not inside the keyrings base dir - ValueError raised - directory part of ``fp...
Save wallet into specified localtion. Returns the canonical path for the ``fpath`` where ``wallet`` has been stored. Error cases: - ``fpath`` is not inside the keyrings base dir - ValueError raised - directory part of ``fpath`` exists and it's not a directory - ...
def spawn(self, *cmds: str) -> List[SublemonSubprocess]: """Coroutine to spawn shell commands. If `max_concurrency` is reached during the attempt to spawn the specified subprocesses, excess subprocesses will block while attempting to acquire this server's semaphore. """ ...
Coroutine to spawn shell commands. If `max_concurrency` is reached during the attempt to spawn the specified subprocesses, excess subprocesses will block while attempting to acquire this server's semaphore.
def download_static_assets(doc, destination, base_url, request_fn=make_request, url_blacklist=[], js_middleware=None, css_middleware=None, derive_filename=_derive_filename): """ Download all static assets referenced from an HTML page. The goal is to easily create HTML5 apps! Downloads JS, CS...
Download all static assets referenced from an HTML page. The goal is to easily create HTML5 apps! Downloads JS, CSS, images, and audio clips. Args: doc: The HTML page source as a string or BeautifulSoup instance. destination: The folder to download the static assets to! base_url: Th...
def evaluate_ising(linear, quad, state): """Calculate the energy of a state given the Hamiltonian. Args: linear: Linear Hamiltonian terms. quad: Quadratic Hamiltonian terms. state: Vector of spins describing the system state. Returns: Energy of the state evaluated by the gi...
Calculate the energy of a state given the Hamiltonian. Args: linear: Linear Hamiltonian terms. quad: Quadratic Hamiltonian terms. state: Vector of spins describing the system state. Returns: Energy of the state evaluated by the given energy function.
def _eq(left, right): """ Equality comparison that allows for equality between tuple and list types with equivalent elements. """ if isinstance(left, (tuple, list)) and isinstance(right, (tuple, list)): return len(left) == len(right) and all(_eq(*pair) for pair in zip(left, right)) else:...
Equality comparison that allows for equality between tuple and list types with equivalent elements.
def _set_base_dn(self): """Get Base DN from LDAP""" results = self._search( 'cn=config', '(objectClass=*)', ['nsslapd-defaultnamingcontext'], scope=ldap.SCOPE_BASE ) if results and type(results) is list: dn, attrs = results[0] ...
Get Base DN from LDAP
def create(cls, mr_spec, shard_number, shard_attempt, _writer_state=None): """Inherit docs.""" writer_spec = cls.get_params(mr_spec.mapper, allow_old=False) # Determine parameters key = cls._generate_filename(writer_spec, mr_spec.name, mr_spec.mapreduce_id, ...
Inherit docs.
def set_multivar(self, section, option, value=''): ''' This function is unique to the GitConfigParser. It will add another value for the option if it already exists, converting the option's value to a list if applicable. If "value" is a list, then any existing values for the spe...
This function is unique to the GitConfigParser. It will add another value for the option if it already exists, converting the option's value to a list if applicable. If "value" is a list, then any existing values for the specified section and option will be replaced with the list being ...
def get_context(): """Provide the context to use. This function takes care of creating new contexts in case of forks. """ pid = os.getpid() if pid not in context: context[pid] = zmq.Context() logger.debug('renewed context for PID %d', pid) return context[pid]
Provide the context to use. This function takes care of creating new contexts in case of forks.
def undo_sign_in(entry, session=None): """Delete a signed in entry. :param entry: `models.Entry` object. The entry to delete. :param session: (optional) SQLAlchemy session through which to access the database. """ # noqa if session is None: session = Session() else: session = se...
Delete a signed in entry. :param entry: `models.Entry` object. The entry to delete. :param session: (optional) SQLAlchemy session through which to access the database.
def submit(self, command="", blocksize=1, job_name="parsl.auto"): ''' The submit method takes the command string to be executed upon instantiation of a resource most often to start a pilot (such as IPP engine or even Swift-T engines). Args : - command (str) : The bash comma...
The submit method takes the command string to be executed upon instantiation of a resource most often to start a pilot (such as IPP engine or even Swift-T engines). Args : - command (str) : The bash command string to be executed. - blocksize (int) : Blocksize to be req...
def set(self, newvalue): # type: (B) -> Callable[[S], T] '''Set the focus to `newvalue`. >>> from lenses import lens >>> set_item_one_to_four = lens[1].set(4) >>> set_item_one_to_four([1, 2, 3]) [1, 4, 3] ''' def setter(state): ...
Set the focus to `newvalue`. >>> from lenses import lens >>> set_item_one_to_four = lens[1].set(4) >>> set_item_one_to_four([1, 2, 3]) [1, 4, 3]
def walk(self, address): ''' Returns a stream of pairs of node addresses and data, raising AddressNotInTree if ADDRESS is not in the tree. First the ancestors of ADDRESS (including itself) are yielded, earliest to latest, and then the descendants of ADDRESS are yielded i...
Returns a stream of pairs of node addresses and data, raising AddressNotInTree if ADDRESS is not in the tree. First the ancestors of ADDRESS (including itself) are yielded, earliest to latest, and then the descendants of ADDRESS are yielded in an unspecified order. Arguments: ...
def is_same_channel(self, left, right): """ Check if given nicknames are equal in the server's case mapping. """ return self.normalize(left) == self.normalize(right)
Check if given nicknames are equal in the server's case mapping.
def memoize(func): """ Memoization decorator for a function taking one or more arguments. """ class Memodict(dict): """ just a dict""" def __getitem__(self, *key): return dict.__getitem__(self, key) def __missing__(self, key): """ this makes it faster """ ...
Memoization decorator for a function taking one or more arguments.
def get_queryset(qs=None, app=DEFAULT_APP, db_alias=None): """ >>> get_queryset('Permission', app='django.contrib.auth').count() > 0 True """ # app = get_app(app); # print 'get_model' + repr(model) + ' app ' + repr(app) if isinstance(qs, (djmodels.Manager, djmodels.query.QuerySet)): ...
>>> get_queryset('Permission', app='django.contrib.auth').count() > 0 True
async def health_check(self) -> Iterator[HealthCheckFail]: """ Perform the checks. So far: - Make a list of the unique destination states from the transitions list, then check the health of each of them. """ ds_class = getattr(settings, 'DEFAULT_STATE', '') fo...
Perform the checks. So far: - Make a list of the unique destination states from the transitions list, then check the health of each of them.
def parse_share_url(share_url): """Return the group_id and share_token in a group's share url. :param str share_url: the share url of a group """ *__, group_id, share_token = share_url.rstrip('/').split('/') return group_id, share_token
Return the group_id and share_token in a group's share url. :param str share_url: the share url of a group
def telegram(self) -> list: """Returns list of Telegram compatible states of the RichMessage instance nested controls. Returns: telegram_controls: Telegram representation of RichMessage instance nested controls. """ telegram_controls = [control.telegr...
Returns list of Telegram compatible states of the RichMessage instance nested controls. Returns: telegram_controls: Telegram representation of RichMessage instance nested controls.
async def peek(self, task_id): """ Get task without changing its state :param task_id: Task id :return: Task instance """ args = (task_id,) res = await self.conn.call(self.__funcs['peek'], args) return self._create_task(res.body)
Get task without changing its state :param task_id: Task id :return: Task instance
def rooms_info(self, room_id=None, room_name=None): """Retrieves the information about the room.""" if room_id is not None: return self.__call_api_get('rooms.info', roomId=room_id) elif room_name is not None: return self.__call_api_get('rooms.info', roomName=room_name) ...
Retrieves the information about the room.
def avail_images(kwargs=None, call=None): ''' Return a dict of all available VM images on the cloud provider. ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ...
Return a dict of all available VM images on the cloud provider.
def get_ip_addresses(): """ :return: all knows IP Address """ LOGGER.debug("IPAddressService.get_ip_addresses") args = {'http_operation': 'GET', 'operation_path': ''} response = IPAddressService.requester.call(args) ret = None if response.rc == 0: ...
:return: all knows IP Address
def filter_backends(backends, filters=None, **kwargs): """Return the backends matching the specified filtering. Filter the `backends` list by their `configuration` or `status` attributes, or from a boolean callable. The criteria for filtering can be specified via `**kwargs` or as a callable via `filter...
Return the backends matching the specified filtering. Filter the `backends` list by their `configuration` or `status` attributes, or from a boolean callable. The criteria for filtering can be specified via `**kwargs` or as a callable via `filters`, and the backends must fulfill all specified conditions...
def collapse(self, id_user): """Collapse comment beloging to user.""" c = CmtCOLLAPSED(id_bibrec=self.id_bibrec, id_cmtRECORDCOMMENT=self.id, id_user=id_user) db.session.add(c) db.session.commit()
Collapse comment beloging to user.
def set_cookie(self, kaka, request): """Returns a http_cookiejar.Cookie based on a set-cookie header line""" if not kaka: return part = urlparse(request.url) _domain = part.hostname logger.debug("%s: '%s'", _domain, kaka) for cookie_name, morsel in kaka.ite...
Returns a http_cookiejar.Cookie based on a set-cookie header line
def make_private(self, recursive=False, future=False, client=None): """Update bucket's ACL, revoking read access for anonymous users. :type recursive: bool :param recursive: If True, this will make all blobs inside the bucket private as well. :type future: boo...
Update bucket's ACL, revoking read access for anonymous users. :type recursive: bool :param recursive: If True, this will make all blobs inside the bucket private as well. :type future: bool :param future: If True, this will make all objects created in the ...
def show(self, dump=False, indent=3, lvl="", label_lvl=""): """ Prints or returns (when "dump" is true) a hierarchical view of the packet. :param dump: determine if it prints or returns the string value :param int indent: the size of indentation for each layer :param str...
Prints or returns (when "dump" is true) a hierarchical view of the packet. :param dump: determine if it prints or returns the string value :param int indent: the size of indentation for each layer :param str lvl: additional information about the layer lvl :param str label_lvl: a...
def is_declared(self, expression_var): """ True if expression_var is declared in this constraint set """ if not isinstance(expression_var, Variable): raise ValueError(f'Expression must be a Variable (not a {type(expression_var)})') return any(expression_var is x for x in self.get_dec...
True if expression_var is declared in this constraint set
def get_lock(lockfile): """ Tries to write a lockfile containing the current pid. Excepts if the lockfile already contains the pid of a running process. Although this should prevent a lock from being granted twice, it can theoretically deny a lock unjustly in the unlikely event that the origin...
Tries to write a lockfile containing the current pid. Excepts if the lockfile already contains the pid of a running process. Although this should prevent a lock from being granted twice, it can theoretically deny a lock unjustly in the unlikely event that the original process is gone but another unrel...
async def check_permissions(self, action: str, **kwargs): """ Check if the action should be permitted. Raises an appropriate exception if the request is not permitted. """ for permission in await self.get_permissions(action=action, **kwargs): if not await ensure_asyn...
Check if the action should be permitted. Raises an appropriate exception if the request is not permitted.
def autohide(obj): """ Automatically hide setup() and teardown() methods, recursively. """ # Members on obj for name, item in six.iteritems(vars(obj)): if callable(item) and name in ('setup', 'teardown'): item = hide(item) # Recurse into class members for name, subclass i...
Automatically hide setup() and teardown() methods, recursively.
def migrate_config(self, current_config, config_to_migrate, always_update, update_defaults): """Migrate config value in current_config, updating config_to_migrate. Given the current_config object, it will attempt to find a value based on all the names given. If no name co...
Migrate config value in current_config, updating config_to_migrate. Given the current_config object, it will attempt to find a value based on all the names given. If no name could be found, then it will simply set the value to the default. If a value is found and is in the list of prev...
def get_apo(self, symbol, interval='daily', series_type='close', fastperiod=None, slowperiod=None, matype=None): """ Return the absolute price oscillator values in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: ...
Return the absolute price oscillator values in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: symbol: the symbol for the equity we want to get its data interval: time interval between two conscutive values, ...
def _get_method_kwargs(self): """ Helper method. Returns kwargs needed to filter the correct object. Can also be used to create the correct object. """ method_kwargs = { 'user': self.user, 'content_type': self.ctype, 'object_id': self.content...
Helper method. Returns kwargs needed to filter the correct object. Can also be used to create the correct object.
def set_value(self, selector, new_value, by=By.CSS_SELECTOR, timeout=settings.LARGE_TIMEOUT): """ This method uses JavaScript to update a text field. """ if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT: timeout = self.__get_new_timeout(timeout) if p...
This method uses JavaScript to update a text field.
def load_ref_spectra(): """ Pull out wl, flux, ivar from files of training spectra """ data_dir = "/Users/annaho/Data/AAOmega/ref_spectra" # Load the files & count the number of training objects ff = glob.glob("%s/*.txt" %data_dir) nstars = len(ff) print("We have %s training objects" %nstars) ...
Pull out wl, flux, ivar from files of training spectra
def index_buffer(self, buffer, index_element_size=4): """ Set the index buffer for this VAO Args: buffer: ``moderngl.Buffer``, ``numpy.array`` or ``bytes`` Keyword Args: index_element_size (int): Byte size of each element. 1, 2 or 4 """ if not ty...
Set the index buffer for this VAO Args: buffer: ``moderngl.Buffer``, ``numpy.array`` or ``bytes`` Keyword Args: index_element_size (int): Byte size of each element. 1, 2 or 4
def DeserializeForImport(self, reader): """ Deserialize full object. Args: reader (neo.IO.BinaryReader): """ super(Block, self).Deserialize(reader) self.Transactions = [] transaction_length = reader.ReadVarInt() for i in range(0, transaction...
Deserialize full object. Args: reader (neo.IO.BinaryReader):