code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def assemble(input_): """ Assembles input string, and leave the result in the MEMORY global object """ global MEMORY if MEMORY is None: MEMORY = Memory() parser.parse(input_, lexer=LEXER, debug=OPTIONS.Debug.value > 2) if len(MEMORY.scopes): error(MEMORY.scopes[-1], 'Missin...
Assembles input string, and leave the result in the MEMORY global object
def next(self): """ Gets next entry as a dictionary. Returns: object - Object key/value pair representing a row. {key1: value1, key2: value2, ...} """ try: entry = {} row = self._csv_reader.next() for i in range(0, le...
Gets next entry as a dictionary. Returns: object - Object key/value pair representing a row. {key1: value1, key2: value2, ...}
def forum_list(context, forum_visibility_contents): """ Renders the considered forum list. This will render the given list of forums by respecting the order and the depth of each forum in the forums tree. Usage:: {% forum_list my_forums %} """ request = context.get('request') tra...
Renders the considered forum list. This will render the given list of forums by respecting the order and the depth of each forum in the forums tree. Usage:: {% forum_list my_forums %}
def to_aws_name(self, name): """ Returns a transliteration of the name that safe to use for resource names on AWS. If the given name is relative, it converted to its absolute form before the transliteration. The transliteration uses two consequitive '_' to encode a single '_' and a sing...
Returns a transliteration of the name that safe to use for resource names on AWS. If the given name is relative, it converted to its absolute form before the transliteration. The transliteration uses two consequitive '_' to encode a single '_' and a single '_' to separate the name components. A...
def stoichiometry_coefficients(compound, elements): """ Determine the stoichiometry coefficients of the specified elements in the specified chemical compound. :param compound: Formula of a chemical compound, e.g. 'SiO2'. :param elements: List of elements, e.g. ['Si', 'O', 'C']. :returns: List ...
Determine the stoichiometry coefficients of the specified elements in the specified chemical compound. :param compound: Formula of a chemical compound, e.g. 'SiO2'. :param elements: List of elements, e.g. ['Si', 'O', 'C']. :returns: List of stoichiometry coefficients.
def replace(self, html): """Perform replacements on given HTML fragment.""" self.html = html text = html.text() positions = [] def perform_replacement(match): offset = sum(positions) start, stop = match.start() + offset, match.end() + offset ...
Perform replacements on given HTML fragment.
def addGene( self, gene_id, gene_label, gene_type=None, gene_description=None ): ''' genes are classes ''' if gene_type is None: gene_type = self.globaltt['gene'] self.model.addClassToGraph(gene_id, gene_label, gene_type, gene_description) return
genes are classes
def main(): """ Continues to validate patterns until it encounters EOF within a pattern file or Ctrl-C is pressed by the user. """ parser = argparse.ArgumentParser(description='Validate STIX Patterns.') parser.add_argument('-f', '--file', help="Specify this arg to read pa...
Continues to validate patterns until it encounters EOF within a pattern file or Ctrl-C is pressed by the user.
def update(self, pid, session, **kwargs): '''taobao.fenxiao.product.update 更新产品 - 更新分销平台产品数据,不传更新数据返回失败 - 对sku进行增、删操作时,原有的sku_ids字段会被忽略,请使用sku_properties和sku_properties_del。''' request = TOPRequest('taobao.fenxiao.product.update') request['pid'] = pid for k, v in...
taobao.fenxiao.product.update 更新产品 - 更新分销平台产品数据,不传更新数据返回失败 - 对sku进行增、删操作时,原有的sku_ids字段会被忽略,请使用sku_properties和sku_properties_del。
def _do_setup(self): """Setup basic parameters for this class. `base` is the numeric base which when raised to `power` is equivalent to 1 unit of the corresponding prefix. I.e., base=2, power=10 represents 2^10, which is the NIST Binary Prefix for 1 Kibibyte. Likewise, for the SI prefix classes `base` will be...
Setup basic parameters for this class. `base` is the numeric base which when raised to `power` is equivalent to 1 unit of the corresponding prefix. I.e., base=2, power=10 represents 2^10, which is the NIST Binary Prefix for 1 Kibibyte. Likewise, for the SI prefix classes `base` will be 10, and the `power` for the Kil...
def many(cls, filter=None, **kwargs): """Return a list of documents matching the filter""" from mongoframes.queries import Condition, Group, to_refs # Flatten the projection kwargs['projection'], references, subs = \ cls._flatten_projection( kwargs.ge...
Return a list of documents matching the filter
def __ProcessHttpResponse(self, method_config, http_response, request): """Process the given http response.""" if http_response.status_code not in (http_client.OK, http_client.CREATED, http_client.NO_CONTENT): ...
Process the given http response.
def deltaW(N, m, h): """Generate sequence of Wiener increments for m independent Wiener processes W_j(t) j=0..m-1 for each of N time intervals of length h. Returns: dW (array of shape (N, m)): The [n, j] element has the value W_j((n+1)*h) - W_j(n*h) """ return np.random.normal(0.0,...
Generate sequence of Wiener increments for m independent Wiener processes W_j(t) j=0..m-1 for each of N time intervals of length h. Returns: dW (array of shape (N, m)): The [n, j] element has the value W_j((n+1)*h) - W_j(n*h)
def transitive_subgraph_of_addresses(self, addresses, *vargs, **kwargs): """Returns all transitive dependencies of `addresses`. Note that this uses `walk_transitive_dependencies_graph` and the predicate is passed through, hence it trims graphs rather than just filtering out Targets that do not match the pr...
Returns all transitive dependencies of `addresses`. Note that this uses `walk_transitive_dependencies_graph` and the predicate is passed through, hence it trims graphs rather than just filtering out Targets that do not match the predicate. See `walk_transitive_dependency_graph for more detail on `predicate...
def _bit_is_one(self, n, hash_bytes): """ Check if the n (index) of hash_bytes is 1 or 0. """ scale = 16 # hexadecimal if not hash_bytes[int(n / (scale / 2))] >> int( (scale / 2) - ((n % (scale / 2)) + 1)) & 1 == 1: return False return True
Check if the n (index) of hash_bytes is 1 or 0.
def validate( message, get_certificate=lambda url: urlopen(url).read(), certificate_url_regex=DEFAULT_CERTIFICATE_URL_REGEX, max_age=DEFAULT_MAX_AGE ): """ Validate a decoded SNS message. Parameters: message: Decoded SNS message. get_certificate: Fun...
Validate a decoded SNS message. Parameters: message: Decoded SNS message. get_certificate: Function that receives a URL, and returns the certificate from that URL as a string. The default doesn't implement caching. certificate_url_regex: Reg...
def handleButtonClick(self, button): """ Handles the button click for this widget. If the Reset button was clicked, then the resetRequested signal will be emitted. All buttons will emit the buttonClicked signal. :param button | <QAbstractButton> """...
Handles the button click for this widget. If the Reset button was clicked, then the resetRequested signal will be emitted. All buttons will emit the buttonClicked signal. :param button | <QAbstractButton>
def add_package_origins(self, modpath): """Whenever you 'import a.b.c', Python automatically binds 'b' in a to the a.b module and binds 'c' in a.b to the a.b.c module.""" parts = modpath.split('.') parent = parts[0] for part in parts[1:]: child = parent + '.' + part ...
Whenever you 'import a.b.c', Python automatically binds 'b' in a to the a.b module and binds 'c' in a.b to the a.b.c module.
def bm3_g(p, v0, g0, g0p, k0, k0p): """ calculate shear modulus at given pressure. not fully tested with mdaap. :param p: pressure :param v0: volume at reference condition :param g0: shear modulus at reference condition :param g0p: pressure derivative of shear modulus at reference condition...
calculate shear modulus at given pressure. not fully tested with mdaap. :param p: pressure :param v0: volume at reference condition :param g0: shear modulus at reference condition :param g0p: pressure derivative of shear modulus at reference condition :param k0: bulk modulus at reference condit...
def get_feed_list(opml_obj: OPML) -> List[str]: """Walk an OPML document to extract the list of feed it contains.""" rv = list() def collect(obj): for outline in obj.outlines: if outline.type == 'rss' and outline.xml_url: rv.append(outline.xml_url) if outlin...
Walk an OPML document to extract the list of feed it contains.
def QA_indicator_DMI(DataFrame, M1=14, M2=6): """ 趋向指标 DMI """ HIGH = DataFrame.high LOW = DataFrame.low CLOSE = DataFrame.close OPEN = DataFrame.open TR = SUM(MAX(MAX(HIGH-LOW, ABS(HIGH-REF(CLOSE, 1))), ABS(LOW-REF(CLOSE, 1))), M1) HD = HIGH-REF(HIGH, 1) LD = R...
趋向指标 DMI
def letternum(letter): """ Get The Number Corresponding To A Letter """ if not isinstance(letter, str): raise TypeError("Invalid letter provided.") if not len(letter) == 1: raise ValueError("Invalid letter length provided.") letter = letter.lower() alphaletters = string.ascii...
Get The Number Corresponding To A Letter
def stringpatterns(table, field): """ Profile string patterns in the given field, returning a table of patterns, counts and frequencies. E.g.:: >>> import petl as etl >>> table = [['foo', 'bar'], ... ['Mr. Foo', '123-1254'], ... ['Mrs. Bar', '234-1123'], ...
Profile string patterns in the given field, returning a table of patterns, counts and frequencies. E.g.:: >>> import petl as etl >>> table = [['foo', 'bar'], ... ['Mr. Foo', '123-1254'], ... ['Mrs. Bar', '234-1123'], ... ['Mr. Spo', '123-1254'], ...
def return_port(port): """Return a port that is no longer being used so it can be reused.""" if port in _random_ports: _random_ports.remove(port) elif port in _owned_ports: _owned_ports.remove(port) _free_ports.add(port) elif port in _free_ports: logging.info("Returning a...
Return a port that is no longer being used so it can be reused.
def delete_credential(self, identifier, credential_id=None): """Delete the object storage credential. :param int id: The object storage account identifier. :param int credential_id: The credential id to be deleted. """ credential = { 'id': credential_id } ...
Delete the object storage credential. :param int id: The object storage account identifier. :param int credential_id: The credential id to be deleted.
def extract_data(self): """Extracts data from archive. Returns: PackageData object containing the extracted data. """ data = PackageData( local_file=self.local_file, name=self.name, pkg_name=self.rpm_name or self.name_convertor.rpm_name( ...
Extracts data from archive. Returns: PackageData object containing the extracted data.
def import_committees(src): """ Read the committees from the csv files into a single Dataframe. Intended for importing new data. """ committees = [] subcommittees = [] with open("{0}/{1}/committees-current.yaml".format(src, LEGISLATOR_DIR), 'r') as stream: committees += ya...
Read the committees from the csv files into a single Dataframe. Intended for importing new data.
def to_uint(self): """Convert vector to an unsigned integer, if possible. This is only useful for arrays filled with zero/one entries. """ num = 0 for i, f in enumerate(self._items): if f.is_zero(): pass elif f.is_one(): nu...
Convert vector to an unsigned integer, if possible. This is only useful for arrays filled with zero/one entries.
def _connect(self): """Connect to PostgreSQL, either by reusing a connection from the pool if possible, or by creating the new connection. :rtype: psycopg2.extensions.connection :raises: pool.NoIdleConnectionsError """ future = concurrent.Future() # Attempt to ...
Connect to PostgreSQL, either by reusing a connection from the pool if possible, or by creating the new connection. :rtype: psycopg2.extensions.connection :raises: pool.NoIdleConnectionsError
def finish(self): """ Creates block of content with lines belonging to fragment. """ self.lines.reverse() self._content = '\n'.join(self.lines) self.lines = None
Creates block of content with lines belonging to fragment.
def _map_arg(arg): """ Return `arg` appropriately parsed or mapped to a usable value. """ # Grab the easy to parse values if isinstance(arg, _ast.Str): return repr(arg.s) elif isinstance(arg, _ast.Num): return arg.n elif isinstance(arg, _ast.Name): name = arg.id ...
Return `arg` appropriately parsed or mapped to a usable value.
def closest_point(mesh, points): """ Given a mesh and a list of points, find the closest point on any triangle. Parameters ---------- mesh : Trimesh object points : (m,3) float, points in space Returns ---------- closest : (m,3) float, closest point on triangles for each po...
Given a mesh and a list of points, find the closest point on any triangle. Parameters ---------- mesh : Trimesh object points : (m,3) float, points in space Returns ---------- closest : (m,3) float, closest point on triangles for each point distance : (m,) float, distance ...
async def start(self): """ This method opens an IP connection on the IP device :return: None """ try: self.reader, self.writer = await asyncio.open_connection( self.ip_address, self.port, loop=self.loop) except OSError: print("Can'...
This method opens an IP connection on the IP device :return: None
def resolvefaults(self, definitions, op): """ Resolve soap fault I{message} references by cross-referencing with operation defined in port type. @param definitions: A definitions object. @type definitions: L{Definitions} @param op: An I{operation} object. @type op...
Resolve soap fault I{message} references by cross-referencing with operation defined in port type. @param definitions: A definitions object. @type definitions: L{Definitions} @param op: An I{operation} object. @type op: I{operation}
def _source_is_newer(src_fs, src_path, dst_fs, dst_path): # type: (FS, Text, FS, Text) -> bool """Determine if source file is newer than destination file. Arguments: src_fs (FS): Source filesystem (instance or URL). src_path (str): Path to a file on the source filesystem. dst_fs (FS...
Determine if source file is newer than destination file. Arguments: src_fs (FS): Source filesystem (instance or URL). src_path (str): Path to a file on the source filesystem. dst_fs (FS): Destination filesystem (instance or URL). dst_path (str): Path to a file on the destination fil...
def forwardSlash(listOfFiles): """convert silly C:\\names\\like\\this.txt to c:/names/like/this.txt""" for i,fname in enumerate(listOfFiles): listOfFiles[i]=fname.replace("\\","/") return listOfFiles
convert silly C:\\names\\like\\this.txt to c:/names/like/this.txt
def eval_advs(self, x, y, preds_adv, X_test, Y_test, att_type): """ Evaluate the accuracy of the model on adversarial examples :param x: symbolic input to model. :param y: symbolic variable for the label. :param preds_adv: symbolic variable for the prediction on an adversarial...
Evaluate the accuracy of the model on adversarial examples :param x: symbolic input to model. :param y: symbolic variable for the label. :param preds_adv: symbolic variable for the prediction on an adversarial example. :param X_test: NumPy array of test set inputs. :param Y_te...
def mzminus(df, minus=0, noise=10000): """ The abundances of ions which are minus below the molecular ion. """ mol_ions = ((df.values > noise) * df.columns).max(axis=1) - minus mol_ions[np.abs(mol_ions) < 0] = 0 d = np.abs(np.ones(df.shape) * df.columns - (mol_ions[np.newaxis].T *...
The abundances of ions which are minus below the molecular ion.
def raise_http_error(cls, response): """Raise a `ResponseError` of the appropriate subclass in reaction to the given `http_client.HTTPResponse`.""" response_xml = response.read() logging.getLogger('recurly.http.response').debug(response_xml) exc_class = recurly.errors.error_class...
Raise a `ResponseError` of the appropriate subclass in reaction to the given `http_client.HTTPResponse`.
def daemonize_posix(self): """ do the UNIX double-fork magic, see Stevens' "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 """ logger.info('daemonize_posix') try: pid =...
do the UNIX double-fork magic, see Stevens' "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
def to_utf8(text): """ Enforce UTF8 encoding. """ # return empty/false stuff unaltered if not text: if isinstance(text, string_types): text = "" return text try: # Is it a unicode string, or pure ascii? return text.encode("utf8") except UnicodeDecodeE...
Enforce UTF8 encoding.
def setattr_context(obj, **kwargs): """ Context manager to temporarily change the values of object attributes while executing a function. Example ------- >>> class Foo: pass >>> f = Foo(); f.attr = 'hello' >>> with setattr_context(f, attr='goodbye'): ... print(f.attr) goodby...
Context manager to temporarily change the values of object attributes while executing a function. Example ------- >>> class Foo: pass >>> f = Foo(); f.attr = 'hello' >>> with setattr_context(f, attr='goodbye'): ... print(f.attr) goodbye >>> print(f.attr) hello
def commit( self, message: str, files_to_add: typing.Optional[typing.Union[typing.List[str], str]] = None, allow_empty: bool = False, ): """ Commits changes to the repo :param message: first line of the message :type message: str ...
Commits changes to the repo :param message: first line of the message :type message: str :param files_to_add: files to commit :type files_to_add: optional list of str :param allow_empty: allow dummy commit :type allow_empty: bool
def load_prefix(s3_loc, success_only=None, recent_versions=None, exclude_regex=None, just_sql=False): """Get a bash command which will load every dataset in a bucket at a prefix. For this to work, all datasets must be of the form `s3://$BUCKET_NAME/$PREFIX/$DATASET_NAME/v$VERSION/$PARTITIONS`. Any other fo...
Get a bash command which will load every dataset in a bucket at a prefix. For this to work, all datasets must be of the form `s3://$BUCKET_NAME/$PREFIX/$DATASET_NAME/v$VERSION/$PARTITIONS`. Any other formats will be ignored. :param bucket_name :param prefix
def decipher(self,string): """Decipher string using Delastelle cipher according to initialised key. Example:: plaintext = Delastelle('APCZ WRLFBDKOTYUQGENHXMIVS').decipher(ciphertext) :param string: The string to decipher. :returns: The deciphered string. The plaintex...
Decipher string using Delastelle cipher according to initialised key. Example:: plaintext = Delastelle('APCZ WRLFBDKOTYUQGENHXMIVS').decipher(ciphertext) :param string: The string to decipher. :returns: The deciphered string. The plaintext will be 1/3 the length of the cipher...
def generate_random_perovskite(lat=None): ''' This generates a random valid perovskite structure in ASE format. Useful for testing. Binary and organic perovskites are not considered. ''' if not lat: lat = round(random.uniform(3.5, Perovskite_tilting.OCTAHEDRON_BOND_LENGTH_LIMIT*2), 3) ...
This generates a random valid perovskite structure in ASE format. Useful for testing. Binary and organic perovskites are not considered.
def check_grad(f_df, xref, stepsize=1e-6, tol=1e-6, width=15, style='round', out=sys.stdout): """ Compares the numerical gradient to the analytic gradient Parameters ---------- f_df : function The analytic objective and gradient function to check x0 : array_like Parameter value...
Compares the numerical gradient to the analytic gradient Parameters ---------- f_df : function The analytic objective and gradient function to check x0 : array_like Parameter values to check the gradient at stepsize : float, optional Stepsize for the numerical gradient. To...
def _match_real(filename, include, exclude, follow, symlinks): """Match real filename includes and excludes.""" sep = '\\' if util.platform() == "windows" else '/' if isinstance(filename, bytes): sep = os.fsencode(sep) if not filename.endswith(sep) and os.path.isdir(filename): filename ...
Match real filename includes and excludes.
def cublasSsyr2(handle, uplo, n, alpha, x, incx, y, incy, A, lda): """ Rank-2 operation on real symmetric matrix. """ status = _libcublas.cublasSsyr2_v2(handle, _CUBLAS_FILL_MODE[uplo], n, ctypes.byref(ctypes.c_float(alpha)...
Rank-2 operation on real symmetric matrix.
def update_resource_assignments(self, id_or_uri, resource_assignments, timeout=-1): """ Modifies scope membership by adding or removing resource assignments. Args: id_or_uri: Can be either the resource ID or the resource URI. resource_assignments (dict): ...
Modifies scope membership by adding or removing resource assignments. Args: id_or_uri: Can be either the resource ID or the resource URI. resource_assignments (dict): A dict object with a list of resource URIs to be added and a list of resource URIs to be removed. ...
def get_pyxb(self): """Generate a DataONE Exception PyXB object. The PyXB object supports directly reading and writing the individual values that may be included in a DataONE Exception. """ dataone_exception_pyxb = dataoneErrors.error() dataone_exception_pyxb.name = sel...
Generate a DataONE Exception PyXB object. The PyXB object supports directly reading and writing the individual values that may be included in a DataONE Exception.
def _run_cmd(self, command): """ Run a DQL command """ if self.throttle: tables = self.engine.describe_all(False) limiter = self.throttle.get_limiter(tables) else: limiter = None self.engine.rate_limit = limiter results = self.engine.execute(co...
Run a DQL command
def normalize(url, strip=False): "RFC3986 normalize URL & Optionally removing url-query/fragment string" if strip: p = _urltools.parse(url) url = p.scheme + '://' + p.subdomain + p.domain + p.path return _urltools.normalize(url)
RFC3986 normalize URL & Optionally removing url-query/fragment string
def configure_specials_key(self, keyboard): """Configures specials key if needed. :param keyboard: Keyboard instance this layout belong. """ special_row = VKeyRow() max_length = self.max_length i = len(self.rows) - 1 current_row = self.rows[i] special_key...
Configures specials key if needed. :param keyboard: Keyboard instance this layout belong.
def unget_service(self, reference): # type: (ServiceReference) -> bool """ Disables a reference to the service :return: True if the bundle was using this reference, else False """ # Lose the dependency return self.__framework._registry.unget_service( ...
Disables a reference to the service :return: True if the bundle was using this reference, else False
def _normalize_lang_attrs(self, text, strip): """Remove embedded bracketed attributes. This (potentially) bitwise-ands bracketed attributes together and adds to the end. This is applied to a single alternative at a time -- not to a parenthesized list. It removes all embe...
Remove embedded bracketed attributes. This (potentially) bitwise-ands bracketed attributes together and adds to the end. This is applied to a single alternative at a time -- not to a parenthesized list. It removes all embedded bracketed attributes, logically-ands them to...
def _CheckGitkitError(self, raw_response): """Raises error if API invocation failed. Args: raw_response: string, the http response. Raises: GitkitClientError: if the error code is 4xx. GitkitServerError: if the response if malformed. Returns: Successful response as dict. "...
Raises error if API invocation failed. Args: raw_response: string, the http response. Raises: GitkitClientError: if the error code is 4xx. GitkitServerError: if the response if malformed. Returns: Successful response as dict.
def unprotect_response(self, response, **kwargs): """ Removes protection from the specified response :param request: response from the key vault service :return: unprotected response with any security protocal encryption removed """ body = response.content # if th...
Removes protection from the specified response :param request: response from the key vault service :return: unprotected response with any security protocal encryption removed
def write_recording(recording, save_path): ''' Save recording extractor to MEArec format. Parameters ---------- recording: RecordingExtractor Recording extractor object to be saved save_path: str .h5 or .hdf5 path ''' assert HAVE_MR...
Save recording extractor to MEArec format. Parameters ---------- recording: RecordingExtractor Recording extractor object to be saved save_path: str .h5 or .hdf5 path
def record_evaluation(eval_result): """Create a callback that records the evaluation history into ``eval_result``. Parameters ---------- eval_result : dict A dictionary to store the evaluation results. Returns ------- callback : function The callback that records the evaluat...
Create a callback that records the evaluation history into ``eval_result``. Parameters ---------- eval_result : dict A dictionary to store the evaluation results. Returns ------- callback : function The callback that records the evaluation history into the passed dictionary.
def resizeEvent( self, event ): """ Resizes the current widget and its parts widget. :param event | <QResizeEvent> """ super(XNavigationEdit, self).resizeEvent(event) w = self.width() h = self.height() self._scrollWidget.res...
Resizes the current widget and its parts widget. :param event | <QResizeEvent>
def _save_pys(self, filepath): """Saves file as pys file and returns True if save success Parameters ---------- filepath: String \tTarget file path for xls file """ try: with Bz2AOpen(filepath, "wb", main_window=self.main_...
Saves file as pys file and returns True if save success Parameters ---------- filepath: String \tTarget file path for xls file
def accept(self, message=None, expires_at=None): """Accept request.""" with db.session.begin_nested(): if self.status != RequestStatus.PENDING: raise InvalidRequestStateError(RequestStatus.PENDING) self.status = RequestStatus.ACCEPTED request_accepted.send...
Accept request.
def dict_merge(a, b, path=None): """merges b into a""" return dict_selective_merge(a, b, b.keys(), path)
merges b into a
def iter_query_indexes(self): """ Iterator that constructs :class:`~dql.models.QueryIndex` for all global and local indexes, and a special one for the default table hash & range key with the name 'TABLE' """ if self._table.range_key is None: range_key = None ...
Iterator that constructs :class:`~dql.models.QueryIndex` for all global and local indexes, and a special one for the default table hash & range key with the name 'TABLE'
def settings(self): """ Resturns the account settings data for this acocunt. This is not a listing endpoint. """ result = self.client.get('/account/settings') if not 'managed' in result: raise UnexpectedResponseError('Unexpected response when getting accoun...
Resturns the account settings data for this acocunt. This is not a listing endpoint.
def set_doc(self, doc: str): """Assign the given docstring to the property instance and, if possible, to the `__test__` dictionary of the module of its owner class.""" self.__doc__ = doc if hasattr(self, 'module'): ref = f'{self.objtype.__name__}.{self.name}' ...
Assign the given docstring to the property instance and, if possible, to the `__test__` dictionary of the module of its owner class.
def save_screenshot(driver, name): """ Save a screenshot of the browser. The location of the screenshot can be configured by the environment variable `SCREENSHOT_DIR`. If not set, this defaults to the current working directory. Args: driver (selenium.webdriver): The Selenium-controlle...
Save a screenshot of the browser. The location of the screenshot can be configured by the environment variable `SCREENSHOT_DIR`. If not set, this defaults to the current working directory. Args: driver (selenium.webdriver): The Selenium-controlled browser. name (str): A name for the s...
def dataframe(self): """ Returns a ``pandas DataFrame`` containing all other relevant class properties and values where each index is a different season plus the career stats. """ temp_index = self._index rows = [] indices = [] if not self._season:...
Returns a ``pandas DataFrame`` containing all other relevant class properties and values where each index is a different season plus the career stats.
def build_result(data): """Create a dictionary with the contents of result.json""" more = {} for key, value in data.items(): if key != 'elements': newnode = value else: newnode = {} for el in value: nkey, nvalue = process_node(el) ...
Create a dictionary with the contents of result.json
def cache_clear(self): """Clear local cache by deleting all cached resources and their downloaded files. """ # Delete content of local cache directory for f in os.listdir(self.directory): f = os.path.join(self.directory, f) if os.path.isfile(f): ...
Clear local cache by deleting all cached resources and their downloaded files.
def read_cifar10(filename_queue): """Reads and parses examples from CIFAR10 data files. Recommendation: if you want N-way read parallelism, call this function N times. This will give you N independent Readers reading different files & positions within those files, which will give better mixing of examples. ...
Reads and parses examples from CIFAR10 data files. Recommendation: if you want N-way read parallelism, call this function N times. This will give you N independent Readers reading different files & positions within those files, which will give better mixing of examples. Args: filename_queue: A queue of...
def create_group(self, attrs, members, folder_id=None, tags=None): """Create a contact group XML example : <cn l="7> ## ContactSpec <a n="lastName">MARTIN</a> <a n="firstName">Pierre</a> <a n="email">pmartin@example.com</a> </cn> Which would b...
Create a contact group XML example : <cn l="7> ## ContactSpec <a n="lastName">MARTIN</a> <a n="firstName">Pierre</a> <a n="email">pmartin@example.com</a> </cn> Which would be in zimsoap : attrs = { 'lastname': 'MARTIN', ...
def to_dict(self): """ Return the task context content as a dictionary. """ return { 'task_name': self.task_name, 'dag_name': self.dag_name, 'workflow_name': self.workflow_name, 'workflow_id': self.workflow_id, 'worker_hostname': self.worker_ho...
Return the task context content as a dictionary.
def _find_pair(self, protocol, remote_candidate): """ Find a candidate pair in the check list. """ for pair in self._check_list: if (pair.protocol == protocol and pair.remote_candidate == remote_candidate): return pair return None
Find a candidate pair in the check list.
def copytree(source_directory, destination_directory, ignore=None): """ Recursively copy the contents of a source directory into a destination directory. Both directories must exist. This function does not copy the root directory ``source_directory`` into ``destination_directory``. Since `...
Recursively copy the contents of a source directory into a destination directory. Both directories must exist. This function does not copy the root directory ``source_directory`` into ``destination_directory``. Since ``shutil.copytree(src, dst)`` requires ``dst`` not to exist, we cannot use fo...
def _calculate(cls): """ Calculate the percentage of each status. """ # We map the current state/counters of the different status. percentages = { "up": PyFunceble.INTERN["counter"]["number"]["up"], "down": PyFunceble.INTERN["counter"]["number"]["down"], ...
Calculate the percentage of each status.
def _get_paging_controls(request): """Parses start and/or limit queries into a paging controls dict. """ start = request.url.query.get('start', None) limit = request.url.query.get('limit', None) controls = {} if limit is not None: try: control...
Parses start and/or limit queries into a paging controls dict.
def _check_raising_stopiteration_in_generator_next_call(self, node): """Check if a StopIteration exception is raised by the call to next function If the next value has a default value, then do not add message. :param node: Check to see if this Call node is a next function :type node: :...
Check if a StopIteration exception is raised by the call to next function If the next value has a default value, then do not add message. :param node: Check to see if this Call node is a next function :type node: :class:`astroid.node_classes.Call`
def is_open(location, now=None): """ Is the company currently open? Pass "now" to test with a specific timestamp. Can be used stand-alone or as a helper. """ if now is None: now = get_now() if has_closing_rule_for_now(location): return False now_time = datetime.time(now.hou...
Is the company currently open? Pass "now" to test with a specific timestamp. Can be used stand-alone or as a helper.
def _add_request_parameters(func): """Adds the ratelimit and request timeout parameters to a function.""" # The function the decorator returns async def decorated_func(*args, handle_ratelimit=None, max_tries=None, request_timeout=None, **kwargs): return await func(*args, handle_rate...
Adds the ratelimit and request timeout parameters to a function.
def reduce_annotations(self, annotations, options): """Reduce annotations to ones used to identify enrichment (normally exclude ND and NOT).""" getfnc_qual_ev = options.getfnc_qual_ev() return [nt for nt in annotations if getfnc_qual_ev(nt.Qualifier, nt.Evidence_Code)]
Reduce annotations to ones used to identify enrichment (normally exclude ND and NOT).
def load_obj(self, jref, getter=None, parser=None): """ load a object(those in spec._version_.objects) from a JSON reference. """ obj = self.__resolver.resolve(jref, getter) # get root document to check its swagger version. tmp = {'_tmp_': {}} version = utils.get_swagger...
load a object(those in spec._version_.objects) from a JSON reference.
def process_alias_create_namespace(namespace): """ Validate input arguments when the user invokes 'az alias create'. Args: namespace: argparse namespace object. """ namespace = filter_alias_create_namespace(namespace) _validate_alias_name(namespace.alias_name) _validate_alias_comman...
Validate input arguments when the user invokes 'az alias create'. Args: namespace: argparse namespace object.
def verify(self): """Raise an |ValueError| if the dates or the step size of the time frame are inconsistent. """ if self.firstdate >= self.lastdate: raise ValueError( f'Unplausible timegrid. The first given date ' f'{self.firstdate}, the second...
Raise an |ValueError| if the dates or the step size of the time frame are inconsistent.
def set_entry(self, filename, obj): """ Set the entry. """ self.entries[filename] = obj self.dirty = True
Set the entry.
def add(self, event, pk, ts=None, ttl=None): """Add an event to event store. All events were stored in a sorted set in redis with timestamp as rank score. :param event: the event to be added, format should be ``table_action`` :param pk: the primary key of event :param ...
Add an event to event store. All events were stored in a sorted set in redis with timestamp as rank score. :param event: the event to be added, format should be ``table_action`` :param pk: the primary key of event :param ts: timestamp of the event, default to redis_server's ...
def estimator_cov(self,method): """ Creates covariance matrix for the estimators Parameters ---------- method : str Estimation method Returns ---------- A Covariance Matrix """ Y = np.array([reg[self.lags:] for reg i...
Creates covariance matrix for the estimators Parameters ---------- method : str Estimation method Returns ---------- A Covariance Matrix
def group_info(name): ''' .. versionadded:: 2016.11.0 Lists all packages in the specified group CLI Example: .. code-block:: bash salt '*' pkg.group_info 'xorg' ''' pkgtypes = ('mandatory', 'optional', 'default', 'conditional') ret = {} for pkgtype in pkgtypes: r...
.. versionadded:: 2016.11.0 Lists all packages in the specified group CLI Example: .. code-block:: bash salt '*' pkg.group_info 'xorg'
def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } ...
Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below
def x_axis_properties(self, title_size=None, title_offset=None, label_angle=None, label_align=None, color=None): """Change x-axis title font size and label angle Parameters ---------- title_size: int, default None Title size, in px title_off...
Change x-axis title font size and label angle Parameters ---------- title_size: int, default None Title size, in px title_offset: int, default None Pixel offset from given axis label_angle: int, default None label angle in degrees labe...
def to_deeper_graph(graph): ''' deeper graph ''' weighted_layer_ids = graph.deep_layer_ids() if len(weighted_layer_ids) >= Constant.MAX_LAYERS: return None deeper_layer_ids = sample(weighted_layer_ids, 1) for layer_id in deeper_layer_ids: layer = graph.layer_list[layer_id] ...
deeper graph
def subscribe(self): """ Subscribe to contact and conversation events. These are accessible through :meth:`getEvents`. """ self.conn("POST", "{0}/users/ME/endpoints/{1}/subscriptions".format(self.conn.msgsHost, self.id), auth=SkypeConnection.Auth.RegToken, ...
Subscribe to contact and conversation events. These are accessible through :meth:`getEvents`.
def get_resource_children(raml_resource): """ Get children of :raml_resource:. :param raml_resource: Instance of ramlfications.raml.ResourceNode. """ path = raml_resource.path return [res for res in raml_resource.root.resources if res.parent and res.parent.path == path]
Get children of :raml_resource:. :param raml_resource: Instance of ramlfications.raml.ResourceNode.
def get(self, sent_id, **kwargs): ''' If sent_id exists, remove and return the associated sentence object else return default. If no default is provided, KeyError will be raised.''' if sent_id is not None and not isinstance(sent_id, int): sent_id = int(sent_id) if sent_id is ...
If sent_id exists, remove and return the associated sentence object else return default. If no default is provided, KeyError will be raised.
def record(self): # type: () -> bytes ''' Record this Extended Attribute Record. Parameters: None. Returns: A string representing this Extended Attribute Record. ''' if not self._initialized: raise pycdlibexception.PyCdlibInternalErr...
Record this Extended Attribute Record. Parameters: None. Returns: A string representing this Extended Attribute Record.
def supported_auth_methods(self) -> List[str]: """ Get all AUTH methods supported by the both server and by us. """ return [auth for auth in self.AUTH_METHODS if auth in self.server_auth_methods]
Get all AUTH methods supported by the both server and by us.
def _get_all_eip_addresses(addresses=None, allocation_ids=None, region=None, key=None, keyid=None, profile=None): ''' Get all EIP's associated with the current credentials. addresses (list) - Optional list of addresses. If provided, only those those in the list w...
Get all EIP's associated with the current credentials. addresses (list) - Optional list of addresses. If provided, only those those in the list will be returned. allocation_ids (list) - Optional list of allocation IDs. If provided, only the addresses associated with the given ...
def set_simple_fault_geometry_3D(w, src): """ Builds a 3D polygon from a node instance """ assert "simpleFaultSource" in src.tag geometry_node = src.nodes[get_taglist(src).index("simpleFaultGeometry")] fault_attrs = parse_simple_fault_geometry(geometry_node) build_polygon_from_fault_attrs(w,...
Builds a 3D polygon from a node instance
def _extract_nn_info(self, structure, nns): """Given Voronoi NNs, extract the NN info in the form needed by NearestNeighbors Args: structure (Structure): Structure being evaluated nns ([dicts]): Nearest neighbor information for a structure Returns: (list of t...
Given Voronoi NNs, extract the NN info in the form needed by NearestNeighbors Args: structure (Structure): Structure being evaluated nns ([dicts]): Nearest neighbor information for a structure Returns: (list of tuples (Site, array, float)): See nn_info