code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def search_upstream(self, device: devicetools.Device, name: str = 'upstream') -> 'Selection': """Return the network upstream of the given starting point, including the starting point itself. >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, ...
Return the network upstream of the given starting point, including the starting point itself. >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, _ = prepare_full_example_2() You can pass both |Node| and |Element| objects and, optionally, the name of the new...
def generate(self, text): """Try to get the generated file. Args: text: The text that you want to generate. """ if not text: raise Exception("No text to speak") if len(text) >= self.MAX_CHARS: raise Exception("Number of characters must be les...
Try to get the generated file. Args: text: The text that you want to generate.
def currentItemChanged(self, _currentIndex=None, _previousIndex=None): """ Updates the description text widget when the user clicks on a selector in the table. The _currentIndex and _previousIndex parameters are ignored. """ self.editor.clear() self.editor.setTextColor(QCOLOR...
Updates the description text widget when the user clicks on a selector in the table. The _currentIndex and _previousIndex parameters are ignored.
def format_filename(self, data, row): """ Returns a formatted filename using the template stored in self.filename - `data`: vaping message - `row`: vaping message data row """ return self.filename.format(**self.filename_formatters(data, row))
Returns a formatted filename using the template stored in self.filename - `data`: vaping message - `row`: vaping message data row
def trace_memory_usage(self, frame, event, arg): """Callback for sys.settrace""" if (event in ('call', 'line', 'return') and frame.f_code in self.code_map): if event != 'call': # "call" event just saves the lineno but not the memory mem = _get_...
Callback for sys.settrace
def _assemble_lsid(self, module_number): """ Return an assembled LSID based off the provided module number and the authority's base LSID. Note: Never includes the module's version number. :param module_number: :return: string """ if self.base_lsid is None: ...
Return an assembled LSID based off the provided module number and the authority's base LSID. Note: Never includes the module's version number. :param module_number: :return: string
def set_menu(self, menu): '''set a MPTopMenu on the frame''' self.menu = menu self.in_queue.put(MPImageMenu(menu))
set a MPTopMenu on the frame
def decrypt(key, ciphertext): """Decrypt Vigenere encrypted ``ciphertext`` using ``key``. Example: >>> decrypt("KEY", "RIJVS") HELLO Args: key (iterable): The key to use ciphertext (str): The text to decrypt Returns: Decrypted ciphertext """ index = 0 ...
Decrypt Vigenere encrypted ``ciphertext`` using ``key``. Example: >>> decrypt("KEY", "RIJVS") HELLO Args: key (iterable): The key to use ciphertext (str): The text to decrypt Returns: Decrypted ciphertext
def print_table(seqs, id2name, name): """ print table of results # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns], orfs?, introns?], ...]] """ itable = open('%s.itable' % (name.rsplit('.', 1)[0]), 'w') print('\t'.join(['#sequence', 'gene', 'model', 'inserti...
print table of results # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns], orfs?, introns?], ...]]
def datastore(self, domain, data_type, mapping=None): """Get instance of the DataStore module. Args: domain (str): The domain can be either "system", "organization", or "local". When using "organization" the data store can be accessed by any Application in the entire org, ...
Get instance of the DataStore module. Args: domain (str): The domain can be either "system", "organization", or "local". When using "organization" the data store can be accessed by any Application in the entire org, while "local" access is restricted to the App writi...
def create_dataset(args): """ Attempt to create a new dataset given the following params: * template_id * template_file * capacity * create_vault * [argument] dataset name or full path NOTE: genome_build has been deprecated and is no longer used. """ # For ...
Attempt to create a new dataset given the following params: * template_id * template_file * capacity * create_vault * [argument] dataset name or full path NOTE: genome_build has been deprecated and is no longer used.
def delete_actions(self, form_id, action_ids): """ Remove actions from a form :param form_id: int :param action_ids: list|tuple :return: dict|str """ response = self._client.session.delete( '{url}/{form_id}/actions/delete'.format( url...
Remove actions from a form :param form_id: int :param action_ids: list|tuple :return: dict|str
def getitem_column_array(self, key): """Get column data for target labels. Args: key: Target labels by which to retrieve data. Returns: A new QueryCompiler. """ # Convert to list for type checking numeric_indices = list(self.columns.get_indexer_f...
Get column data for target labels. Args: key: Target labels by which to retrieve data. Returns: A new QueryCompiler.
def _find_countour_yaml(start, checked, names=None): """Traverse the directory tree identified by start until a directory already in checked is encountered or the path of countour.yaml is found. Checked is present both to make the loop termination easy to reason about and so the same directories do...
Traverse the directory tree identified by start until a directory already in checked is encountered or the path of countour.yaml is found. Checked is present both to make the loop termination easy to reason about and so the same directories do not get rechecked Args: start: the path to...
def _filter_attrs(self, feature, request): """ Remove some attributes from the feature and set the geometry to None in the feature based ``attrs`` and the ``no_geom`` parameters. """ if 'attrs' in request.params: attrs = request.params['attrs'].split(',') props = feat...
Remove some attributes from the feature and set the geometry to None in the feature based ``attrs`` and the ``no_geom`` parameters.
def flipcoords(xcoord, ycoord, axis): """ Flip the coordinates over a specific axis, to a different quadrant :type xcoord: integer :param xcoord: The x coordinate to flip :type ycoord: integer :param ycoord: The y coordinate to flip :type axis: string :param axis: The axis to flip acr...
Flip the coordinates over a specific axis, to a different quadrant :type xcoord: integer :param xcoord: The x coordinate to flip :type ycoord: integer :param ycoord: The y coordinate to flip :type axis: string :param axis: The axis to flip across. Could be 'x' or 'y'
def lxml(self) -> _LXML: """`lxml <http://lxml.de>`_ representation of the :class:`Element <Element>` or :class:`XML <XML>`. """ if self._lxml is None: self._lxml = etree.fromstring(self.raw_xml) return self._lxml
`lxml <http://lxml.de>`_ representation of the :class:`Element <Element>` or :class:`XML <XML>`.
def read_fwf(filepath_or_buffer: FilePathOrBuffer, colspecs='infer', widths=None, infer_nrows=100, **kwds): r""" Read a table of fixed-width formatted lines into DataFrame. Also supports optionally iterating or breaking of the file into chunks. ...
r""" Read a table of fixed-width formatted lines into DataFrame. Also supports optionally iterating or breaking of the file into chunks. Additional help can be found in the `online docs for IO Tools <http://pandas.pydata.org/pandas-docs/stable/io.html>`_. Parameters ---------- filepat...
def write_logfile(): # type: () -> None """Write a DEBUG log file COMMAND-YYYYMMDD-HHMMSS.ffffff.log.""" command = os.path.basename(os.path.realpath(os.path.abspath(sys.argv[0]))) now = datetime.datetime.now().strftime('%Y%m%d-%H%M%S.%f') filename = '{}-{}.log'.format(command, now) with open(fil...
Write a DEBUG log file COMMAND-YYYYMMDD-HHMMSS.ffffff.log.
def _is_match(self, response, answer): """Does the response match the answer """ def compare_conditions(droppable_id, spatial_units, response_conditions): """Compare response coordinates with spatial units for droppable_id""" coordinate_match = True for coordinate in...
Does the response match the answer
def cache_cluster_present(name, wait=900, security_groups=None, region=None, key=None, keyid=None, profile=None, **args): ''' Ensure a given cache cluster exists. name Name of the cache cluster (cache cluster id). wait Integer describing how long, in seconds, ...
Ensure a given cache cluster exists. name Name of the cache cluster (cache cluster id). wait Integer describing how long, in seconds, to wait for confirmation from AWS that the resource is in the desired state. Zero meaning to return success or failure immediately of course. ...
def freeze(value): """ Cast value to its frozen counterpart. """ if isinstance(value, list): return FrozenList(*value) if isinstance(value, dict): return FrozenDict(**value) return value
Cast value to its frozen counterpart.
def combine_calls(*args): """Combine multiple callsets into a final set of merged calls. """ if len(args) == 3: is_cwl = False batch_id, samples, data = args caller_names, vrn_files = _organize_variants(samples, batch_id) else: is_cwl = True samples = [utils.to_si...
Combine multiple callsets into a final set of merged calls.
def _sslobj(sock): """Returns the underlying PySLLSocket object with which the C extension functions interface. """ pass if isinstance(sock._sslobj, _ssl._SSLSocket): return sock._sslobj else: return sock._sslobj._sslobj
Returns the underlying PySLLSocket object with which the C extension functions interface.
def request_sensor_value(self, req, msg): """Request the value of a sensor or sensors. A list of sensor values as a sequence of #sensor-value informs. Parameters ---------- name : str, optional Name of the sensor to poll (the default is to send values for all ...
Request the value of a sensor or sensors. A list of sensor values as a sequence of #sensor-value informs. Parameters ---------- name : str, optional Name of the sensor to poll (the default is to send values for all sensors). If name starts and ends with '/' it i...
def BIC(self,data=None): ''' BIC on the passed data. If passed data is None (default), calculates BIC on the model's assigned data ''' # NOTE: in principle this method computes the BIC only after finding the # maximum likelihood parameters (or, of course, an EM fixed-poin...
BIC on the passed data. If passed data is None (default), calculates BIC on the model's assigned data
def deps_used(self, pkg, used): """Create dependencies dictionary """ if find_package(pkg + self.meta.sp, self.meta.pkg_path): if pkg not in self.deps_dict.values(): self.deps_dict[pkg] = used else: self.deps_dict[pkg] += used
Create dependencies dictionary
def Throughput(self): """Combined throughput from multiplying all the components together. Returns ------- throughput : `~pysynphot.spectrum.TabularSpectralElement` or `None` Combined throughput. """ try: throughput = spectrum.TabularSpectralElem...
Combined throughput from multiplying all the components together. Returns ------- throughput : `~pysynphot.spectrum.TabularSpectralElement` or `None` Combined throughput.
def clean(self): """ Prevents cycles in the tree. """ super(CTENode, self).clean() if self.parent and self.pk in getattr(self.parent, self._cte_node_path): raise ValidationError(_("A node cannot be made a descendant of itself."))
Prevents cycles in the tree.
def synthesize(self, duration): """ Synthesize white noise Args: duration (numpy.timedelta64): The duration of the synthesized sound """ sr = self.samplerate.samples_per_second seconds = duration / Seconds(1) samples = np.random.uniform(low=-1., high=...
Synthesize white noise Args: duration (numpy.timedelta64): The duration of the synthesized sound
def int_global_to_local(self, index, axis=0): """ Calculate local index from global index for integer input :param index: global index as integer :param axis: current axis to process :return: """ # Warum >= an dieser Stelle. Eigentlich sollte > ausreichend sein! Test! ...
Calculate local index from global index for integer input :param index: global index as integer :param axis: current axis to process :return:
def format_number(col, d): """ Formats the number X to a format like '#,--#,--#.--', rounded to d decimal places with HALF_EVEN round mode, and returns the result as a string. :param col: the column name of the numeric value to be formatted :param d: the N decimal places >>> spark.createDataFr...
Formats the number X to a format like '#,--#,--#.--', rounded to d decimal places with HALF_EVEN round mode, and returns the result as a string. :param col: the column name of the numeric value to be formatted :param d: the N decimal places >>> spark.createDataFrame([(5,)], ['a']).select(format_number...
def cd_previous(self): """ cd to the gDirectory before this file was open. """ if self._prev_dir is None or isinstance(self._prev_dir, ROOT.TROOT): return False if isinstance(self._prev_dir, ROOT.TFile): if self._prev_dir.IsOpen() and self._prev_dir.IsWrit...
cd to the gDirectory before this file was open.
def predict_proba(self, a, b, device=None): """Infer causal directions using the trained NCC pairwise model. Args: a (numpy.ndarray): Variable 1 b (numpy.ndarray): Variable 2 device (str): Device to run the algorithm on (defaults to ``cdt.SETTINGS.default_device``) ...
Infer causal directions using the trained NCC pairwise model. Args: a (numpy.ndarray): Variable 1 b (numpy.ndarray): Variable 2 device (str): Device to run the algorithm on (defaults to ``cdt.SETTINGS.default_device``) Returns: float: Causation score (Va...
def declaration_path(decl): """ Returns a list of parent declarations names. Args: decl (declaration_t): declaration for which declaration path should be calculated. Returns: list[(str | basestring)]: list of names, where first item is the top ...
Returns a list of parent declarations names. Args: decl (declaration_t): declaration for which declaration path should be calculated. Returns: list[(str | basestring)]: list of names, where first item is the top parent name and la...
def find_recipients_conversations(self, context=None, exclude=None, from_conversation_id=None, permissions=None, search=None, type=None, user_id=None): """ Find recipients. Find valid recipients (users, courses and groups) that the current user can send messages to. The /api/v1/sea...
Find recipients. Find valid recipients (users, courses and groups) that the current user can send messages to. The /api/v1/search/recipients path is the preferred endpoint, /api/v1/conversations/find_recipients is deprecated. Pagination is supported.
def _get_full_model_smt_script(self, constraints=(), variables=()): """ Returns a SMT script that declare all the symbols and constraint and checks their satisfiability (check-sat) :param extra-constraints: list of extra constraints that we want to evaluate only ...
Returns a SMT script that declare all the symbols and constraint and checks their satisfiability (check-sat) :param extra-constraints: list of extra constraints that we want to evaluate only in the scope of this call :return string: smt-lib representation of th...
def frange(start, end, step): """Like range(), but with floats. """ val = start while val < end: yield val val += step
Like range(), but with floats.
def _get_line_styles(marker_str): """Return line style, color and marker type from specified marker string. For example, if ``marker_str`` is 'g-o' then the method returns ``('solid', 'green', 'circle')``. """ def _extract_marker_value(marker_str, code_dict): """Extracts the marker value fr...
Return line style, color and marker type from specified marker string. For example, if ``marker_str`` is 'g-o' then the method returns ``('solid', 'green', 'circle')``.
def get_coordinates_xyz(filename): """ Get coordinates from filename and return a vectorset with all the coordinates, in XYZ format. Parameters ---------- filename : string Filename to read Returns ------- atoms : list List of atomic types V : array (N,3...
Get coordinates from filename and return a vectorset with all the coordinates, in XYZ format. Parameters ---------- filename : string Filename to read Returns ------- atoms : list List of atomic types V : array (N,3) where N is number of atoms
def setExpandedIcon( self, column, icon ): """ Sets the icon to be used when the item is expanded. :param column | <int> icon | <QtGui.QIcon> || None """ self._expandedIcon[column] = QtGui.QIcon(icon)
Sets the icon to be used when the item is expanded. :param column | <int> icon | <QtGui.QIcon> || None
def get_checking_block(self): """Workaround for parity https://github.com/paritytech/parity-ethereum/issues/9707 In parity doing any call() with the 'pending' block no longer falls back to the latest if no pending block is found but throws a mistaken error. Until that bug is fixed we nee...
Workaround for parity https://github.com/paritytech/parity-ethereum/issues/9707 In parity doing any call() with the 'pending' block no longer falls back to the latest if no pending block is found but throws a mistaken error. Until that bug is fixed we need to enforce special behaviour for parity...
def pause(vm_): ''' Pause the named vm CLI Example: .. code-block:: bash salt '*' virt.pause <vm name> ''' with _get_xapi_session() as xapi: vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False try: xapi.VM.pause(...
Pause the named vm CLI Example: .. code-block:: bash salt '*' virt.pause <vm name>
def ensure_dir_exists(directory): """Se asegura de que un directorio exista.""" if directory and not os.path.exists(directory): os.makedirs(directory)
Se asegura de que un directorio exista.
def setitem_via_pathlist(ol,value,pathlist): ''' from elist.elist import * y = ['a',['b',["bb"]],'c'] y[1][1] setitem_via_pathlist(y,"500",[1,1]) y ''' this = ol for i in range(0,pathlist.__len__()-1): key = pathlist[i] this = this.__getitem__(key)...
from elist.elist import * y = ['a',['b',["bb"]],'c'] y[1][1] setitem_via_pathlist(y,"500",[1,1]) y
def connect(reactor, control_endpoint=None, password_function=None): """ Creates a :class:`txtorcon.Tor` instance by connecting to an already-running tor's control port. For example, a common default tor uses is UNIXClientEndpoint(reactor, '/var/run/tor/control') or TCP4ClientEndpoint(reactor, 'loca...
Creates a :class:`txtorcon.Tor` instance by connecting to an already-running tor's control port. For example, a common default tor uses is UNIXClientEndpoint(reactor, '/var/run/tor/control') or TCP4ClientEndpoint(reactor, 'localhost', 9051) If only password authentication is available in the tor we con...
def add_rule(self, ip_protocol, from_port, to_port, src_group_name, src_group_owner_id, cidr_ip): """ Add a rule to the SecurityGroup object. Note that this method only changes the local version of the object. No information is sent to EC2. """ rule = I...
Add a rule to the SecurityGroup object. Note that this method only changes the local version of the object. No information is sent to EC2.
def check_column_existence(col_name, df, presence=True): """ Checks whether or not `col_name` is in `df` and raises a helpful error msg if the desired condition is not met. Parameters ---------- col_name : str. Should represent a column whose presence in `df` is to be checked. df : ...
Checks whether or not `col_name` is in `df` and raises a helpful error msg if the desired condition is not met. Parameters ---------- col_name : str. Should represent a column whose presence in `df` is to be checked. df : pandas DataFrame. The dataframe that will be checked for the ...
def set_reload_params( self, min_lifetime=None, max_lifetime=None, max_requests=None, max_requests_delta=None, max_addr_space=None, max_rss=None, max_uss=None, max_pss=None, max_addr_space_forced=None, max_rss_forced=None, watch_interval_forced=None, mercy=Non...
Sets workers reload parameters. :param int min_lifetime: A worker cannot be destroyed/reloaded unless it has been alive for N seconds (default 60). This is an anti-fork-bomb measure. Since 1.9 :param int max_lifetime: Reload workers after this many seconds. Disabled by default....
def set_callbacks(self, **dic_functions): """Register callbacks needed by the interface object""" for action in self.interface.CALLBACKS: try: f = dic_functions[action] except KeyError: pass else: setattr(self.interface....
Register callbacks needed by the interface object
def clear_file(self, label): """stub""" rm = self.my_osid_object_form._get_provider_manager('REPOSITORY') catalog_id_str = '' if 'assignedBankIds' in self.my_osid_object_form._my_map: catalog_id_str = self.my_osid_object_form._my_map['assignedBankIds'][0] elif 'assi...
stub
def summed_probabilities(self, choosers, alternatives): """ Calculate total probability associated with each alternative. Parameters ---------- choosers : pandas.DataFrame Table describing the agents making choices, e.g. households. alternatives : pandas.Data...
Calculate total probability associated with each alternative. Parameters ---------- choosers : pandas.DataFrame Table describing the agents making choices, e.g. households. alternatives : pandas.DataFrame Table describing the things from which agents are choosing...
def king(self, color: Color) -> Optional[Square]: """ Finds the king square of the given side. Returns ``None`` if there is no king of that color. In variants with king promotions, only non-promoted kings are considered. """ king_mask = self.occupied_co[color] & ...
Finds the king square of the given side. Returns ``None`` if there is no king of that color. In variants with king promotions, only non-promoted kings are considered.
def check_activation(self, contacts): """Enter or exit downtime if necessary :return: None """ now = time.time() was_is_in_effect = self.is_in_effect self.is_in_effect = (self.start_time <= now <= self.end_time) # Raise a log entry when we get in the downtime ...
Enter or exit downtime if necessary :return: None
def socket(type, filename, line_nbr): """ Get a new ZMQ socket, automagically creating a ZMQ context if this is the first time. Caller is responsible for destroying the ZMQ socket before process exits, to avoid a ZMQ deadlock. Note: you should not use this method in CZMQ apps, use zsock_new() instead. *...
Get a new ZMQ socket, automagically creating a ZMQ context if this is the first time. Caller is responsible for destroying the ZMQ socket before process exits, to avoid a ZMQ deadlock. Note: you should not use this method in CZMQ apps, use zsock_new() instead. *** This is for CZMQ internal use only and may change arbit...
def encode(cls, value): """Encodes a value into bencoded bytes. :param value: Python object to be encoded (str, int, list, dict). :param str val_encoding: Encoding used by strings in a given object. :rtype: bytes """ val_encoding = 'utf-8' def encode_str(v): ...
Encodes a value into bencoded bytes. :param value: Python object to be encoded (str, int, list, dict). :param str val_encoding: Encoding used by strings in a given object. :rtype: bytes
def register(self, name, description, obj, plugin): """ Registers a new shared object. :param name: Unique name for shared object :type name: str :param description: Description of shared object :type description: str :param obj: The object, which shall be shared...
Registers a new shared object. :param name: Unique name for shared object :type name: str :param description: Description of shared object :type description: str :param obj: The object, which shall be shared :type obj: any type :param plugin: Plugin, which regist...
def get_context_data(self, **kwargs): """Tests cookies. """ self.request.session.set_test_cookie() if not self.request.session.test_cookie_worked(): messages.add_message( self.request, messages.ERROR, "Please enable cookies.") self.request.session.dele...
Tests cookies.
def parse(cls, data): """ Parse a Config structure out of a Python dict (that's likely deserialized from YAML). :param data: Config-y dict :type data: dict :return: Config object :rtype: valohai_yaml.objs.Config """ parsers = { 'step': ([], St...
Parse a Config structure out of a Python dict (that's likely deserialized from YAML). :param data: Config-y dict :type data: dict :return: Config object :rtype: valohai_yaml.objs.Config
def inv_diagonal(S): """ Computes the inverse of a diagonal NxN np.array S. In general this will be much faster than calling np.linalg.inv(). However, does NOT check if the off diagonal elements are non-zero. So long as S is truly diagonal, the output is identical to np.linalg.inv(). Parameter...
Computes the inverse of a diagonal NxN np.array S. In general this will be much faster than calling np.linalg.inv(). However, does NOT check if the off diagonal elements are non-zero. So long as S is truly diagonal, the output is identical to np.linalg.inv(). Parameters ---------- S : np.array...
def inspect_container(self, container): """ Identical to the `docker inspect` command, but only for containers. Args: container (str): The container to inspect Returns: (dict): Similar to the output of `docker inspect`, but as a single dict ...
Identical to the `docker inspect` command, but only for containers. Args: container (str): The container to inspect Returns: (dict): Similar to the output of `docker inspect`, but as a single dict Raises: :py:class:`docker.errors.APIError` ...
def solve_status_str(hdrlbl, fmtmap=None, fwdth0=4, fwdthdlt=6, fprec=2): """Construct header and format details for status display of an iterative solver. Parameters ---------- hdrlbl : tuple of strings Tuple of field header strings fmtmap : dict or None, optional (d...
Construct header and format details for status display of an iterative solver. Parameters ---------- hdrlbl : tuple of strings Tuple of field header strings fmtmap : dict or None, optional (default None) A dict providing a mapping from field header strings to print format strings,...
def history(self, first=0, last=0, limit=-1, only_ops=[], exclude_ops=[]): """ Returns a generator for individual account transactions. The latest operation will be first. This call can be used in a ``for`` loop. :param int first: sequence number of the first ...
Returns a generator for individual account transactions. The latest operation will be first. This call can be used in a ``for`` loop. :param int first: sequence number of the first transaction to return (*optional*) :param int last: sequence number of the...
def is_builtin(text): """Test if passed string is the name of a Python builtin object""" from spyder.py3compat import builtins return text in [str(name) for name in dir(builtins) if not name.startswith('_')]
Test if passed string is the name of a Python builtin object
def get_config(): ''' Get the current DSC Configuration Returns: dict: A dictionary representing the DSC Configuration on the machine Raises: CommandExecutionError: On failure CLI Example: .. code-block:: bash salt '*' dsc.get_config ''' cmd = 'Get-DscConfigu...
Get the current DSC Configuration Returns: dict: A dictionary representing the DSC Configuration on the machine Raises: CommandExecutionError: On failure CLI Example: .. code-block:: bash salt '*' dsc.get_config
def _get_generic_two_antidep_episodes_result( rowdata: Tuple[Any, ...] = None) -> DataFrame: """ Create a results row for this application. """ # Valid data types... see: # - pandas.core.dtypes.common.pandas_dtype # - https://pandas.pydata.org/pandas-docs/stable/timeseries.html # - h...
Create a results row for this application.
def vcsNodeState_originator_switch_info_switchIdentifier(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") vcsNodeState = ET.SubElement(config, "vcsNodeState", xmlns="urn:brocade.com:mgmt:brocade-vcs") originator_switch_info = ET.SubElement(vcsNodeState, "...
Auto Generated Code
def _kalman_prediction_step_SVD(k, p_m , p_P, p_dyn_model_callable, calc_grad_log_likelihood=False, p_dm = None, p_dP = None): """ Desctrete prediction function Input: k:int Iteration No. Starts at 0. Total number of iterations equal t...
Desctrete prediction function Input: k:int Iteration No. Starts at 0. Total number of iterations equal to the number of measurements. p_m: matrix of size (state_dim, time_series_no) Mean value from the previous step. For "multiple time se...
def connect_signals(self, target): """ This is deprecated. Pass your controller to connect signals the old way. """ if self.connected: raise RuntimeError("GtkBuilder can only connect signals once") self.builder.connect_signals(target) self.connected = ...
This is deprecated. Pass your controller to connect signals the old way.
def init_printing(*, reset=False, init_sympy=True, **kwargs): """Initialize the printing system. This determines the behavior of the :func:`ascii`, :func:`unicode`, and :func:`latex` functions, as well as the ``__str__`` and ``__repr__`` of any :class:`.Expression`. The routine may be called in on...
Initialize the printing system. This determines the behavior of the :func:`ascii`, :func:`unicode`, and :func:`latex` functions, as well as the ``__str__`` and ``__repr__`` of any :class:`.Expression`. The routine may be called in one of two forms. First, :: init_printing( st...
def _tta_only(learn:Learner, ds_type:DatasetType=DatasetType.Valid, scale:float=1.35) -> Iterator[List[Tensor]]: "Computes the outputs for several augmented inputs for TTA" dl = learn.dl(ds_type) ds = dl.dataset old = ds.tfms augm_tfm = [o for o in learn.data.train_ds.tfms if o.tfm not in ...
Computes the outputs for several augmented inputs for TTA
def rotateX(self, angle): """ Rotates the point around the X axis by the given angle in degrees. """ rad = angle * math.pi / 180 cosa = math.cos(rad) sina = math.sin(rad) y = self.y * cosa - self.z * sina z = self.y * sina + self.z * cosa return Point3D(self.x, y,...
Rotates the point around the X axis by the given angle in degrees.
def get_assessment_part_form(self, *args, **kwargs): """Pass through to provider AssessmentPartAdminSession.get_assessment_part_form_for_update""" # This method might be a bit sketchy. Time will tell. if isinstance(args[-1], list) or 'assessment_part_record_types' in kwargs: return s...
Pass through to provider AssessmentPartAdminSession.get_assessment_part_form_for_update
def _times_to_hours_after_local_midnight(times): """convert local pandas datetime indices to array of hours as floats""" times = times.tz_localize(None) hrs = 1 / NS_PER_HR * ( times.astype(np.int64) - times.normalize().astype(np.int64)) return np.array(hrs)
convert local pandas datetime indices to array of hours as floats
def assert_inbounds(num, low, high, msg='', eq=False, verbose=not util_arg.QUIET): r""" Args: num (scalar): low (scalar): high (scalar): msg (str): """ from utool import util_str if util_arg.NO_ASSERTS: return passed = util_alg.inbounds(num, low, high, eq=...
r""" Args: num (scalar): low (scalar): high (scalar): msg (str):
def from_coordinates(cls, coordinates, labels): """Initialize a similarity descriptor Arguments: coordinates -- a Nx3 numpy array labels -- a list with integer labels used to identify atoms of the same type """ from molmod.ext im...
Initialize a similarity descriptor Arguments: coordinates -- a Nx3 numpy array labels -- a list with integer labels used to identify atoms of the same type
def v(msg, *args, **kwargs): ''' log a message at verbose level; ''' return logging.log(VERBOSE, msg, *args, **kwargs)
log a message at verbose level;
def add_response_signature(self, response_data, sign_algorithm=OneLogin_Saml2_Constants.RSA_SHA1): """ Builds the Signature of the SAML Response. :param response_data: The Response parameters :type response_data: dict :param sign_algorithm: Signature algorithm method :ty...
Builds the Signature of the SAML Response. :param response_data: The Response parameters :type response_data: dict :param sign_algorithm: Signature algorithm method :type sign_algorithm: string
def collect_mean(self, fitness_functions): """! @brief Stores average value of fitness function among chromosomes on specific iteration. @param[in] fitness_functions (float): Average value of fitness functions among chromosomes. """ if not self._need_mean_ff: ...
! @brief Stores average value of fitness function among chromosomes on specific iteration. @param[in] fitness_functions (float): Average value of fitness functions among chromosomes.
def IncrementCounter(self, metric_name, delta=1, fields=None): """See base class.""" if delta < 0: raise ValueError("Invalid increment for counter: %d." % delta) self._counter_metrics[metric_name].Increment(delta, fields)
See base class.
def wait_for_event(event): """ Wraps a win32 event into a `Future` and wait for it. """ f = Future() def ready(): get_event_loop().remove_win32_handle(event) f.set_result(None) get_event_loop().add_win32_handle(event, ready) return f
Wraps a win32 event into a `Future` and wait for it.
def replicate_per_farm_dbs(cloud_url=None, local_url=None, farm_name=None): """ Sete up replication of the per-farm databases from the local server to the cloud server. :param str cloud_url: Used to override the cloud url from the global configuration in case the calling function is in the process ...
Sete up replication of the per-farm databases from the local server to the cloud server. :param str cloud_url: Used to override the cloud url from the global configuration in case the calling function is in the process of initializing the cloud server :param str local_url: Used to override the loca...
def pull(configuration, *resources): """ Pull translations from all languages listed in conf/locale/config.yaml where there is at least 10% reviewed translations. If arguments are provided, they are specific resources to pull. Otherwise, all resources are pulled. """ print("Pulling conf/l...
Pull translations from all languages listed in conf/locale/config.yaml where there is at least 10% reviewed translations. If arguments are provided, they are specific resources to pull. Otherwise, all resources are pulled.
def execute_greenlet_async(func, *args, **kwargs): """ Executes `func` in a separate greenlet in the same process. Memory and other resources are available (e.g. TCP connections etc.) `args` and `kwargs` are passed to `func`. """ global _GREENLET_EXECUTOR if _GREENLET_EXECUTOR is None: _GREENLET_EXECU...
Executes `func` in a separate greenlet in the same process. Memory and other resources are available (e.g. TCP connections etc.) `args` and `kwargs` are passed to `func`.
def _set_bad_packet(self, v, load=False): """ Setter method for bad_packet, mapped from YANG variable /rbridge_id/router/ospf/log/bad_packet (container) If this variable is read-only (config: false) in the source YANG file, then _set_bad_packet is considered as a private method. Backends looking to ...
Setter method for bad_packet, mapped from YANG variable /rbridge_id/router/ospf/log/bad_packet (container) If this variable is read-only (config: false) in the source YANG file, then _set_bad_packet is considered as a private method. Backends looking to populate this variable should do so via calling th...
def temp_dir(sub_dir='work'): """Obtain the temporary working directory for the operating system. An inasafe subdirectory will automatically be created under this and if specified, a user subdirectory under that. .. note:: You can use this together with unique_filename to create a file in a tem...
Obtain the temporary working directory for the operating system. An inasafe subdirectory will automatically be created under this and if specified, a user subdirectory under that. .. note:: You can use this together with unique_filename to create a file in a temporary directory under the inasafe wo...
def _track_change(self, name, value, formatter=None): """Track that a change happened. This function is only needed for manually recording changes that are not captured by changes to properties of this object that are tracked automatically. Classes that inherit from `emulation_mixin` s...
Track that a change happened. This function is only needed for manually recording changes that are not captured by changes to properties of this object that are tracked automatically. Classes that inherit from `emulation_mixin` should use this function to record interesting changes in ...
def view_vector(self, vector, viewup=None): """Point the camera in the direction of the given vector""" focal_pt = self.center if viewup is None: viewup = rcParams['camera']['viewup'] cpos = [vector + np.array(focal_pt), focal_pt, viewup] self.camera_p...
Point the camera in the direction of the given vector
def get_sorted_proposal_list(self): """Return a list of `CodeAssistProposal`""" proposals = {} for proposal in self.proposals: proposals.setdefault(proposal.scope, []).append(proposal) result = [] for scope in self.scopepref: scope_proposals = proposals.ge...
Return a list of `CodeAssistProposal`
def serialize_smarttag(ctx, document, el, root): "Serializes smarttag." if ctx.options['smarttag_span']: _span = etree.SubElement(root, 'span', {'class': 'smarttag', 'data-smarttag-element': el.element}) else: _span = root for elem in el.elements: _ser = ctx.get_serializer(elem...
Serializes smarttag.
def _build_error_report( self, message, report_location=None, http_context=None, user=None ): """Builds the Error Reporting object to report. This builds the object according to https://cloud.google.com/error-reporting/docs/formatting-error-messages :type message: str ...
Builds the Error Reporting object to report. This builds the object according to https://cloud.google.com/error-reporting/docs/formatting-error-messages :type message: str :param message: The stack trace that was reported or logged by the service. :type rep...
def permute(sequence, permutation): """Apply a permutation sigma({j}) to an arbitrary sequence. :param sequence: Any finite length sequence ``[l_1,l_2,...l_n]``. If it is a list, tuple or str, the return type will be the same. :param permutation: permutation image tuple :type permutation: tuple :re...
Apply a permutation sigma({j}) to an arbitrary sequence. :param sequence: Any finite length sequence ``[l_1,l_2,...l_n]``. If it is a list, tuple or str, the return type will be the same. :param permutation: permutation image tuple :type permutation: tuple :return: The permuted sequence ``[l_sigma(1), ...
def infer_modifications(stmts): """Return inferred Modification from RegulateActivity + ActiveForm. This function looks for combinations of Activation/Inhibition Statements and ActiveForm Statements that imply a Modification Statement. For example, if we know that A activates B, and pho...
Return inferred Modification from RegulateActivity + ActiveForm. This function looks for combinations of Activation/Inhibition Statements and ActiveForm Statements that imply a Modification Statement. For example, if we know that A activates B, and phosphorylated B is active, then we ca...
def put(self, thing_id='0', property_name=None): """ Handle a PUT request. thing_id -- ID of the thing this request is for property_name -- the name of the property from the URL path """ thing = self.get_thing(thing_id) if thing is None: self.set_stat...
Handle a PUT request. thing_id -- ID of the thing this request is for property_name -- the name of the property from the URL path
def date(self, year: Number, month: Number, day: Number) -> Date: """ Takes three numbers and returns a ``Date`` object whose year, month, and day are the three numbers in that order. """ return Date(year, month, day)
Takes three numbers and returns a ``Date`` object whose year, month, and day are the three numbers in that order.
def resize(self, image, size): """ Resizes the image :param image: The image object :param size: size is PIL tuple (width, heigth, force) ex: (200,100,True) """ (width, height, force) = size if image.size[0] > width or image.size[1] > height: ...
Resizes the image :param image: The image object :param size: size is PIL tuple (width, heigth, force) ex: (200,100,True)
def get_summary(self): """ Get summary of ``SNPs``. Returns ------- dict summary info, else None if ``SNPs`` is not valid """ if not self.is_valid(): return None else: return { "source": self.source, ...
Get summary of ``SNPs``. Returns ------- dict summary info, else None if ``SNPs`` is not valid
def basic_reject(self, delivery_tag, requeue): """Reject an incoming message This method allows a client to reject a message. It can be used to interrupt and cancel large incoming messages, or return untreatable messages to their original queue. RULE: The server S...
Reject an incoming message This method allows a client to reject a message. It can be used to interrupt and cancel large incoming messages, or return untreatable messages to their original queue. RULE: The server SHOULD be capable of accepting and process the ...
def OverwriteAndClose(self, compressed_data, size): """Directly overwrite the current contents. Replaces the data currently in the stream with compressed_data, and closes the object. Makes it possible to avoid recompressing the data. Args: compressed_data: The data to write, must be zlib comp...
Directly overwrite the current contents. Replaces the data currently in the stream with compressed_data, and closes the object. Makes it possible to avoid recompressing the data. Args: compressed_data: The data to write, must be zlib compressed. size: The uncompressed size of the data.
def iterative_overlap_assembly( variant_sequences, min_overlap_size=MIN_VARIANT_SEQUENCE_ASSEMBLY_OVERLAP_SIZE): """ Assembles longer sequences from reads centered on a variant by between merging all pairs of overlapping sequences and collapsing shorter sequences onto every longer sequen...
Assembles longer sequences from reads centered on a variant by between merging all pairs of overlapping sequences and collapsing shorter sequences onto every longer sequence which contains them. Returns a list of variant sequences, sorted by decreasing read support.