code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def parse_table_row(self, markup, row): """ Parses a row of cells in a Wikipedia table. Cells in the row are separated by "||". A "!" indicates a row of heading columns. Each cell can contain properties before a "|", # e.g. align="right" | Cell 2 (right aligned). ...
Parses a row of cells in a Wikipedia table. Cells in the row are separated by "||". A "!" indicates a row of heading columns. Each cell can contain properties before a "|", # e.g. align="right" | Cell 2 (right aligned).
def on_session_end(self, session): """Triggered by the given session object when the session is about to close normally. in session of type :class:`ISession` Session that is being closed return progress of type :class:`IProgress` Used to wait until the correspon...
Triggered by the given session object when the session is about to close normally. in session of type :class:`ISession` Session that is being closed return progress of type :class:`IProgress` Used to wait until the corresponding machine is actually dissociat...
def td_taper(out, start, end, beta=8, side='left'): """Applies a taper to the given TimeSeries. A half-kaiser window is used for the roll-off. Parameters ---------- out : TimeSeries The ``TimeSeries`` to taper. start : float The time (in s) to start the taper window. end :...
Applies a taper to the given TimeSeries. A half-kaiser window is used for the roll-off. Parameters ---------- out : TimeSeries The ``TimeSeries`` to taper. start : float The time (in s) to start the taper window. end : float The time (in s) to end the taper window. ...
def hide_arp_holder_arp_entry_interfacetype_Port_channel_Port_channel(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hide_arp_holder = ET.SubElement(config, "hide-arp-holder", xmlns="urn:brocade.com:mgmt:brocade-arp") arp_entry = ET.SubElement(hide_arp_...
Auto Generated Code
def slice_graph(graph, node, frontier, include_frontier=False): """ Generate a slice of the graph from the head node to the given frontier. :param networkx.DiGraph graph: The graph to work on. :param node: The starting node in the graph. :param frontier: A list of frontier nodes...
Generate a slice of the graph from the head node to the given frontier. :param networkx.DiGraph graph: The graph to work on. :param node: The starting node in the graph. :param frontier: A list of frontier nodes. :param bool include_frontier: Whether the frontier nodes are included in t...
def output_summary(self, output_stream=sys.stdout): """outputs a usage tip and the list of acceptable commands. This is useful as the output of the 'help' option. parameters: output_stream - an open file-like object suitable for use as the target of a pri...
outputs a usage tip and the list of acceptable commands. This is useful as the output of the 'help' option. parameters: output_stream - an open file-like object suitable for use as the target of a print function
def assign(name, value): ''' Assign a single sysctl parameter for this minion CLI Example: .. code-block:: bash salt '*' sysctl.assign net.inet.icmp.icmplim 50 ''' ret = {} cmd = 'sysctl {0}="{1}"'.format(name, value) data = __salt__['cmd.run_all'](cmd, python_shell=False) ...
Assign a single sysctl parameter for this minion CLI Example: .. code-block:: bash salt '*' sysctl.assign net.inet.icmp.icmplim 50
def substructure(self, atoms, meta=False, as_view=True): """ create substructure containing atoms from nbunch list :param atoms: list of atoms numbers of substructure :param meta: if True metadata will be copied to substructure :param as_view: If True, the returned graph-view pr...
create substructure containing atoms from nbunch list :param atoms: list of atoms numbers of substructure :param meta: if True metadata will be copied to substructure :param as_view: If True, the returned graph-view provides a read-only view of the original structure scaffold withou...
def playerJoin(config, agentCallBack, lobbyTimeout=c.INITIAL_TIMEOUT, debug=True): """cause an agent to join an already hosted game""" FLAGS(sys.argv) # ignore pysc2 command-line handling (eww) log = protocol.logging.logging log.disable(log.CRITICAL) # disable pysc2 logging amHosting = not bool(co...
cause an agent to join an already hosted game
def format_h1(s, format="text", indents=0): """ Encloses string in format text Args: s: string format: string starting with "text", "markdown", or "rest" indents: number of leading intenting spaces Returns: list >>> print("\\n".join(format_h2("Header 1", indents...
Encloses string in format text Args: s: string format: string starting with "text", "markdown", or "rest" indents: number of leading intenting spaces Returns: list >>> print("\\n".join(format_h2("Header 1", indents=10))) Header 1 -------- ...
def join_ops(ops1, ops2): """For internal use.""" i = len(ops1) - 1 j = 0 while i >= 0 and j < len(ops2): if ops1[i] == ops2[j]: i -= 1 j += 1 else: break return ops1[:i + 1] + ops2[j:]
For internal use.
def get_bound(pts): """Compute a minimal rectangle that covers all the points.""" (x0, y0, x1, y1) = (INF, INF, -INF, -INF) for (x, y) in pts: x0 = min(x0, x) y0 = min(y0, y) x1 = max(x1, x) y1 = max(y1, y) return (x0, y0, x1, y1)
Compute a minimal rectangle that covers all the points.
def location_id(self, location_id): """ Sets the location_id of this Order. The ID of the merchant location this order is associated with. :param location_id: The location_id of this Order. :type: str """ if location_id is None: raise ValueError("Inv...
Sets the location_id of this Order. The ID of the merchant location this order is associated with. :param location_id: The location_id of this Order. :type: str
def status(self, return_json=False): """ Describe the status of the current deployment. """ def tabular_print(title, value): """ Convenience function for priting formatted table items. """ click.echo('%-*s%s' % (32, click.style("\t" + titl...
Describe the status of the current deployment.
def _nodeSetValuesFromDict(self, dct): """ Sets values from a dictionary in the current node. Non-recursive auxiliary function for setValuesFromDict """ if 'data' in dct: qFont = QtGui.QFont() success = qFont.fromString(dct['data']) if not success:...
Sets values from a dictionary in the current node. Non-recursive auxiliary function for setValuesFromDict
def _process_all(self, limit): """ This takes the list of omim identifiers from the omim.txt.Z file, and iteratively queries the omim api for the json-formatted data. This will create OMIM classes, with the label, definition, and some synonyms. If an entry is "removed", ...
This takes the list of omim identifiers from the omim.txt.Z file, and iteratively queries the omim api for the json-formatted data. This will create OMIM classes, with the label, definition, and some synonyms. If an entry is "removed", it is added as a deprecated class. ...
def can_invite_others(self, user): """Determine if user can invite people to a group. Be aware that this check is independent from the people (users) which are going to be invited. The checked user is the one who invites someone, NOT who is going to be invited. :param user: Use...
Determine if user can invite people to a group. Be aware that this check is independent from the people (users) which are going to be invited. The checked user is the one who invites someone, NOT who is going to be invited. :param user: User to be checked. :returns: True or Fal...
def generate_content_media_type(self): """ Means loading value when it's specified as JSON. .. code-block:: python { 'contentMediaType': 'application/json', } """ if self._definition['contentMediaType'] == 'application/json': ...
Means loading value when it's specified as JSON. .. code-block:: python { 'contentMediaType': 'application/json', }
def init_weights(self, w, n=-1): """ This function initialises the adaptive weights of the filter. **Args:** * `w` : initial weights of filter. Possible values are: * array with initial weights (1 dimensional array) of filter size * "random" : ...
This function initialises the adaptive weights of the filter. **Args:** * `w` : initial weights of filter. Possible values are: * array with initial weights (1 dimensional array) of filter size * "random" : create random weights * "zer...
def maxCtxContextualSubtable(maxCtx, st, ruleType, chain=''): """Calculate usMaxContext based on a contextual feature subtable.""" if st.Format == 1: for ruleset in getattr(st, '%s%sRuleSet' % (chain, ruleType)): if ruleset is None: continue for rule in getattr(r...
Calculate usMaxContext based on a contextual feature subtable.
def normalize(W, copy=True): ''' Normalizes an input weighted connection matrix. If copy is not set, this function will *modify W in place.* Parameters ---------- W : np.ndarray weighted connectivity matrix copy : bool if True, returns a copy of the matrix. Otherwise, modif...
Normalizes an input weighted connection matrix. If copy is not set, this function will *modify W in place.* Parameters ---------- W : np.ndarray weighted connectivity matrix copy : bool if True, returns a copy of the matrix. Otherwise, modifies the matrix in place. Default ...
def _to_rest_includes(models, includes): """ Fetch the models to be included The includes should follow a few basic rules: * the include MUST not already be an array member of the included array (no dupes) * the include MUST not be the same as the primary data if the prima...
Fetch the models to be included The includes should follow a few basic rules: * the include MUST not already be an array member of the included array (no dupes) * the include MUST not be the same as the primary data if the primary data is a single resource object (no...
def split_params(sym, params): """Helper function to split params dictionary into args and aux params Parameters ---------- sym : :class:`~mxnet.symbol.Symbol` MXNet symbol object params : dict of ``str`` to :class:`~mxnet.ndarray.NDArray` Dict of convert...
Helper function to split params dictionary into args and aux params Parameters ---------- sym : :class:`~mxnet.symbol.Symbol` MXNet symbol object params : dict of ``str`` to :class:`~mxnet.ndarray.NDArray` Dict of converted parameters stored in ``mxnet.ndarray.ND...
def to_unicode_optional_iterator(x): """ Raise TypeError if x is a str containing non-utf8 bytes or if x is an iterable which contains such a str. """ if isinstance(x, STRING_TYPES): return to_unicode(x) try: l = list(x) except TypeError as e: assert 'is not iterable...
Raise TypeError if x is a str containing non-utf8 bytes or if x is an iterable which contains such a str.
def create(self, data): """Create a new component """ response = self.http.post(str(self), json=data, auth=self.auth) response.raise_for_status() return response.json()
Create a new component
def top(self, objects: Set[Object]) -> Set[Object]: """ Return the topmost objects (i.e. minimum y_loc). The comparison is done separately for each box. """ objects_per_box = self._separate_objects_by_boxes(objects) return_set: Set[Object] = set() for _, box_objec...
Return the topmost objects (i.e. minimum y_loc). The comparison is done separately for each box.
def token(self): '''Attempt to return the auth header token. :return: token related to request ''' auth_header = self.headers.get('Authorization', '') if 'Token ' in auth_header: return auth_header.partition('Token ')[-1] else: return auth_header
Attempt to return the auth header token. :return: token related to request
def watch(self, key, pipeline=False): """Watch the given key. Marks the given key to be watch for conditional execution of a transaction. Args: key (str): Key that needs to be watched pipeline (bool): True, start a transaction block. Default false. """ ...
Watch the given key. Marks the given key to be watch for conditional execution of a transaction. Args: key (str): Key that needs to be watched pipeline (bool): True, start a transaction block. Default false.
def _py_ex_argtype(executable): """Returns the code to create the argtype to assign to the methods argtypes attribute. """ result = [] for p in executable.ordered_parameters: atypes = p.argtypes if atypes is not None: result.extend(p.argtypes) else: pr...
Returns the code to create the argtype to assign to the methods argtypes attribute.
def p_expression_uxnor(self, p): 'expression : XNOR expression %prec UXNOR' p[0] = Uxnor(p[2], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
expression : XNOR expression %prec UXNOR
def bundle_stylesheets(context: Context): """ Compiles stylesheets """ args = [ '--output', context.app.scss_build_path, '--output-style', 'compressed', ] if context.verbosity == 0: args.append('--quiet') if not context.use_colour: args.append('--no-color') ...
Compiles stylesheets
def Run(self, unused_args): """Does the segfaulting.""" if flags.FLAGS.pdb_post_mortem: logging.warning("Segfault action requested :(") print(ctypes.cast(1, ctypes.POINTER(ctypes.c_void_p)).contents) else: logging.warning("Segfault requested but not running in debug mode.")
Does the segfaulting.
def run_training(sub_id: int, run_seed: int, run_options, process_queue): """ Launches training session. :param process_queue: Queue used to send signal back to main. :param sub_id: Unique id for training session. :param run_seed: Random seed used for training. :param run_options: Command line a...
Launches training session. :param process_queue: Queue used to send signal back to main. :param sub_id: Unique id for training session. :param run_seed: Random seed used for training. :param run_options: Command line arguments for training.
def transcodeImage(self, media, height, width, opacity=100, saturation=100): """ Returns the URL for a transcoded image from the specified media object. Returns None if no media specified (needed if user tries to pass thumb or art directly). Parameters: heigh...
Returns the URL for a transcoded image from the specified media object. Returns None if no media specified (needed if user tries to pass thumb or art directly). Parameters: height (int): Height to transcode the image to. width (int): Width to transcod...
def get_episode_ids(self, show_id, season): """Get episode ids from the show id and the season. :param int show_id: show id. :param int season: season of the episode. :return: episode ids per episode number. :rtype: dict """ # get the page of the season of the s...
Get episode ids from the show id and the season. :param int show_id: show id. :param int season: season of the episode. :return: episode ids per episode number. :rtype: dict
def get_pk_value_on_save(self, instance): """Generate ID if required.""" value = super(AleaIdField, self).get_pk_value_on_save(instance) if not value: value = self.get_seeded_value(instance) return value
Generate ID if required.
def bpp2newick(bppnewick): "converts bpp newick format to normal newick" regex1 = re.compile(r" #[-+]?[0-9]*\.?[0-9]*[:]") regex2 = re.compile(r" #[-+]?[0-9]*\.?[0-9]*[;]") regex3 = re.compile(r": ") new = regex1.sub(":", bppnewick) new = regex2.sub(";", new) new = regex3.sub(":", new) r...
converts bpp newick format to normal newick
def get_nendo (): """今は何年度?""" y, m = map(int, time.strftime("%Y %m").split()) return y if m >= 4 else y - 1
今は何年度?
def needs_fixing(raw_params, kwargs_default=_kwargs_default_name): u""" Returns string with the name of the kwargs dict if the params after the first star need fixing Otherwise returns empty string """ found_kwargs = False needs_fix = False for t in raw_params[2:]: if t.type == toke...
u""" Returns string with the name of the kwargs dict if the params after the first star need fixing Otherwise returns empty string
def rsa_decrypt_base64_encoded_key(rsaprivatekey, enckey): # type: (cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey, # str) -> bytes """Decrypt an RSA encrypted key encoded as base64 :param rsaprivatekey: RSA private key :type rsaprivatekey: cryptography.hazmat.primitives....
Decrypt an RSA encrypted key encoded as base64 :param rsaprivatekey: RSA private key :type rsaprivatekey: cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey :param str enckey: base64-encoded key :rtype: bytes :return: decrypted key
def step2_exchange(self, code=None, http=None, device_flow_info=None): """Exchanges a code for OAuth2Credentials. Args: code: string, a dict-like object, or None. For a non-device flow, this is either the response code as a string, or a dictionary of quer...
Exchanges a code for OAuth2Credentials. Args: code: string, a dict-like object, or None. For a non-device flow, this is either the response code as a string, or a dictionary of query parameters to the redirect_uri. For a device flow, this should...
def update(self, docs=None, split=0, parallelism=None, progress_bar=True): """Update the features of the specified candidates. :param docs: If provided, apply features to all the candidates in these documents. :param split: If docs is None, apply features to the candidates in this ...
Update the features of the specified candidates. :param docs: If provided, apply features to all the candidates in these documents. :param split: If docs is None, apply features to the candidates in this particular split. :type split: int :param parallelism: How ...
def urlencode_utf8(params): """ UTF-8 safe variant of urllib.urlencode. http://stackoverflow.com/a/8152242 """ if hasattr(params, 'items'): params = params.items() params = ( '='.join(( quote_plus(k.encode('utf8'), safe='/'), quote_plus(v.encode('utf8'), s...
UTF-8 safe variant of urllib.urlencode. http://stackoverflow.com/a/8152242
def create_parser(subparsers): """ create parser """ metrics_parser = subparsers.add_parser( 'metrics', help='Display info of a topology\'s metrics', usage="%(prog)s cluster/[role]/[env] topology-name [options]", add_help=False) args.add_cluster_role_env(metrics_parser) args.add_topology...
create parser
def after(self, i, sibling, name=None): """Adds siblings after the current tag.""" self.parent._insert(sibling, idx=self._own_index + 1 + i, name=name) return self
Adds siblings after the current tag.
def entropy(data=None, prob=None, tol=1e-5): ''' given a probability distribution (prob) or an interable of symbols (data) compute and return its entropy inputs: ------ data: iterable of symbols prob: iterable with probabilities tol: if prob is given, 'e...
given a probability distribution (prob) or an interable of symbols (data) compute and return its entropy inputs: ------ data: iterable of symbols prob: iterable with probabilities tol: if prob is given, 'entropy' checks that the sum is about 1. ...
def install(self, name=None, prefix=None, pkgs=None, dep=True, channels=None, token=None): """ Install a set of packages into an environment by name or path. If token is specified, the channels different from the defaults will get the token appended. """ ...
Install a set of packages into an environment by name or path. If token is specified, the channels different from the defaults will get the token appended.
def _create_class(rule, index): # type: (Type[Rule], int) -> Type[SplitRule] """ Create subtype of SplitRule based on rule. :param rule: Rule from which the SplitRule derive. :param index: Index of the rule (in original Rule class) to use for SplitRule. :return: Class inh...
Create subtype of SplitRule based on rule. :param rule: Rule from which the SplitRule derive. :param index: Index of the rule (in original Rule class) to use for SplitRule. :return: Class inherited from SplitRule representing rule at index.
def _allocate_address_neutron(self, instance, network_ids): """ Allocates a floating/public ip address to the given instance, using the OpenStack Network ('Neutron') API. :param instance: instance to assign address to :param list network_id: List of IDs (as strings) of...
Allocates a floating/public ip address to the given instance, using the OpenStack Network ('Neutron') API. :param instance: instance to assign address to :param list network_id: List of IDs (as strings) of networks where to request allocation the floating IP. :retur...
def delete(self, force=False): """ Deletes this hosted zone. After this method is ran, you won't be able to add records, or do anything else with the zone. You'd need to re-create it, as zones are read-only after creation. :keyword bool force: If ``True``, delete the ...
Deletes this hosted zone. After this method is ran, you won't be able to add records, or do anything else with the zone. You'd need to re-create it, as zones are read-only after creation. :keyword bool force: If ``True``, delete the :py:class:`HostedZone <route53.hosted_zone.HostedZ...
def com_google_fonts_check_metadata_valid_post_script_name_values(font_metadata, font_familynames): """METADATA.pb font.post_script_name field contains font name in right format? """ for font_familyname in font_familynames: psname = "".joi...
METADATA.pb font.post_script_name field contains font name in right format?
def fromtif(path, ext='tif', start=None, stop=None, recursive=False, nplanes=None, npartitions=None, labels=None, engine=None, credentials=None, discard_extra=False): """ Loads images from single or multi-page TIF files. Parameters ---------- path : str Path to data files or directory, spec...
Loads images from single or multi-page TIF files. Parameters ---------- path : str Path to data files or directory, specified as either a local filesystem path or in a URI-like format, including scheme. May include a single '*' wildcard character. ext : string, optional, default = 'tif...
def add_environment(self, environment, sync=True): """ add an environment to this OS instance. :param environment: the environment to add on this OS instance :param sync: If sync=True(default) synchronize with Ariane server. If sync=False, add the environment object on list to be...
add an environment to this OS instance. :param environment: the environment to add on this OS instance :param sync: If sync=True(default) synchronize with Ariane server. If sync=False, add the environment object on list to be added on next save(). :return:
def create_event(self, institute, case, user, link, category, verb, subject, level='specific', variant=None, content=None, panel=None): """Create a Event with the parameters given. Arguments: institute (dict): A institute case (dict): A ...
Create a Event with the parameters given. Arguments: institute (dict): A institute case (dict): A case user (dict): A User link (str): The url to be used in the event category (str): case or variant verb (str): What type of event ...
def random(self: 'ErrorValue') -> np.ndarray: """Sample a random number (array) of the distribution defined by mean=`self.val` and variance=`self.err`^2. """ if isinstance(self.val, np.ndarray): # IGNORE:E1103 return np.random.randn(self.val.shape) * self.err + se...
Sample a random number (array) of the distribution defined by mean=`self.val` and variance=`self.err`^2.
def get_gae_versions(): """Gets a list of all of the available Python SDK versions, sorted with the newest last.""" r = requests.get(SDK_RELEASES_URL) r.raise_for_status() releases = r.json().get('items', {}) # We only care about the Python releases, which all are in the format # "featured...
Gets a list of all of the available Python SDK versions, sorted with the newest last.
def parse_bytes(self, bytestr, isfinal=True): """ Parse a byte string. If the string is very large, split it in chuncks and parse each chunk with isfinal=False, then parse an empty chunk with isfinal=True. """ with self._context(): self.filename = None ...
Parse a byte string. If the string is very large, split it in chuncks and parse each chunk with isfinal=False, then parse an empty chunk with isfinal=True.
def _start_keep_alive(self): ''' Start the keep alive thread as a daemon ''' keep_alive_thread = threading.Thread(target=self.keep_alive) keep_alive_thread.daemon = True keep_alive_thread.start()
Start the keep alive thread as a daemon
def get(self, name: str) -> Union[None, str, List[str]]: """ 获取 header """ name = name.casefold() if name == "referer" or name == "referrer": if "referrer" in self._headers: return self._headers["referrer"] elif "referer" in self._headers: ...
获取 header
def onStart(self): """ Override onStart method for npyscreen """ curses.mousemask(0) self.paths.host_config() version = Version() # setup initial runtime stuff if self.first_time[0] and self.first_time[1] != 'exists': system = System() thr = Threa...
Override onStart method for npyscreen
def generic_commit_and_try_merge2master_wf(git_action, file_content, doc_id, auth_info, parent_sha, commi...
Actually make a local Git commit and push it to our remote
async def _build_state(self, request: Request, message: BaseMessage, responder: Responder) \ -> Tuple[ Optional[BaseState], Optional[BaseTrigger], Optional[bool], ]: ...
Build the state for this request.
def RawBytesToScriptHash(raw): """ Get a hash of the provided raw bytes using the ripemd160 algorithm. Args: raw (bytes): byte array of raw bytes. e.g. b'\xAA\xBB\xCC' Returns: UInt160: """ rawh = binascii.unhexlify(raw) rawhashstr = bina...
Get a hash of the provided raw bytes using the ripemd160 algorithm. Args: raw (bytes): byte array of raw bytes. e.g. b'\xAA\xBB\xCC' Returns: UInt160:
def make_contiguous(im, keep_zeros=True): r""" Take an image with arbitrary greyscale values and adjust them to ensure all values fall in a contiguous range starting at 0. This function will handle negative numbers such that most negative number will become 0, *unless* ``keep_zeros`` is ``True`` in...
r""" Take an image with arbitrary greyscale values and adjust them to ensure all values fall in a contiguous range starting at 0. This function will handle negative numbers such that most negative number will become 0, *unless* ``keep_zeros`` is ``True`` in which case it will become 1, and all 0's ...
def rgb_to_yiq(r, g=None, b=None): """Convert the color from RGB to YIQ. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (y, i, q) tuple in the range: y[0...1], i[0...1],...
Convert the color from RGB to YIQ. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (y, i, q) tuple in the range: y[0...1], i[0...1], q[0...1] >>> '(%g, %g, %g)' % rg...
def get_nonparametric_sources(self): """ :returns: list of non parametric sources in the composite source model """ return [src for sm in self.source_models for src_group in sm.src_groups for src in src_group if hasattr(src, 'data')]
:returns: list of non parametric sources in the composite source model
def K_r2(self, r2): """ Returns the kernel evaluated on `r2`, which is the scaled squared distance. Will call self.K_r(r=sqrt(r2)), or can be overwritten directly (and should operate element-wise on r2). """ r = self._clipped_sqrt(r2) return self.K_r(r)
Returns the kernel evaluated on `r2`, which is the scaled squared distance. Will call self.K_r(r=sqrt(r2)), or can be overwritten directly (and should operate element-wise on r2).
def _db_pre_transform(self, train_tfm:List[Callable], valid_tfm:List[Callable]): "Call `train_tfm` and `valid_tfm` after opening image, before converting from `PIL.Image`" self.train_ds.x.after_open = compose(train_tfm) self.valid_ds.x.after_open = compose(valid_tfm) return self
Call `train_tfm` and `valid_tfm` after opening image, before converting from `PIL.Image`
def list(ctx, scenario_name, format): # pragma: no cover """ Lists status of instances. """ args = ctx.obj.get('args') subcommand = base._get_subcommand(__name__) command_args = { 'subcommand': subcommand, 'format': format, } statuses = [] s = scenarios.Scenarios( b...
Lists status of instances.
def is_git_file(cls, path, name): """Determine if file is known by git.""" os.chdir(path) p = subprocess.Popen(['git', 'ls-files', '--error-unmatch', name], stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.wait() return p.returncode == 0
Determine if file is known by git.
def _kill(self, variable, code_loc): # pylint:disable=no-self-use """ Kill previous defs. addr_list is a list of normalized addresses. """ # Case 1: address perfectly match, we kill # Case 2: a is a subset of the original address # Case 3: a is a superset of the origina...
Kill previous defs. addr_list is a list of normalized addresses.
def remove(name=None, pkgs=None, **kwargs): ''' Remove specified package. Accepts full or partial FMRI. In case of multiple match, the command fails and won't modify the OS. name The name of the package to be deleted. Multiple Package Options: pkgs A list of packages to delet...
Remove specified package. Accepts full or partial FMRI. In case of multiple match, the command fails and won't modify the OS. name The name of the package to be deleted. Multiple Package Options: pkgs A list of packages to delete. Must be passed as a python list. The ``name``...
def _gql(cls, query_string, *args, **kwds): """Run a GQL query.""" from .query import gql # Import late to avoid circular imports. return gql('SELECT * FROM %s %s' % (cls._class_name(), query_string), *args, **kwds)
Run a GQL query.
def identify_ibids(line): """Find IBIDs within the line, record their position and length, and replace them with underscores. @param line: (string) the working reference line @return: (tuple) containing 2 dictionaries and a string: Dictionary: matched IBID text: (Key: position of IBI...
Find IBIDs within the line, record their position and length, and replace them with underscores. @param line: (string) the working reference line @return: (tuple) containing 2 dictionaries and a string: Dictionary: matched IBID text: (Key: position of IBID in line;...
def _format_name(self, name, surname, snake_case=False): """Format a first name and a surname into a cohesive string. Note that either name or surname can be empty strings, and formatting will still succeed. :param str name: A first name. :param str surname: A surname. ...
Format a first name and a surname into a cohesive string. Note that either name or surname can be empty strings, and formatting will still succeed. :param str name: A first name. :param str surname: A surname. :param bool snake_case: If True, format the name as "sna...
def expr_stmt(self, lhs, rhs): """ (2.6, 2.7, 3.0, 3.1) expr_stmt: testlist (augassign (yield_expr|testlist) | ('=' (yield_expr|testlist))*) (3.2-) expr_stmt: testlist_star_expr (augassign (yield_expr|testlist) | ('=' (yie...
(2.6, 2.7, 3.0, 3.1) expr_stmt: testlist (augassign (yield_expr|testlist) | ('=' (yield_expr|testlist))*) (3.2-) expr_stmt: testlist_star_expr (augassign (yield_expr|testlist) | ('=' (yield_expr|testlist_star_expr))*)
def add(self, resource, replace=False): """Add just a single resource.""" uri = resource.uri if (uri in self and not replace): raise ResourceListDupeError( "Attempt to add resource already in resource_list") self[uri] = resource
Add just a single resource.
def parse_mbox(filepath): """Parse a mbox file. This method parses a mbox file and returns an iterator of dictionaries. Each one of this contains an email message. :param filepath: path of the mbox to parse :returns : generator of messages; each message is stored in a ...
Parse a mbox file. This method parses a mbox file and returns an iterator of dictionaries. Each one of this contains an email message. :param filepath: path of the mbox to parse :returns : generator of messages; each message is stored in a dictionary of type `requests.stru...
def find_shadowed(self, extra=()): """Find all the shadowed names. extra is an iterable of variables that may be defined with `add_special` which may occour scoped. """ i = self.identifiers return (i.declared | i.outer_undeclared) & \ (i.declared_locally | i.decla...
Find all the shadowed names. extra is an iterable of variables that may be defined with `add_special` which may occour scoped.
def addFileAnnot(self, point, buffer, filename, ufilename=None, desc=None): """Add a 'FileAttachment' annotation at location 'point'.""" CheckParent(self) val = _fitz.Page_addFileAnnot(self, point, buffer, filename, ufilename, desc) if not val: return val.thisown = True ...
Add a 'FileAttachment' annotation at location 'point'.
def is_filtered(self, require=None, ignore=None): """Return ``True`` for filtered calls :param iterable ignore: if set, the filters to ignore, make sure to include 'PASS', when setting, default is ``['PASS']`` :param iterable require: if set, the filters to require for returning ...
Return ``True`` for filtered calls :param iterable ignore: if set, the filters to ignore, make sure to include 'PASS', when setting, default is ``['PASS']`` :param iterable require: if set, the filters to require for returning ``True``
def td_tr(points, dist_threshold): """ Top-Down Time-Ratio Trajectory Compression Algorithm Detailed in https://www.itc.nl/library/Papers_2003/peer_ref_conf/meratnia_new.pdf Args: points (:obj:`list` of :obj:`Point`): trajectory or part of it dist_threshold (float): max distance error, in ...
Top-Down Time-Ratio Trajectory Compression Algorithm Detailed in https://www.itc.nl/library/Papers_2003/peer_ref_conf/meratnia_new.pdf Args: points (:obj:`list` of :obj:`Point`): trajectory or part of it dist_threshold (float): max distance error, in meters Returns: :obj:`list` of ...
def save(): """ save function """ results = {} cpu_number = 0 while True: try: _file = open( CPU_PREFIX + 'cpu{}/cpufreq/scaling_governor'.format(cpu_number)) except: break governor = _file.read().strip() results.setdefaul...
save function
def checkMultipleFiles(input): """ Evaluates the input to determine whether there is 1 or more than 1 valid input file. """ f,i,o,a=buildFileList(input) return len(f) > 1
Evaluates the input to determine whether there is 1 or more than 1 valid input file.
def get_activities(self): """Gets all ``Activities``. In plenary mode, the returned list contains all known activites or an error results. Otherwise, the returned list may contain only those activities that are accessible through this session. return: (osid.learning.ActivityLis...
Gets all ``Activities``. In plenary mode, the returned list contains all known activites or an error results. Otherwise, the returned list may contain only those activities that are accessible through this session. return: (osid.learning.ActivityList) - a ``ActivityList`` raise...
def handle_nextPageTemplate(self, pt): ''' if pt has also templates for even and odd page convert it to list ''' has_left_template = self._has_template_for_name(pt + '_left') has_right_template = self._has_template_for_name(pt + '_right') if has_left_template and has_rig...
if pt has also templates for even and odd page convert it to list
def compute_fw_at_frac_max_1d_simple(Y, xc, X=None, f=0.5): """Compute the full width at fraction f of the maximum""" yy = np.asarray(Y) if yy.ndim != 1: raise ValueError('array must be 1-d') if yy.size == 0: raise ValueError('array is empty') if X is None: xx = np.arange...
Compute the full width at fraction f of the maximum
def mapping_create(index, doc_type, body=None, hosts=None, profile=None, source=None): ''' Create a mapping in a given index index Index for the mapping doc_type Name of the document type body Mapping definition as specified in https://www.elastic.co/guide/en/elasticsearch/r...
Create a mapping in a given index index Index for the mapping doc_type Name of the document type body Mapping definition as specified in https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-put-mapping.html source URL to file specifying mapping definit...
def configure(cls, api_token, api_url="https://api.qubole.com/api/", version="v1.2", poll_interval=5, skip_ssl_cert_check=False, cloud_name="AWS"): """ Set parameters governing interaction with QDS Args: `api_token`: authorization token for QDS. r...
Set parameters governing interaction with QDS Args: `api_token`: authorization token for QDS. required `api_url`: the base URL for QDS API. configurable for testing only `version`: QDS REST api version. Will be used throughout unless overridden in Qubole.agent(..) ...
def set_parent(self, new_parent, init=False): "Associate the header to the control (it could be recreated)" self._created = False SubComponent.set_parent(self, new_parent, init) # if index not given, append the column at the last position: if self.index == -1 or self.index >...
Associate the header to the control (it could be recreated)
def get_order(membersuite_id, client=None): """Get an Order by ID. """ if not membersuite_id: return None client = client or get_new_client(request_session=True) if not client.session_id: client.request_session() object_query = "SELECT Object() FROM ORDER WHERE ID = '{}'".forma...
Get an Order by ID.
def setup_job(manager, job_id, tool_id, tool_version, use_metadata=False): """ Setup new job from these inputs and return dict summarizing state (used to configure command line). """ job_id = manager.setup_job(job_id, tool_id, tool_version) if use_metadata: manager.enable_metadata_directory(...
Setup new job from these inputs and return dict summarizing state (used to configure command line).
def filter_conflicts(conflicts_list, fields): """Use this function to automatically filter all the entries defined for a given rule. Params: conflicts_list(List[Conflict]): the list of conflicts to filter. fields(List[str]): fields to filter out, using an accessor syntax of the ...
Use this function to automatically filter all the entries defined for a given rule. Params: conflicts_list(List[Conflict]): the list of conflicts to filter. fields(List[str]): fields to filter out, using an accessor syntax of the form ``field.subfield.subsubfield``. Return: ...
def get_config_variable(self, config_id, offset): """Get a chunk of a config variable's value.""" config = self._config_variables.get(config_id) if config is None: return [b""] return [bytes(config.current_value[offset:offset + 20])]
Get a chunk of a config variable's value.
def build_reportnum_kb(fpath): """Given the path to a knowledge base file containing the details of institutes and the patterns that their preprint report numbering schemes take, create a dictionary of regexp search patterns to recognise these preprint references in reference lines, and ...
Given the path to a knowledge base file containing the details of institutes and the patterns that their preprint report numbering schemes take, create a dictionary of regexp search patterns to recognise these preprint references in reference lines, and a dictionary of replacements for non-s...
def _setup_regex(self): """Sets up the constant regex strings etc. that can be used to parse the strings for determining context.""" self.RE_COMMENTS = cache.RE_COMMENTS self.RE_MODULE = cache.RE_MODULE self.RE_TYPE = cache.RE_TYPE self.RE_EXEC = cache.RE_EXEC sel...
Sets up the constant regex strings etc. that can be used to parse the strings for determining context.
def _PopulateQuantilesHistogram(self, hist, nums): """Fills in the histogram with quantile information from the provided array. Args: hist: A Histogram proto message to fill in. nums: A list of numbers to create a quantiles histogram from. """ if not nums: return num_quantile_bucke...
Fills in the histogram with quantile information from the provided array. Args: hist: A Histogram proto message to fill in. nums: A list of numbers to create a quantiles histogram from.
def is_watching(self, username): """Check if user is being watched by the given user :param username: Check if username is watching you """ if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type...
Check if user is being watched by the given user :param username: Check if username is watching you
def with_connection(func): """Decorate a function to open a new datafind connection if required This method will inspect the ``connection`` keyword, and if `None` (or missing), will use the ``host`` and ``port`` keywords to open a new connection and pass it as ``connection=<new>`` to ``func``. """ ...
Decorate a function to open a new datafind connection if required This method will inspect the ``connection`` keyword, and if `None` (or missing), will use the ``host`` and ``port`` keywords to open a new connection and pass it as ``connection=<new>`` to ``func``.
def sha256sum(filename): """Return SHA256 hash of file.""" sha256 = hashlib.sha256() mem_view = memoryview(bytearray(128*1024)) with open(filename, 'rb', buffering=0) as stream: for i in iter(lambda: stream.readinto(mem_view), 0): sha256.update(mem_view[:i]) return sha256.hexdige...
Return SHA256 hash of file.