code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def block_html(self, html): """Rendering block level pure html content. :param html: text content of the html snippet. """ if self.options.get('skip_style') and \ html.lower().startswith('<style'): return '' if self.options.get('escape'): retur...
Rendering block level pure html content. :param html: text content of the html snippet.
def run_single_with_display(wf, display): """Adds a display to the single runner. Everything still runs in a single thread. Every time a job is pulled by the worker, a message goes to the display routine; when the job is finished the result is sent to the display routine.""" S = Scheduler(error_hand...
Adds a display to the single runner. Everything still runs in a single thread. Every time a job is pulled by the worker, a message goes to the display routine; when the job is finished the result is sent to the display routine.
def uncrop(data, crinfo, orig_shape, resize=False, outside_mode="constant", cval=0): """ Put some boundary to input image. :param data: input data :param crinfo: array with minimum and maximum index along each axis [[minX, maxX],[minY, maxY],[minZ, maxZ]]. If crinfo is None, the whole input im...
Put some boundary to input image. :param data: input data :param crinfo: array with minimum and maximum index along each axis [[minX, maxX],[minY, maxY],[minZ, maxZ]]. If crinfo is None, the whole input image is placed into [0, 0, 0]. If crinfo is just series of three numbers, it is used as an...
def create_regular_expression(self, regexp): """ Create a regular expression for this inspection situation context. The inspection situation must be using an inspection context that supports regex. :param str regexp: regular expression string :raises CreateElemen...
Create a regular expression for this inspection situation context. The inspection situation must be using an inspection context that supports regex. :param str regexp: regular expression string :raises CreateElementFailed: failed to modify the situation
def getfqdn(name=''): """Get fully qualified domain name from name. An empty argument is interpreted as meaning the local host. First the hostname returned by gethostbyaddr() is checked, then possibly existing aliases. In case no FQDN is available, hostname from gethostname() is returned. """ ...
Get fully qualified domain name from name. An empty argument is interpreted as meaning the local host. First the hostname returned by gethostbyaddr() is checked, then possibly existing aliases. In case no FQDN is available, hostname from gethostname() is returned.
def object(self, o_type, o_name=None): """Get an object from the scheduler. The result is a serialized object which is a Json structure containing: - content: the serialized object content - __sys_python_module__: the python class of the returned object The Alignak unserialize ...
Get an object from the scheduler. The result is a serialized object which is a Json structure containing: - content: the serialized object content - __sys_python_module__: the python class of the returned object The Alignak unserialize function of the alignak.misc.serialization package...
def add_mod(self, seq, mod): """Create a tree.{Complement, LookAhead, Neg, Until}""" modstr = self.value(mod) if modstr == '~': seq.parser_tree = parsing.Complement(seq.parser_tree) elif modstr == '!!': seq.parser_tree = parsing.LookAhead(seq.parser_tree) elif modstr == '!': ...
Create a tree.{Complement, LookAhead, Neg, Until}
def _setup_metric_group_values(self): """ Return the list of MetricGroupValues objects for this metrics response, by processing its metrics response string. The lines in the metrics response string are:: MetricsResponse: MetricsGroup{0,*} <empty...
Return the list of MetricGroupValues objects for this metrics response, by processing its metrics response string. The lines in the metrics response string are:: MetricsResponse: MetricsGroup{0,*} <emptyline> a third empty line at the end Metr...
def project_from_files( files, func_wrapper=_astroid_wrapper, project_name="no name", black_list=("CVS",) ): """return a Project from a list of files or modules""" # build the project representation astroid_manager = manager.AstroidManager() project = Project(project_name) for something in files...
return a Project from a list of files or modules
def upload_file_handle( self, bucket: str, key: str, src_file_handle: typing.BinaryIO, content_type: str=None, metadata: dict=None): """ Saves the contents of a file handle as the contents of an object in a bucket. """ ...
Saves the contents of a file handle as the contents of an object in a bucket.
def uninstall(self, package): """Uninstalls the given package (given in pip's package syntax or a tuple of ('name', 'ver')) from this virtual environment.""" if isinstance(package, tuple): package = '=='.join(package) if not self.is_installed(package): self._write...
Uninstalls the given package (given in pip's package syntax or a tuple of ('name', 'ver')) from this virtual environment.
def delete(args): """ Delete a template by name """ m = TemplateManager(args.hosts) m.delete(args.name)
Delete a template by name
def _scatter_obs( adata, x=None, y=None, color=None, use_raw=None, layers='X', sort_order=True, alpha=None, basis=None, groups=None, components=None, projection='2d', legend_loc='right margin', legend_fontsiz...
See docstring of scatter.
def pkg_config_libdirs(packages): """ Returns a list of all library paths that pkg-config says should be included when linking against the list of packages given as 'packages'. An empty return list means that the package may be found in the standard system locations, irrespective of pkg-config. ...
Returns a list of all library paths that pkg-config says should be included when linking against the list of packages given as 'packages'. An empty return list means that the package may be found in the standard system locations, irrespective of pkg-config.
def children(self): """"Return the table's other column that have this column as a parent, excluding labels""" for c in self.table.columns: if c.parent == self.name and not c.valuetype_class.is_label(): yield c
Return the table's other column that have this column as a parent, excluding labels
def format_lines(statements, lines): """Nicely format a list of line numbers. Format a list of line numbers for printing by coalescing groups of lines as long as the lines represent consecutive statements. This will coalesce even if there are gaps between statements. For example, if `statements` ...
Nicely format a list of line numbers. Format a list of line numbers for printing by coalescing groups of lines as long as the lines represent consecutive statements. This will coalesce even if there are gaps between statements. For example, if `statements` is [1,2,3,4,5,10,11,12,13,14] and `lines...
def stage_config(self): """ A shortcut property for settings of a stage. """ def get_stage_setting(stage, extended_stages=None): if extended_stages is None: extended_stages = [] if stage in extended_stages: raise RuntimeError(stag...
A shortcut property for settings of a stage.
def _len_objid(self): '''Get the actual size of the content, as some attributes have variable sizes''' try: return self._size except AttributeError: temp = (self.object_id, self.birth_vol_id, self.birth_object_id, self.birth_domain_id) self._size = sum([ObjectID._UUID_SIZE for data i...
Get the actual size of the content, as some attributes have variable sizes
def _update_progress(self, percentage, **kwargs): """ Update the progress with a percentage, including updating the progressbar as well as calling the progress callback. :param float percentage: Percentage of the progressbar. from 0.0 to 100.0. :param kwargs: Oth...
Update the progress with a percentage, including updating the progressbar as well as calling the progress callback. :param float percentage: Percentage of the progressbar. from 0.0 to 100.0. :param kwargs: Other parameters that will be passed to the progress_callback handler. ...
def create_channel( self, name, values=None, *, shape=None, units=None, dtype=None, **kwargs ) -> Channel: """Append a new channel. Parameters ---------- name : string Unique name for this channel. values : array (optional) Array. If None, an ...
Append a new channel. Parameters ---------- name : string Unique name for this channel. values : array (optional) Array. If None, an empty array equaling the data shape is created. Default is None. shape : tuple of int Shape to use...
def choose(n, k): """ A fast way to calculate binomial coefficients by Andrew Dalke (contrib). """ if 0 <= k <= n: ntok = 1 ktok = 1 for t in xrange(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 return ntok // ktok else: ...
A fast way to calculate binomial coefficients by Andrew Dalke (contrib).
def added_env_paths(env_vars, env=None): """ :param dict|None env_vars: Env vars to customize :param dict env: Original env vars """ if not env_vars: return None if not env: env = dict(os.environ) result = dict(env) for env_var, paths in env_vars.items(): separa...
:param dict|None env_vars: Env vars to customize :param dict env: Original env vars
def connect_put_namespaced_service_proxy_with_path(self, name, namespace, path, **kwargs): # noqa: E501 """connect_put_namespaced_service_proxy_with_path # noqa: E501 connect PUT requests to proxy of Service # noqa: E501 This method makes a synchronous HTTP request by default. To make an ...
connect_put_namespaced_service_proxy_with_path # noqa: E501 connect PUT requests to proxy of Service # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_put_namespaced_service_p...
def role_exists(role, **kwargs): ''' Checks if a role exists. CLI Example: .. code-block:: bash salt minion mssql.role_exists db_owner ''' # We should get one, and only one row return len(tsql_query(query='sp_helprole "{0}"'.format(role), as_dict=True, **kwargs)) == 1
Checks if a role exists. CLI Example: .. code-block:: bash salt minion mssql.role_exists db_owner
def list_authors(): """List all authors. e.g.: GET /authors""" authors = Author.query.all() content = '<p>Authors:</p>' for author in authors: content += '<p>%s</p>' % author.name return content
List all authors. e.g.: GET /authors
def poisson_equation(image, gradient=1, max_iter=100, convergence=.01, percentile = 90.0): '''Estimate the solution to the Poisson Equation The Poisson Equation is the solution to gradient(x) = h^2/4 and, in this context, we use a boundary condition where x is zero for background pixels. Also, we set h...
Estimate the solution to the Poisson Equation The Poisson Equation is the solution to gradient(x) = h^2/4 and, in this context, we use a boundary condition where x is zero for background pixels. Also, we set h^2/4 = 1 to indicate that each pixel is a distance of 1 from its neighbors. The estimatio...
def apply_parameters(self, parameters): """Recursively apply dictionary entries in 'parameters' to {item}s in recipe structure, leaving undefined {item}s as they are. A special case is a {$REPLACE:item}, which replaces the string with a copy of the referenced parameter item. Exa...
Recursively apply dictionary entries in 'parameters' to {item}s in recipe structure, leaving undefined {item}s as they are. A special case is a {$REPLACE:item}, which replaces the string with a copy of the referenced parameter item. Examples: parameters = { 'x':'5' } ap...
def _compute_sources_for_target(self, target): """Computes and returns the sources (relative to buildroot) for the given target.""" def resolve_target_sources(target_sources): resolved_sources = [] for tgt in target_sources: if tgt.has_sources(): resolved_sources.extend(tgt.sources...
Computes and returns the sources (relative to buildroot) for the given target.
def from_string(string): """ Reads an PWInput object from a string. Args: string (str): PWInput string Returns: PWInput object """ lines = list(clean_lines(string.splitlines())) def input_mode(line): if line[0] == "&": ...
Reads an PWInput object from a string. Args: string (str): PWInput string Returns: PWInput object
def _from_dict(cls, _dict): """Initialize a WorkspaceSystemSettings object from a json dictionary.""" args = {} if 'tooling' in _dict: args['tooling'] = WorkspaceSystemSettingsTooling._from_dict( _dict.get('tooling')) if 'disambiguation' in _dict: ...
Initialize a WorkspaceSystemSettings object from a json dictionary.
def update_settings(self, settings, force=False, timeout=-1): """ Updates interconnect settings on the logical interconnect. Changes to interconnect settings are asynchronously applied to all managed interconnects. (This method is not available from API version 600 onwards) Args:...
Updates interconnect settings on the logical interconnect. Changes to interconnect settings are asynchronously applied to all managed interconnects. (This method is not available from API version 600 onwards) Args: settings: Interconnect settings force: If set to true, th...
def get_html_string(self, **kwargs): """Return string representation of HTML formatted version of table in current state. Arguments: start - index of first data row to include in output end - index of last data row to include in output PLUS ONE (list slice style) fields - name...
Return string representation of HTML formatted version of table in current state. Arguments: start - index of first data row to include in output end - index of last data row to include in output PLUS ONE (list slice style) fields - names of fields (columns) to include header -...
def partial(self, *args): """ Partially apply a function by creating a version that has had some of its arguments pre-filled, without changing its dynamic `this` context. """ def part(*args2): args3 = args + args2 return self.obj(*args3) return se...
Partially apply a function by creating a version that has had some of its arguments pre-filled, without changing its dynamic `this` context.
def _CreateDatabase(self): """ Create all database tables. """ goodlogging.Log.Info("DB", "Initialising new database", verbosity=self.logVerbosity) with sqlite3.connect(self._dbPath) as db: # Configuration tables db.execute("CREATE TABLE Config (" "Name TEXT UNIQUE NOT NULL, "...
Create all database tables.
def __getCashToBuyStock(self): ''' calculate the amount of money to buy stock ''' account=self.__strategy.getAccountCopy() if (account.getCash() >= account.getTotalValue() / self.buying_ratio): return account.getTotalValue() / self.buying_ratio else: return 0
calculate the amount of money to buy stock
def write_main(self): ''' Writes out a huge string representing the main section of the python compiled toil script. Currently looks at and writes 5 sections: 1. JSON Variables (includes importing and preparing files as tuples) 2. TSV Variables (includes importing and pr...
Writes out a huge string representing the main section of the python compiled toil script. Currently looks at and writes 5 sections: 1. JSON Variables (includes importing and preparing files as tuples) 2. TSV Variables (includes importing and preparing files as tuples) 3. CSV Va...
def inferRowCompat(self, distribution): """ Equivalent to the category inference of zeta1.TopLevel. Computes the max_prod (maximum component of a component-wise multiply) between the rows of the histogram and the incoming distribution. May be slow if the result of clean_outcpd() is not valid. :...
Equivalent to the category inference of zeta1.TopLevel. Computes the max_prod (maximum component of a component-wise multiply) between the rows of the histogram and the incoming distribution. May be slow if the result of clean_outcpd() is not valid. :param distribution: Array of length equal to the num...
def compile_vocab(docs, limit=1e6, verbose=0, tokenizer=Tokenizer(stem=None, lower=None, strip=None)): """Get the set of words used anywhere in a sequence of documents and assign an integer id This vectorizer is much faster than the scikit-learn version (and only requires low/constant RAM ?). >>> gen = ('...
Get the set of words used anywhere in a sequence of documents and assign an integer id This vectorizer is much faster than the scikit-learn version (and only requires low/constant RAM ?). >>> gen = ('label: ' + chr(ord('A') + i % 3)*3 for i in range(11)) >>> d = compile_vocab(gen, verbose=0) >>> d ...
def search_messages(session, thread_id, query, limit=20, offset=0, message_context_details=None, window_above=None, window_below=None): """ Search for messages """ query = { 'thread_id': thread_id, 'query': query, 'limit': limit, 'o...
Search for messages
def prepare_dispatches(): """Automatically creates dispatches for messages without them. :return: list of Dispatch :rtype: list """ dispatches = [] target_messages = Message.get_without_dispatches() cache = {} for message_model in target_messages: if message_model.cls not in ...
Automatically creates dispatches for messages without them. :return: list of Dispatch :rtype: list
def greaterThan(self, value): """ Sets the operator type to Query.Op.GreaterThan and sets the value to the inputted value. :param value <variant> :return <Query> :sa __gt__ :usage |>>> from orb import...
Sets the operator type to Query.Op.GreaterThan and sets the value to the inputted value. :param value <variant> :return <Query> :sa __gt__ :usage |>>> from orb import Query as Q |>>> query = Q('te...
def write_error(self, status_code, **kwargs): ''' :param status_code: :param kwargs: :return: ''' if "exc_info" in kwargs: exc_info = kwargs["exc_info"] error = exc_info[1] errormessage = "%s: %s" % (status_code, error) self.render("error.html", errormessage=errormessage...
:param status_code: :param kwargs: :return:
def macontrol(self, data: ['SASdata', str] = None, ewmachart: str = None, machart: str = None, procopts: str = None, stmtpassthrough: str = None, **kwargs: dict) -> 'SASresults': """ Python method to call the MACON...
Python method to call the MACONTROL procedure Documentation link: https://go.documentation.sas.com/?cdcId=pgmsascdc&cdcVersion=9.4_3.4&docsetId=qcug&docsetTarget=qcug_macontrol_toc.htm&locale=en :param data: SASdata object or string. This parameter is required. :parm ewmachart: The ewm...
def get_edit_token(self): """ Can be called in order to retrieve the edit token from an instance of WDLogin :return: returns the edit token """ if not self.edit_token or (time.time() - self.instantiation_time) > self.token_renew_period: self.generate_edit_credentials(...
Can be called in order to retrieve the edit token from an instance of WDLogin :return: returns the edit token
async def disconnect(self): """ Shuts down and disconnects the websocket. """ self._is_shutdown = True self.ready.clear() self.update_state(NodeState.DISCONNECTING) await self.player_manager.disconnect() if self._ws is not None and self._ws.open: ...
Shuts down and disconnects the websocket.
def lvscan(self): """ Probes the volume group for logical volumes and returns a list of LogicalVolume instances:: from lvm2py import * lvm = LVM() vg = lvm.get_vg("myvg") lvs = vg.lvscan() *Raises:* * HandleError "...
Probes the volume group for logical volumes and returns a list of LogicalVolume instances:: from lvm2py import * lvm = LVM() vg = lvm.get_vg("myvg") lvs = vg.lvscan() *Raises:* * HandleError
def save(self, filename=None, *, gzipped=None, byteorder=None): """Write the file at the specified location. The `gzipped` keyword only argument indicates if the file should be gzipped. The `byteorder` keyword only argument lets you specify whether the file should be big-endian or ...
Write the file at the specified location. The `gzipped` keyword only argument indicates if the file should be gzipped. The `byteorder` keyword only argument lets you specify whether the file should be big-endian or little-endian. If the method is called without any argument, it w...
def server_exists(s_name, ip=None, s_state=None, **connection_args): ''' Checks if a server exists CLI Example: .. code-block:: bash salt '*' netscaler.server_exists 'serverName' ''' server = _server_get(s_name, **connection_args) if server is None: return False if ip ...
Checks if a server exists CLI Example: .. code-block:: bash salt '*' netscaler.server_exists 'serverName'
def _map_block_index_to_location(ir_blocks): """Associate each IR block with its corresponding location, by index.""" block_index_to_location = {} # MarkLocation blocks occur after the blocks related to that location. # The core approach here is to buffer blocks until their MarkLocation is encountered ...
Associate each IR block with its corresponding location, by index.
def save_anim(self, fig, animate, init, bitrate=10000, fps=30): """Not functional -- TODO""" from matplotlib import animation anim = animation.FuncAnimation(fig, animate, init_func=init, frames=360, interval=20) FFMpegWriter = animation.writers['ffmpeg'] writer = FFMpegWriter(bit...
Not functional -- TODO
def count(self): """Approximate number of results, according to the API""" if self._total_count is None: self._total_count = self._get_total_count() return self._total_count
Approximate number of results, according to the API
def fetch(self, start=False, full_data=True): """ Get the current job data and possibly flag it as started. """ if self.id is None: return self if full_data is True: fields = None elif isinstance(full_data, dict): fields = full_data else: ...
Get the current job data and possibly flag it as started.
def personal_sign(self, message, account, password=None): """https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign :param message: Message for sign :type message: str :param account: Account address :type account: str :param password: Password of a...
https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign :param message: Message for sign :type message: str :param account: Account address :type account: str :param password: Password of account (optional) :type password: str :return: signa...
def _cut_to_pieces(self, bunch_stack): """ :type bunch_stack: list of list of int """ stack_len = len(bunch_stack[0]) for i in xrange(0, stack_len, self.fragment_length): yield np.array(map(lambda stack: stack[i: i + self.fragment_length], bunch_stack))
:type bunch_stack: list of list of int
async def setup_hostname() -> str: """ Intended to be run when the server starts. Sets the machine hostname. The machine hostname is set from the systemd-generated machine-id, which changes at every boot. Once the hostname is set, we restart avahi. This is a separate task from establishing an...
Intended to be run when the server starts. Sets the machine hostname. The machine hostname is set from the systemd-generated machine-id, which changes at every boot. Once the hostname is set, we restart avahi. This is a separate task from establishing and changing the opentrons machine name, whic...
def sign(self, value): """Signs the given string and also attaches a time information.""" value = want_bytes(value) timestamp = base64_encode(int_to_bytes(self.get_timestamp())) sep = want_bytes(self.sep) value = value + sep + timestamp return value + sep + self.get_signa...
Signs the given string and also attaches a time information.
def modification_time(self): """dfdatetime.DateTimeValues: modification time or None if not available.""" timestamp = getattr( self._cpio_archive_file_entry, 'modification_time', None) if timestamp is None: return None return dfdatetime_posix_time.PosixTime(timestamp=timestamp)
dfdatetime.DateTimeValues: modification time or None if not available.
def register_type(self, typename): """ Registers a type name so that it may be used to send and receive packages. :param typename: Name of the packet type. A method with the same name and a "on_" prefix should be added to handle incomming packets. :raise...
Registers a type name so that it may be used to send and receive packages. :param typename: Name of the packet type. A method with the same name and a "on_" prefix should be added to handle incomming packets. :raises ValueError: If there is a hash code collision.
def issue_instant_ok(self): """ Check that the response was issued at a reasonable time """ upper = time_util.shift_time(time_util.time_in_a_while(days=1), self.timeslack).timetuple() lower = time_util.shift_time(time_util.time_a_while_ago(days=1), ...
Check that the response was issued at a reasonable time
def is_script(self, container): """Returns `True` if this styled text is super/subscript.""" try: style = self._style(container) return style.get_value('position', container) != TextPosition.NORMAL except StyleException: retu...
Returns `True` if this styled text is super/subscript.
def _parse_proxy(proxy): """Return (scheme, user, password, host/port) given a URL or an authority. If a URL is supplied, it must have an authority (host:port) component. According to RFC 3986, having an authority component means the URL must have two slashes after the scheme: >>> _parse_proxy('fi...
Return (scheme, user, password, host/port) given a URL or an authority. If a URL is supplied, it must have an authority (host:port) component. According to RFC 3986, having an authority component means the URL must have two slashes after the scheme: >>> _parse_proxy('file:/ftp.example.com/') Trace...
def wait_for_current_tasks(self): """Waits for all tasks in the task list to be completed, by waiting for their AppFuture to be completed. This method will not necessarily wait for any tasks added after cleanup has started (such as data stageout?) """ logger.info("Waiting for al...
Waits for all tasks in the task list to be completed, by waiting for their AppFuture to be completed. This method will not necessarily wait for any tasks added after cleanup has started (such as data stageout?)
def symmetry_reduce(tensors, structure, tol=1e-8, **kwargs): """ Function that converts a list of tensors corresponding to a structure and returns a dictionary consisting of unique tensor keys with symmop values corresponding to transformations that will result in derivative tensors from the origina...
Function that converts a list of tensors corresponding to a structure and returns a dictionary consisting of unique tensor keys with symmop values corresponding to transformations that will result in derivative tensors from the original list Args: tensors (list of tensors): list of Tensor objec...
def point_in_segment(ac, b): ''' point_in_segment((a,b), c) yields True if point x is in segment (a,b) and False otherwise. Note that this differs from point_on_segment in that a point that if c is equal to a or b it is considered 'on' but not 'in' the segment. ''' (a,c) = ac abc = [np.asarr...
point_in_segment((a,b), c) yields True if point x is in segment (a,b) and False otherwise. Note that this differs from point_on_segment in that a point that if c is equal to a or b it is considered 'on' but not 'in' the segment.
def count_collisions(Collisions): """ Counts the number of unique collisions and gets the collision index. Parameters ---------- Collisions : array_like Array of booleans, containing true if during a collision event, false otherwise. Returns ------- CollisionCount : int ...
Counts the number of unique collisions and gets the collision index. Parameters ---------- Collisions : array_like Array of booleans, containing true if during a collision event, false otherwise. Returns ------- CollisionCount : int Number of unique collisions CollisionIndi...
def exists(name=None, region=None, key=None, keyid=None, profile=None, vpc_id=None, vpc_name=None, group_id=None): ''' Check to see if a security group exists. CLI example:: salt myminion boto_secgroup.exists mysecgroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, p...
Check to see if a security group exists. CLI example:: salt myminion boto_secgroup.exists mysecgroup
def print_results(self): """Print results of the package command.""" # Updates if self.package_data.get('updates'): print('\n{}{}Updates:'.format(c.Style.BRIGHT, c.Fore.BLUE)) for p in self.package_data['updates']: print( '{!s:<20}{}{} ...
Print results of the package command.
def NDP_Attack_DAD_DoS_via_NA(iface=None, mac_src_filter=None, tgt_filter=None, reply_mac=None): """ Perform the DAD DoS attack using NS described in section 4.1.3 of RFC 3756. This is done by listening incoming NS messages *sent from the unspecified address* and sending a ...
Perform the DAD DoS attack using NS described in section 4.1.3 of RFC 3756. This is done by listening incoming NS messages *sent from the unspecified address* and sending a NA reply for the target address, leading the peer to believe that another node is also performing DAD for that address. By def...
def cover(self, match_set): """Return a new classifier rule that can be added to the match set, with a condition that matches the situation of the match set and an action selected to avoid duplication of the actions already contained therein. The match_set argument is a MatchSet instance...
Return a new classifier rule that can be added to the match set, with a condition that matches the situation of the match set and an action selected to avoid duplication of the actions already contained therein. The match_set argument is a MatchSet instance representing the match set to ...
def matching_tokens(self, text, start=0): """Retrieve all token definitions matching the beginning of a text. Args: text (str): the text to test start (int): the position where matches should be searched in the string (see re.match(rx, txt, pos)) Yields:...
Retrieve all token definitions matching the beginning of a text. Args: text (str): the text to test start (int): the position where matches should be searched in the string (see re.match(rx, txt, pos)) Yields: (token_class, re.Match): all token class...
def install(args: List[str]) -> None: """`pip install` as a function. Accepts a list of pip arguments. .. code-block:: py >>> install(['numpy', '--target', 'site-packages']) Collecting numpy Downloading numpy-1.13.3-cp35-cp35m-manylinux1_x86_64.whl (16.9MB) 100% || 16....
`pip install` as a function. Accepts a list of pip arguments. .. code-block:: py >>> install(['numpy', '--target', 'site-packages']) Collecting numpy Downloading numpy-1.13.3-cp35-cp35m-manylinux1_x86_64.whl (16.9MB) 100% || 16.9MB 53kB/s Installing collected packa...
def build_index_from_design(df, design, remove_prefix=None, types=None, axis=1, auto_convert_numeric=True, unmatched_columns='index'): """ Build a MultiIndex from a design table. Supply with a table with column headings for the new multiindex and a index containing the labels to search for in the data....
Build a MultiIndex from a design table. Supply with a table with column headings for the new multiindex and a index containing the labels to search for in the data. :param df: :param design: :param remove: :param types: :param axis: :param auto_convert_numeric: :return:
def ics2task(): """Command line tool to convert from iCalendar to Taskwarrior""" from argparse import ArgumentParser, FileType from sys import stdin parser = ArgumentParser(description='Converter from iCalendar to Taskwarrior syntax.') parser.add_argument('infile', nargs='?', type=FileType('r'), de...
Command line tool to convert from iCalendar to Taskwarrior
def _addToSegmentUpdates(self, c, i, segUpdate): """ Store a dated potential segment update. The "date" (iteration index) is used later to determine whether the update is too old and should be forgotten. This is controlled by parameter ``segUpdateValidDuration``. :param c: TODO: document :param...
Store a dated potential segment update. The "date" (iteration index) is used later to determine whether the update is too old and should be forgotten. This is controlled by parameter ``segUpdateValidDuration``. :param c: TODO: document :param i: TODO: document :param segUpdate: TODO: document
def obj_box_zoom( im, classes=None, coords=None, zoom_range=(0.9, 1.1), row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0., order=1, is_rescale=False, is_center=False, is_random=False, thresh_wh=0.02, thresh_wh2=12. ): """Zoom i...
Zoom in and out of a single image, randomly or non-randomly, and compute the new bounding box coordinates. Objects outside the cropped image will be removed. Parameters ----------- im : numpy.array An image with dimension of [row, col, channel] (default). classes : list of int or None ...
def concentric_circles_path(size): """ Yields a set of paths that are concentric circles, moving outwards, about the center of the image. :param size: The (width, height) of the image :return: Yields individual circles, where each circle is a generator that yields pixel coordinates. """ width, ...
Yields a set of paths that are concentric circles, moving outwards, about the center of the image. :param size: The (width, height) of the image :return: Yields individual circles, where each circle is a generator that yields pixel coordinates.
def getOverlayInputMethod(self, ulOverlayHandle): """Returns the current input settings for the specified overlay.""" fn = self.function_table.getOverlayInputMethod peInputMethod = VROverlayInputMethod() result = fn(ulOverlayHandle, byref(peInputMethod)) return result, peInputMe...
Returns the current input settings for the specified overlay.
def str(self, var, default=NOTSET, multiline=False): """ :rtype: str """ value = self.get_value(var, default=default) if multiline: return value.replace('\\n', '\n') return value
:rtype: str
def decompose_by_component(model, observed_time_series, parameter_samples): """Decompose an observed time series into contributions from each component. This method decomposes a time series according to the posterior represention of a structural time series model. In particular, it: - Computes the posterior ...
Decompose an observed time series into contributions from each component. This method decomposes a time series according to the posterior represention of a structural time series model. In particular, it: - Computes the posterior marginal mean and covariances over the additive model's latent space. -...
def img2img_transformer2d_n31(): """Set of hyperparameters.""" hparams = img2img_transformer2d_base() hparams.batch_size = 1 hparams.num_encoder_layers = 6 hparams.num_decoder_layers = 12 hparams.num_heads = 8 hparams.query_shape = (16, 32) hparams.memory_flange = (16, 32) return hparams
Set of hyperparameters.
def parse_media_range(range): """Carves up a media range and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/*;q=0.5' would get parsed into: ('application', '*', {'q...
Carves up a media range and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/*;q=0.5' would get parsed into: ('application', '*', {'q', '0.5'}) In addition this f...
def add_node(self, info): """ Handles adding a Node to the graph. """ if not info.initialized: return graph = self._request_graph(info.ui.control) if graph is None: return IDs = [v.ID for v in graph.nodes] node = Node(ID=make_unique_name...
Handles adding a Node to the graph.
def check(self, completed, failed=None): """check whether our dependencies have been met.""" if len(self) == 0: return True against = set() if self.success: against = completed if failed is not None and self.failure: against = against.union(fai...
check whether our dependencies have been met.
def init(): """ Initializes the GLFW library. Wrapper for: int glfwInit(void); """ cwd = _getcwd() res = _glfw.glfwInit() os.chdir(cwd) return res
Initializes the GLFW library. Wrapper for: int glfwInit(void);
def _get_struct_dropshadowfilter(self): """Get the values for the DROPSHADOWFILTER record.""" obj = _make_object("DropShadowFilter") obj.DropShadowColor = self._get_struct_rgba() obj.BlurX = unpack_fixed16(self._src) obj.BlurY = unpack_fixed16(self._src) obj.Angle = unpac...
Get the values for the DROPSHADOWFILTER record.
def setattr(self, name, val): """ Change the attribute value of the UI element. Not all attributes can be casted to text. If changing the immutable attributes or attributes which do not exist, the InvalidOperationException exception is raised. Args: name: attribute name ...
Change the attribute value of the UI element. Not all attributes can be casted to text. If changing the immutable attributes or attributes which do not exist, the InvalidOperationException exception is raised. Args: name: attribute name val: new attribute value to cast ...
def _set_lldp(self, v, load=False): """ Setter method for lldp, mapped from YANG variable /protocol/lldp (container) If this variable is read-only (config: false) in the source YANG file, then _set_lldp is considered as a private method. Backends looking to populate this variable should do so vi...
Setter method for lldp, mapped from YANG variable /protocol/lldp (container) If this variable is read-only (config: false) in the source YANG file, then _set_lldp is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_lldp() directly.
def list_overlay_names(self): """Return list of overlay names.""" overlay_names = [] for fname in _ls(self._overlays_abspath): name, ext = os.path.splitext(fname) overlay_names.append(name) return overlay_names
Return list of overlay names.
def read_client_secrets(): '''for private or protected registries, a client secrets file is required to be located at .sregistry. If no secrets are found, we use default of Singularity Hub, and return a dummy secrets. ''' client_secrets = _default_client_secrets() # If token file not prov...
for private or protected registries, a client secrets file is required to be located at .sregistry. If no secrets are found, we use default of Singularity Hub, and return a dummy secrets.
def infos(self, type=None, failed=False): """Get all infos created by the participants nodes. Return a list of infos produced by nodes associated with the participant. If specified, ``type`` filters by class. By default, failed infos are excluded, to include only failed nodes use ``fail...
Get all infos created by the participants nodes. Return a list of infos produced by nodes associated with the participant. If specified, ``type`` filters by class. By default, failed infos are excluded, to include only failed nodes use ``failed=True``, for all nodes use ``failed=all``. ...
def build_message(self, checker): """Builds the checker's error message to report""" solution = ' (%s)' % checker.solution if self.with_solutions else '' return '{} {}{}'.format(checker.code, checker.msg, solution)
Builds the checker's error message to report
def filter_composite_from_subgroups(s): """ Given a sorted list of subgroups, return a string appropriate to provide as the a composite track's `filterComposite` argument >>> import trackhub >>> trackhub.helpers.filter_composite_from_subgroups(['cell', 'ab', 'lab', 'knockdown']) 'dimA dimB' ...
Given a sorted list of subgroups, return a string appropriate to provide as the a composite track's `filterComposite` argument >>> import trackhub >>> trackhub.helpers.filter_composite_from_subgroups(['cell', 'ab', 'lab', 'knockdown']) 'dimA dimB' Parameters ---------- s : list A l...
def status_counter(self): """ Returns a `Counter` object that counts the number of task with given status (use the string representation of the status as key). """ counter = collections.Counter() for task in self: counter[str(task.status)] += 1 retur...
Returns a `Counter` object that counts the number of task with given status (use the string representation of the status as key).
def get_reference_line_numeration_marker_patterns(prefix=u''): """Return a list of compiled regex patterns used to search for the marker. Marker of a reference line in a full-text document. :param prefix: (string) the possible prefix to a reference line :return: (list) of compiled regex patterns. ...
Return a list of compiled regex patterns used to search for the marker. Marker of a reference line in a full-text document. :param prefix: (string) the possible prefix to a reference line :return: (list) of compiled regex patterns.
def gather_dilated_memory_blocks(x, num_memory_blocks, gap_size, query_block_size, memory_block_size, gather_indices, dire...
Gathers blocks with gaps in between. Args: x: Tensor of shape [length, batch, heads, depth] num_memory_blocks: how many memory blocks to look in "direction". Each will be separated by gap_size. gap_size: an integer indicating the gap size query_block_size: an integer indicating size of query bl...
def Nu_cylinder_Zukauskas(Re, Pr, Prw=None): r'''Calculates Nusselt number for crossflow across a single tube at a specified Re. Method from [1]_, also shown without modification in [2]_. .. math:: Nu_{D}=CRe^{m}Pr^{n}\left(\frac{Pr}{Pr_s}\right)^{1/4} Parameters ---------- Re : float ...
r'''Calculates Nusselt number for crossflow across a single tube at a specified Re. Method from [1]_, also shown without modification in [2]_. .. math:: Nu_{D}=CRe^{m}Pr^{n}\left(\frac{Pr}{Pr_s}\right)^{1/4} Parameters ---------- Re : float Reynolds number with respect to cylinder ...
def sources(self): """ Returns a dictionary of source methods found on this object, keyed on method name. Source methods are identified by (self, context) arguments on this object. For example: .. code-block:: python def f(self, context): ... ...
Returns a dictionary of source methods found on this object, keyed on method name. Source methods are identified by (self, context) arguments on this object. For example: .. code-block:: python def f(self, context): ... is a source method, but ...
def variations(iterable, optional=lambda x: False): """ Returns all possible variations of a sequence with optional items. """ # For example: variations(["A?", "B?", "C"], optional=lambda s: s.endswith("?")) # defines a sequence where constraint A and B are optional: # [("A?", "B?", "C"), ("B?", "C"...
Returns all possible variations of a sequence with optional items.
def update_Broyden_J(self): """Execute a Broyden update of J""" CLOG.debug('Broyden update.') delta_vals = self.param_vals - self._last_vals delta_residuals = self.calc_residuals() - self._last_residuals nrm = np.sqrt(np.dot(delta_vals, delta_vals)) direction = delta_vals...
Execute a Broyden update of J
def start(self): """ Confirm that we may access the target cluster. """ version = self.request("get", "/version") if version != 2: raise GanetiApiError("Can't work with Ganeti RAPI version %d" % version) logging.info("Access...
Confirm that we may access the target cluster.