code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def logic(self, data): """Parse the data and respond to it appropriately. Response is returned to the caller and has to be sent data as a mysensors command string. """ try: msg = Message(data, self) msg.validate(self.protocol_version) except (Valu...
Parse the data and respond to it appropriately. Response is returned to the caller and has to be sent data as a mysensors command string.
def detectBlackBerry10Phone(self): """Return detection of a Blackberry 10 OS phone Detects if the current browser is a BlackBerry 10 OS phone. Excludes the PlayBook. """ return UAgentInfo.deviceBB10 in self.__userAgent \ and UAgentInfo.mobile in self.__userAgent
Return detection of a Blackberry 10 OS phone Detects if the current browser is a BlackBerry 10 OS phone. Excludes the PlayBook.
def scroll(clicks, x=None, y=None, pause=None, _pause=True): """Performs a scroll of the mouse scroll wheel. Whether this is a vertical or horizontal scroll depends on the underlying operating system. The x and y parameters detail where the mouse event happens. If None, the current mouse position ...
Performs a scroll of the mouse scroll wheel. Whether this is a vertical or horizontal scroll depends on the underlying operating system. The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the bo...
def rename(self, name): """Rename the table """ sql = """ALTER TABLE {s}.{t} RENAME TO {name} """.format( s=self.schema, t=self.name, name=name ) self.engine.execute(sql) self.table = SQLATable(name, self.metadata, schema=self.schema, autoload=Tr...
Rename the table
def get_next_second(intersection, intersections, to_end=True): """Gets the next node along the current (second) edge. .. note:: This is a helper used only by :func:`get_next`, which in turn is only used by :func:`basic_interior_combine`, which itself is only used by :func:`combine_interse...
Gets the next node along the current (second) edge. .. note:: This is a helper used only by :func:`get_next`, which in turn is only used by :func:`basic_interior_combine`, which itself is only used by :func:`combine_intersections`. Along with :func:`get_next_first`, this function does th...
def BatchLabelVocabulary(self): """Return all batch labels as a display list """ bsc = getToolByName(self, 'bika_setup_catalog') ret = [] for p in bsc(portal_type='BatchLabel', is_active=True, sort_on='sortable_title'): ret.ap...
Return all batch labels as a display list
def cross_fade(self, seg1, seg2, duration): """Add a linear crossfade to the composition between two segments. :param seg1: First segment (fading out) :type seg1: :py:class:`radiotool.composer.Segment` :param seg2: Second segment (fading in) :type seg2: :py:class:`radiot...
Add a linear crossfade to the composition between two segments. :param seg1: First segment (fading out) :type seg1: :py:class:`radiotool.composer.Segment` :param seg2: Second segment (fading in) :type seg2: :py:class:`radiotool.composer.Segment` :param duration: Duration...
async def findTask(self, *args, **kwargs): """ Find Indexed Task Find a task by index path, returning the highest-rank task with that path. If no task exists for the given path, this API end-point will respond with a 404 status. This method gives output: ``v1/indexed-task-respo...
Find Indexed Task Find a task by index path, returning the highest-rank task with that path. If no task exists for the given path, this API end-point will respond with a 404 status. This method gives output: ``v1/indexed-task-response.json#`` This method is ``stable``
def new_clustered_sortind(x, k=10, row_key=None, cluster_key=None): """ Uses MiniBatch k-means clustering to cluster matrix into groups. Each cluster of rows is then sorted by `scorefunc` -- by default, the max peak height when all rows in a cluster are averaged, or cluster.mean(axis=0).max(). ...
Uses MiniBatch k-means clustering to cluster matrix into groups. Each cluster of rows is then sorted by `scorefunc` -- by default, the max peak height when all rows in a cluster are averaged, or cluster.mean(axis=0).max(). Returns the index that will sort the rows of `x` and a list of "breaks". `b...
def _type_single(self, value, _type): ' apply type to the single value ' if value is None or _type in (None, NoneType): # don't convert null values # default type is the original type if none set pass elif isinstance(value, _type): # or values already of corr...
apply type to the single value
def from_df(cls, path:PathOrStr, train_df:DataFrame, valid_df:DataFrame, test_df:Optional[DataFrame]=None, tokenizer:Tokenizer=None, vocab:Vocab=None, classes:Collection[str]=None, text_cols:IntsOrStrs=1, label_cols:IntsOrStrs=0, label_delim:str=None, chunksize:int=10000, max_vocab:int=6...
Create a `TextDataBunch` from DataFrames. `kwargs` are passed to the dataloader creation.
def pathsplit(pth, dropext=True): """Split a path into a tuple of all of its components.""" if dropext: pth = os.path.splitext(pth)[0] parts = os.path.split(pth) if parts[0] == '': return parts[1:] elif len(parts[0]) == 1: return parts else: return pathsplit(part...
Split a path into a tuple of all of its components.
def sitetree_breadcrumbs(parser, token): """Parses sitetree_breadcrumbs tag parameters. Two notation types are possible: 1. Two arguments: {% sitetree_breadcrumbs from "mytree" %} Used to render breadcrumb path for "mytree" site tree. 2. Four arguments: {% site...
Parses sitetree_breadcrumbs tag parameters. Two notation types are possible: 1. Two arguments: {% sitetree_breadcrumbs from "mytree" %} Used to render breadcrumb path for "mytree" site tree. 2. Four arguments: {% sitetree_breadcrumbs from "mytree" template "sitetre...
def name(self, name): """ Updates the security labels name. Args: name: """ self._data['name'] = name request = self._base_request request['name'] = name return self._tc_requests.update(request, owner=self.owner)
Updates the security labels name. Args: name:
def scale_0to1(image_in, exclude_outliers_below=False, exclude_outliers_above=False): """Scale the two images to [0, 1] based on min/max from both. Parameters ----------- image_in : ndarray Input image exclude_outliers_{below,above} : float Lower/upper...
Scale the two images to [0, 1] based on min/max from both. Parameters ----------- image_in : ndarray Input image exclude_outliers_{below,above} : float Lower/upper limit, a value between 0 and 100. Returns ------- scaled_image : ndarray clipped and/or scaled image
def get_similar_entries(context, number=5, template='zinnia/tags/entries_similar.html'): """ Return similar entries. """ entry = context.get('entry') if not entry: return {'template': template, 'entries': []} vectors = EntryPublishedVectorBuilder() entries = ...
Return similar entries.
def main(): """Register your own mode and handle method here.""" plugin = Register() if plugin.args.option == 'sqlserverlocks': plugin.sqlserverlocks_handle() else: plugin.unknown("Unknown actions.")
Register your own mode and handle method here.
def inbox(self): """ :class:`Inbox feed <pypump.models.feed.Inbox>` with all :class:`activities <pypump.models.activity.Activity>` received by the person, can only be read if logged in as the owner. Example: >>> for activity in pump.me.inbox[:2]: ... print(ac...
:class:`Inbox feed <pypump.models.feed.Inbox>` with all :class:`activities <pypump.models.activity.Activity>` received by the person, can only be read if logged in as the owner. Example: >>> for activity in pump.me.inbox[:2]: ... print(activity.id) ... ...
def calc_sasa(dssp_df): """ Calculation of SASA utilizing the DSSP program. DSSP must be installed for biopython to properly call it. Install using apt-get on Ubuntu or from: http://swift.cmbi.ru.nl/gv/dssp/ Input: PDB or CIF structure file Output: SASA (integer) of structure """ ...
Calculation of SASA utilizing the DSSP program. DSSP must be installed for biopython to properly call it. Install using apt-get on Ubuntu or from: http://swift.cmbi.ru.nl/gv/dssp/ Input: PDB or CIF structure file Output: SASA (integer) of structure
def select_parser(self, request, parsers): """ Selects the appropriated parser which matches to the request's content type. :param request: The HTTP request. :param parsers: The lists of parsers. :return: The parser selected or none. """ if not request.content_ty...
Selects the appropriated parser which matches to the request's content type. :param request: The HTTP request. :param parsers: The lists of parsers. :return: The parser selected or none.
def list_models( self, dataset, max_results=None, page_token=None, retry=DEFAULT_RETRY ): """[Beta] List models in the dataset. See https://cloud.google.com/bigquery/docs/reference/rest/v2/models/list Args: dataset (Union[ \ :class:`~google.cloud...
[Beta] List models in the dataset. See https://cloud.google.com/bigquery/docs/reference/rest/v2/models/list Args: dataset (Union[ \ :class:`~google.cloud.bigquery.dataset.Dataset`, \ :class:`~google.cloud.bigquery.dataset.DatasetReference`, \ ...
def flush(self, timeout=None, callback=None): """Alias for self.client.flush""" client, scope = self._stack[-1] if client is not None: return client.flush(timeout=timeout, callback=callback)
Alias for self.client.flush
def pin_direction(self, pin): """Gets the `ahio.Direction` this pin was set to. If you're developing a driver, implement _pin_direction(self, pin) @arg pin the pin you want to see the mode @returns the `ahio.Direction` the pin is set to @throw KeyError if pin isn't mapped. ...
Gets the `ahio.Direction` this pin was set to. If you're developing a driver, implement _pin_direction(self, pin) @arg pin the pin you want to see the mode @returns the `ahio.Direction` the pin is set to @throw KeyError if pin isn't mapped.
def script_dir_plus_file(filename, pyobject, follow_symlinks=True): """Get current script's directory and then append a filename Args: filename (str): Filename to append to directory path pyobject (Any): Any Python object in the script follow_symlinks (Optional[bool]): Follow symlinks o...
Get current script's directory and then append a filename Args: filename (str): Filename to append to directory path pyobject (Any): Any Python object in the script follow_symlinks (Optional[bool]): Follow symlinks or not. Defaults to True. Returns: str: Current script's direct...
def _do_spelling_suggestion(database, query, spelling_query): """ Private method that returns a single spelling suggestion based on `spelling_query` or `query`. Required arguments: `database` -- The database to check spelling against `query` -- The query to check...
Private method that returns a single spelling suggestion based on `spelling_query` or `query`. Required arguments: `database` -- The database to check spelling against `query` -- The query to check `spelling_query` -- If not None, this will be checked instead of `que...
def _to_eng_tuple(number): """ Return tuple with mantissa and exponent of number formatted in engineering notation. :param number: Number :type number: integer or float :rtype: tuple """ # pylint: disable=W0141 # Helper function: split integer and fractional part of mantissa # + ...
Return tuple with mantissa and exponent of number formatted in engineering notation. :param number: Number :type number: integer or float :rtype: tuple
def get_mon_map(service): """ Returns the current monitor map. :param service: six.string_types. The Ceph user name to run the command under :return: json string. :raise: ValueError if the monmap fails to parse. Also raises CalledProcessError if our ceph command fails """ try: mon_...
Returns the current monitor map. :param service: six.string_types. The Ceph user name to run the command under :return: json string. :raise: ValueError if the monmap fails to parse. Also raises CalledProcessError if our ceph command fails
def get_attachment_info(self, attachment): """Returns a dictionary of attachment information """ attachment_uid = api.get_uid(attachment) attachment_file = attachment.getAttachmentFile() attachment_type = attachment.getAttachmentType() attachment_icon = attachment_file.i...
Returns a dictionary of attachment information
def indent_iterable(elems: Sequence[str], num: int = 2) -> List[str]: """Indent an iterable.""" return [" " * num + l for l in elems]
Indent an iterable.
def describe_cache_parameter_groups(name=None, conn=None, region=None, key=None, keyid=None, profile=None): ''' Return details about all (or just one) Elasticache cache clusters. Example: .. code-block:: bash salt myminion boto3_elasticache.describe_cache_p...
Return details about all (or just one) Elasticache cache clusters. Example: .. code-block:: bash salt myminion boto3_elasticache.describe_cache_parameter_groups salt myminion boto3_elasticache.describe_cache_parameter_groups myParameterGroup
def run_show_val(obj, name): """Generic subcommand value display""" val = obj.debugger.settings[obj.name] obj.msg("%s is %s." % (obj.name, obj.cmd.proc._saferepr(val),)) return False
Generic subcommand value display
def get_bpf_pointer(tcpdump_lines): """Create a BPF Pointer for TCPDump filter""" if conf.use_pypy: return _legacy_bpf_pointer(tcpdump_lines) # Allocate BPF instructions size = int(tcpdump_lines[0]) bpf_insn_a = bpf_insn * size bip = bpf_insn_a() # Fill the BPF instruction structur...
Create a BPF Pointer for TCPDump filter
def join_path_prefix(path, pre_path=None): """ If path set and not absolute, append it to pre path (if used) :param path: path to append :type path: str | None :param pre_path: Base path to append to (default: None) :type pre_path: None | str :return: Path or appended path :rtype: str |...
If path set and not absolute, append it to pre path (if used) :param path: path to append :type path: str | None :param pre_path: Base path to append to (default: None) :type pre_path: None | str :return: Path or appended path :rtype: str | None
def assembleimage(patches, pmasks, gridids): r""" Assemble an image from a number of patches, patch masks and their grid ids. Parameters ---------- patches : sequence Sequence of patches. pmasks : sequence Sequence of associated patch mask...
r""" Assemble an image from a number of patches, patch masks and their grid ids. Parameters ---------- patches : sequence Sequence of patches. pmasks : sequence Sequence of associated patch masks. gridids Sequence of associated...
def __read_byte_size(decl, attrs): """Using duck typing to set the size instead of in constructor""" size = attrs.get(XML_AN_SIZE, 0) # Make sure the size is in bytes instead of bits decl.byte_size = int(size) / 8
Using duck typing to set the size instead of in constructor
def cdd(d, k): """ Conditionally delete key (or list of keys) 'k' from dict 'd' """ if not isinstance(k, list): k = [k] for i in k: if i in d: d.pop(i)
Conditionally delete key (or list of keys) 'k' from dict 'd'
def setup_graph(self): """ Creates our Graph and figures out, which shared/global model to hook up to. If we are in a global-model's setup procedure, we do not create a new graph (return None as the context). We will instead use the already existing local replica graph of the mod...
Creates our Graph and figures out, which shared/global model to hook up to. If we are in a global-model's setup procedure, we do not create a new graph (return None as the context). We will instead use the already existing local replica graph of the model. Returns: None or the graph's a...
def get_all_subdomains(offset=None, count=None, min_sequence=None, db_path=None, zonefiles_dir=None): """ Static method for getting the list of all subdomains """ opts = get_blockstack_opts() if not is_subdomains_enabled(opts): return [] if db_path is None: db_path = opts['subdo...
Static method for getting the list of all subdomains
def check_serial_port(name): """returns valid COM Port.""" try: cdc = next(serial.tools.list_ports.grep(name)) return cdc[0] except StopIteration: msg = "device {} not found. ".format(name) msg += "available devices are: " ports = list(serial.tools.list_ports.comports...
returns valid COM Port.
def load_glb(self): """Loads a binary gltf file""" with open(self.path, 'rb') as fd: # Check header magic = fd.read(4) if magic != GLTF_MAGIC_HEADER: raise ValueError("{} has incorrect header {} != {}".format(self.path, magic, GLTF_MAGIC_HEADER)) ...
Loads a binary gltf file
def load(args): ''' %prog load gff_file fasta_file [--options] Parses the selected features out of GFF, with subfeatures concatenated. For example, to get the CDS sequences, do this: $ %prog load athaliana.gff athaliana.fa --parents mRNA --children CDS To get 500bp upstream of a genes Transcri...
%prog load gff_file fasta_file [--options] Parses the selected features out of GFF, with subfeatures concatenated. For example, to get the CDS sequences, do this: $ %prog load athaliana.gff athaliana.fa --parents mRNA --children CDS To get 500bp upstream of a genes Transcription Start Site (TSS), do t...
def call_somatic(tumor_name, normal_name): """Call SOMATIC variants from tumor/normal calls, adding REJECT filters and SOMATIC flag. Works from stdin and writes to stdout, finding positions of tumor and normal samples. Uses MuTect like somatic filter based on implementation in speedseq: https://github...
Call SOMATIC variants from tumor/normal calls, adding REJECT filters and SOMATIC flag. Works from stdin and writes to stdout, finding positions of tumor and normal samples. Uses MuTect like somatic filter based on implementation in speedseq: https://github.com/cc2qe/speedseq/blob/e6729aa2589eca4e3a946f398...
def declare_alias(self, name): """Insert a Python function into this Namespace with an explicitly-given name, but detect its argument count automatically. """ def decorator(f): self._auto_register_function(f, name) return f return decorator
Insert a Python function into this Namespace with an explicitly-given name, but detect its argument count automatically.
def point_distance_ellipsode(point1,point2): """ calculate the distance between two points on the ellipsode based on point1 Keyword arguments: point1 -- point one geojson object point2 -- point two geojson object return distance """ a = 6378137 f = 1/298.25722 b = a -...
calculate the distance between two points on the ellipsode based on point1 Keyword arguments: point1 -- point one geojson object point2 -- point two geojson object return distance
def _get(self, node, key): """ get value inside a node :param node: node in form of list, or BLANK_NODE :param key: nibble list without terminator :return: BLANK_NODE if does not exist, otherwise value or hash """ node_type = self._get_node_type(node) ...
get value inside a node :param node: node in form of list, or BLANK_NODE :param key: nibble list without terminator :return: BLANK_NODE if does not exist, otherwise value or hash
def _handle_codeblock(self, match): """ match args: 1:backticks, 2:lang_name, 3:newline, 4:code, 5:backticks """ from pygments.lexers import get_lexer_by_name # section header yield match.start(1), String , match.group(1) yield match.start(2), String ...
match args: 1:backticks, 2:lang_name, 3:newline, 4:code, 5:backticks
def build_props(self): """Build the props dictionary.""" props = {} if self.filters: props["filters"] = {} for grp in self.filters: props["filters"][grp] = [f.params for f in self.filters[grp]] if self.charts: props["charts"] = [c.param...
Build the props dictionary.
def update(self): ''' Updates LaserData. ''' if self.hasproxy(): sonarD = SonarData() range = 0 data = self.proxy.getSonarData() sonarD.range = data.range sonarD.maxAngle = data.maxAngle sonarD.minAngle = data.minAn...
Updates LaserData.
def _readXput(self, fileCards, directory, session, spatial=False, spatialReferenceID=4236, replaceParamFile=None): """ GSSHAPY Project Read Files from File Method """ ## NOTE: This function is dependent on the project file being read first # Read Input/Output Files for ca...
GSSHAPY Project Read Files from File Method
def flat(self, obj, mask=0): '''Return the aligned flat size. ''' s = self.base if self.leng and self.item > 0: # include items s += self.leng(obj) * self.item if _getsizeof: # _getsizeof prevails s = _getsizeof(obj, s) if mask: # align ...
Return the aligned flat size.
def _query_helper(self, by=None): """ Internal helper for preparing queries. """ if by is None: primary_keys = self.table.primary_key.columns.keys() if len(primary_keys) > 1: warnings.warn("WARNING: MORE THAN 1 PRIMARY KEY FOR TABLE %s. " ...
Internal helper for preparing queries.
def copyto(self, other): """Copies the value of this array to another array. If ``other`` is a ``NDArray`` or ``RowSparseNDArray`` object, then ``other.shape`` and ``self.shape`` should be the same. This function copies the value from ``self`` to ``other``. If ``other`` is a co...
Copies the value of this array to another array. If ``other`` is a ``NDArray`` or ``RowSparseNDArray`` object, then ``other.shape`` and ``self.shape`` should be the same. This function copies the value from ``self`` to ``other``. If ``other`` is a context, a new ``RowSparseNDArray`` wi...
def _log_graphql_error(self, query, data): '''Log a ``{"errors": [...]}`` GraphQL return and return itself. :param query: the GraphQL query that triggered the result. :type query: str :param data: the decoded JSON object. :type data: dict :return: the input ``data`` ...
Log a ``{"errors": [...]}`` GraphQL return and return itself. :param query: the GraphQL query that triggered the result. :type query: str :param data: the decoded JSON object. :type data: dict :return: the input ``data`` :rtype: dict
def t_binaryValue(t): r'[+-]?[0-9]+[bB]' # We must match [0-9], and then check the validity of the binary number. # If we match [0-1], the invalid binary number "2b" would match # 'decimalValue' 2 and 'IDENTIFIER 'b'. if re.search(r'[2-9]', t.value) is not None: msg = _format("Invalid binary...
r'[+-]?[0-9]+[bB]
def analyze(problem, Y, X, M=10, print_to_console=False, seed=None): """Performs the Random Balanced Design - Fourier Amplitude Sensitivity Test (RBD-FAST) on model outputs. Returns a dictionary with keys 'S1', where each entry is a list of size D (the number of parameters) containing the indices ...
Performs the Random Balanced Design - Fourier Amplitude Sensitivity Test (RBD-FAST) on model outputs. Returns a dictionary with keys 'S1', where each entry is a list of size D (the number of parameters) containing the indices in the same order as the parameter file. Parameters --------...
def exponentialRDD(sc, mean, size, numPartitions=None, seed=None): """ Generates an RDD comprised of i.i.d. samples from the Exponential distribution with the input mean. :param sc: SparkContext used to create the RDD. :param mean: Mean, or 1 / lambda, for the Exponential distri...
Generates an RDD comprised of i.i.d. samples from the Exponential distribution with the input mean. :param sc: SparkContext used to create the RDD. :param mean: Mean, or 1 / lambda, for the Exponential distribution. :param size: Size of the RDD. :param numPartitions: Number of p...
def get_android_resources(self): """ Return the :class:`ARSCParser` object which corresponds to the resources.arsc file :rtype: :class:`ARSCParser` """ try: return self.arsc["resources.arsc"] except KeyError: self.arsc["resources.arsc"] = ...
Return the :class:`ARSCParser` object which corresponds to the resources.arsc file :rtype: :class:`ARSCParser`
def transpose(a, axes=None): """Returns a view of the array with axes transposed. For a 1-D array, this has no effect. For a 2-D array, this is the usual matrix transpose. For an n-D array, if axes are given, their order indicates how the axes are permuted Args: a (array_like): Input arr...
Returns a view of the array with axes transposed. For a 1-D array, this has no effect. For a 2-D array, this is the usual matrix transpose. For an n-D array, if axes are given, their order indicates how the axes are permuted Args: a (array_like): Input array. axes (list of int, optiona...
def _ignore_sql(self, query): """Check to see if we should ignore the sql query.""" return any([ re.search(pattern, query.get('sql')) for pattern in QC_SETTINGS['IGNORE_SQL_PATTERNS'] ])
Check to see if we should ignore the sql query.
def get_minutes_description(self): """Generates a description for only the MINUTE portion of the expression Returns: The MINUTE description """ return self.get_segment_description( self._expression_parts[1], _("every minute"), lambda s: ...
Generates a description for only the MINUTE portion of the expression Returns: The MINUTE description
def logical_chassis_fwdl_status_output_cluster_fwdl_entries_fwdl_entries_blade_swbd(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") logical_chassis_fwdl_status = ET.Element("logical_chassis_fwdl_status") config = logical_chassis_fwdl_status outpu...
Auto Generated Code
def _expand_colspan_rowspan(self, rows): """ Given a list of <tr>s, return a list of text rows. Parameters ---------- rows : list of node-like List of <tr>s Returns ------- list of list Each returned row is a list of str text. ...
Given a list of <tr>s, return a list of text rows. Parameters ---------- rows : list of node-like List of <tr>s Returns ------- list of list Each returned row is a list of str text. Notes ----- Any cell with ``rowspan`` o...
def learn(self, bottomUpInput, enableInference=None): """ TODO: document :param bottomUpInput: :param enableInference: :return: """ return self.compute(bottomUpInput, enableLearn=True, enableInference=enableInference)
TODO: document :param bottomUpInput: :param enableInference: :return:
def delete(self, folder_id): """ Delete a specific campaign folder, and mark all the campaigns in the folder as ‘unfiled’. :param folder_id: The unique id for the campaign folder. :type folder_id: :py:class:`str` """ self.folder_id = folder_id return self...
Delete a specific campaign folder, and mark all the campaigns in the folder as ‘unfiled’. :param folder_id: The unique id for the campaign folder. :type folder_id: :py:class:`str`
def flipFlopFsm(self, fsmTable, *varBinds, **context): """Read, modify, create or remove Managed Objects Instances. Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType`, recursively transitions corresponding Managed Objects Instances through the Finite State Machine (FSM) states ...
Read, modify, create or remove Managed Objects Instances. Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType`, recursively transitions corresponding Managed Objects Instances through the Finite State Machine (FSM) states till it reaches its final stop state. Parameters ...
def get_arguments(self): """ Extracts the specific arguments of this CLI """ ApiCli.get_arguments(self) if self.args.hostGroupId is not None: self.hostGroupId = self.args.hostGroupId if self.args.force is not None: self.force = self.args.force ...
Extracts the specific arguments of this CLI
def __msgc_step3_discontinuity_localization(self): """ Estimate discontinuity in basis of low resolution image segmentation. :return: discontinuity in low resolution """ import scipy start = self._start_time seg = 1 - self.segmentation.astype(np.int8) sel...
Estimate discontinuity in basis of low resolution image segmentation. :return: discontinuity in low resolution
def full_parent_name(self): """Retrieves the fully qualified parent command name. This the base command name required to execute it. For example, in ``?one two three`` the parent name would be ``one two``. """ entries = [] command = self while command.parent is n...
Retrieves the fully qualified parent command name. This the base command name required to execute it. For example, in ``?one two three`` the parent name would be ``one two``.
def area(self): """ The surface area of the primitive extrusion. Calculated from polygon and height to avoid mesh creation. Returns ---------- area: float, surface area of 3D extrusion """ # area of the sides of the extrusion area = abs(self.prim...
The surface area of the primitive extrusion. Calculated from polygon and height to avoid mesh creation. Returns ---------- area: float, surface area of 3D extrusion
def colorize(text, messageType=None): """ Function that colorizes a message. Args: ----- text: The string to be colorized. messageType: Possible options include "ERROR", "WARNING", "SUCCESS", "INFO" or "BOLD". Returns: -------- string: Colorized if the optio...
Function that colorizes a message. Args: ----- text: The string to be colorized. messageType: Possible options include "ERROR", "WARNING", "SUCCESS", "INFO" or "BOLD". Returns: -------- string: Colorized if the option is correct, including a tag at the end ...
def url_for(self, *args, **kwargs): """Construct url for route with additional params.""" return yarl.URL(self.url(parts=kwargs))
Construct url for route with additional params.
def format_cffi_externs(cls): """Generate stubs for the cffi bindings from @_extern_decl methods.""" extern_decls = [ f.extern_signature.pretty_print() for _, f in cls._extern_fields.items() ] return ( 'extern "Python" {\n' + '\n'.join(extern_decls) + '\n}\n')
Generate stubs for the cffi bindings from @_extern_decl methods.
def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username...
Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults ...
def std(a, axis=None, ddof=0): """ Request the standard deviation of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. :param axis: Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation ...
Request the standard deviation of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. :param axis: Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation over all the dimensions of the ...
def lazy_connect(cls, pk): """ Create an object, setting its primary key without testing it. So the instance is not connected """ instance = cls() instance._pk = instance.pk.normalize(pk) instance._connected = False return instance
Create an object, setting its primary key without testing it. So the instance is not connected
def __perform_request(self, url, type=GET, params=None): """ This method will perform the real request, in this way we can customize only the "output" of the API call by using self.__call_api method. This method will return the request object. """ ...
This method will perform the real request, in this way we can customize only the "output" of the API call by using self.__call_api method. This method will return the request object.
def update_energy(self, bypass_check: bool = False): """Builds weekly, monthly and yearly dictionaries""" if bypass_check or (not bypass_check and self.update_time_check): self.get_weekly_energy() if 'week' in self.energy: self.get_monthly_energy() ...
Builds weekly, monthly and yearly dictionaries
def parse_comet(self): """Parse `targetname` as if it were a comet. :return: (string or None, int or None, string or None); The designation, number and prefix, and name of the comet as derived from `self.targetname` are extracted into a tuple; each element that does not ex...
Parse `targetname` as if it were a comet. :return: (string or None, int or None, string or None); The designation, number and prefix, and name of the comet as derived from `self.targetname` are extracted into a tuple; each element that does not exist is set to `None`. Parenthesis ...
def _process_book(book_url): """ Parse available informations about book from the book details page. Args: book_url (str): Absolute URL of the book. Returns: obj: :class:`structures.Publication` instance with book details. """ data = DOWNER.download(book_url) dom = dhtmlpar...
Parse available informations about book from the book details page. Args: book_url (str): Absolute URL of the book. Returns: obj: :class:`structures.Publication` instance with book details.
def _get_real_ip(self): """ Get IP from request. :param request: A usual request object :type request: HttpRequest :return: ipv4 string or None """ try: # Trying to work with most common proxy headers real_ip = self.request.META['HTTP_X_FO...
Get IP from request. :param request: A usual request object :type request: HttpRequest :return: ipv4 string or None
def cli(env, limit, closed=False, get_all=False): """Invoices and all that mess""" manager = AccountManager(env.client) invoices = manager.get_invoices(limit, closed, get_all) table = formatting.Table([ "Id", "Created", "Type", "Status", "Starting Balance", "Ending Balance", "Invoice Amount", ...
Invoices and all that mess
def delete(self, records, context): """ Removes the inputted record from the database. :param records | <orb.Collection> context | <orb.Context> :return <int> number of rows removed """ # include various schema records to remove DE...
Removes the inputted record from the database. :param records | <orb.Collection> context | <orb.Context> :return <int> number of rows removed
def add_criterion(self, name, priority, and_or, search_type, value): # pylint: disable=too-many-arguments """Add a search criteria object to a smart group. Args: name: String Criteria type name (e.g. "Application Title") priority: Int or Str number priority of criterion. ...
Add a search criteria object to a smart group. Args: name: String Criteria type name (e.g. "Application Title") priority: Int or Str number priority of criterion. and_or: Str, either "and" or "or". search_type: String Criteria search type. (e.g. "is", "is ...
def _set_pfiles(dry_run, **kwargs): """Set the PFILES env var Parameters ---------- dry_run : bool Don't actually run Keyword arguments ----------------- pfiles : str Value to set PFILES Returns ------- pfiles_orig : str Current value of PFILES e...
Set the PFILES env var Parameters ---------- dry_run : bool Don't actually run Keyword arguments ----------------- pfiles : str Value to set PFILES Returns ------- pfiles_orig : str Current value of PFILES envar
def ppf(q, df, loc=0.0, scale=1.0, gamma = 1.0): """ PPF function for Skew t distribution """ result = np.zeros(q.shape[0]) probzero = Skewt.cdf(x=np.zeros(1),loc=np.zeros(1),df=df,gamma=gamma) result[q<probzero] = 1.0/gamma*ss.t.ppf(((np.power(gamma,2) + 1.0) * q[q<probz...
PPF function for Skew t distribution
def get_profiles(self): """Returns set of profile names referenced in this Feature :returns: set of profile names """ out = set(x.profile for x in self.requires if x.profile) out.update(x.profile for x in self.removes if x.profile) return out
Returns set of profile names referenced in this Feature :returns: set of profile names
def sign_transaction(self, signer: Account): """ This interface is used to sign the transaction. :param signer: an Account object which will sign the transaction. :return: a Transaction object which has been signed. """ tx_hash = self.hash256() sig_data = signer....
This interface is used to sign the transaction. :param signer: an Account object which will sign the transaction. :return: a Transaction object which has been signed.
def set_state(self, state): """ used in unittests """ self.index_x.set(state[REG_X]) self.index_y.set(state[REG_Y]) self.user_stack_pointer.set(state[REG_U]) self.system_stack_pointer.set(state[REG_S]) self.program_counter.set(state[REG_PC]) sel...
used in unittests
def doNew(self, WHAT={}, **params): """This function will perform the command -new.""" if hasattr(WHAT, '_modified'): for key in WHAT: if key not in ['RECORDID','MODID']: if WHAT.__new2old__.has_key(key): self._addDBParam(WHAT.__new2old__[key].encode('utf-8'), WHAT[key]) else: self._ad...
This function will perform the command -new.
def notify(self, subsystem, recipient, subject, body_html, body_text): """You can send messages either to channels and private groups by using the following formats #channel-name @username-direct-message Args: subsystem (`str`): Name of the subsystem originating the notific...
You can send messages either to channels and private groups by using the following formats #channel-name @username-direct-message Args: subsystem (`str`): Name of the subsystem originating the notification recipient (`str`): Recipient subject (`str`): Subjec...
def save(self, file, contents, name=None, overwrite=False): """Save contents into a file. The format name can be specified explicitly or inferred from the file extension.""" if name is None: name = self.format_from_extension(op.splitext(file)[1]) file_format = self.file_type(...
Save contents into a file. The format name can be specified explicitly or inferred from the file extension.
def find_one(driver, locator_list, elem_type=CSS, timeout=TIMEOUT): """ Args: driver (selenium webdriver): Selenium webdriver object locator_list (:obj: `list` of :obj: `str`): List of CSS selector strings elem_type (Selenium By types): Selenium By type (i.e. By.CSS_SELECTOR) tim...
Args: driver (selenium webdriver): Selenium webdriver object locator_list (:obj: `list` of :obj: `str`): List of CSS selector strings elem_type (Selenium By types): Selenium By type (i.e. By.CSS_SELECTOR) timeout (int): Number of seconds to wait before timing out Returns: Se...
def com_google_fonts_check_metadata_match_filename_postscript(font_metadata): """METADATA.pb font.filename and font.post_script_name fields have equivalent values? """ post_script_name = font_metadata.post_script_name filename = os.path.splitext(font_metadata.filename)[0] if filename != post_script_name...
METADATA.pb font.filename and font.post_script_name fields have equivalent values?
def images(self, type): """ Return the list of images available for this type on controller and on the compute node. """ images = [] res = yield from self.http_query("GET", "/{}/images".format(type), timeout=None) images = res.json try: if ty...
Return the list of images available for this type on controller and on the compute node.
def read_header(filename): ''' returns a dictionary of values in the header of the given file ''' header = {} in_header = False data = nl.universal_read(filename) lines = [x.strip() for x in data.split('\n')] for line in lines: if line=="*** Header Start ***": in_header=True ...
returns a dictionary of values in the header of the given file
def sign_digest_deterministic(self, digest, hashfunc=None, sigencode=sigencode_string): """ Calculates 'k' from data itself, removing the need for strong random generator and producing deterministic (reproducible) signatures. See RFC 6979 for more details. """ secexp = se...
Calculates 'k' from data itself, removing the need for strong random generator and producing deterministic (reproducible) signatures. See RFC 6979 for more details.
def is_close_to(self, other, tolerance): """Asserts that val is numeric and is close to other within tolerance.""" self._validate_close_to_args(self.val, other, tolerance) if self.val < (other-tolerance) or self.val > (other+tolerance): if type(self.val) is datetime.datetime: ...
Asserts that val is numeric and is close to other within tolerance.
def read_gtfs(path: Path, dist_units: str) -> "Feed": """ Create a Feed instance from the given path and given distance units. The path should be a directory containing GTFS text files or a zip file that unzips as a collection of GTFS text files (and not as a directory containing GTFS text files). ...
Create a Feed instance from the given path and given distance units. The path should be a directory containing GTFS text files or a zip file that unzips as a collection of GTFS text files (and not as a directory containing GTFS text files). The distance units given must lie in :const:`constants.dist_uni...
def AgregarDatoPDF(self, campo, valor, pagina='T'): "Agrego un dato a la factura (internamente)" # corrijo path relativo para las imágenes (compatibilidad hacia atrás): if campo == 'fondo' and valor.startswith(self.InstallDir): if not os.path.exists(valor): valor = os...
Agrego un dato a la factura (internamente)
def exclude_reference_link(self, exclude): """Sets `sysparm_exclude_reference_link` to a bool value :param exclude: bool """ if not isinstance(exclude, bool): raise InvalidUsage('exclude_reference_link must be of type bool') self._sysparms['sysparm_exclude_reference...
Sets `sysparm_exclude_reference_link` to a bool value :param exclude: bool