code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def add_pi_equation(self,par_names,pilbl=None,rhs=0.0,weight=1.0, obs_group="pi_obgnme",coef_dict={}): """ a helper to construct a new prior information equation. Parameters ---------- par_names : list parameter names in the equation pilbl : s...
a helper to construct a new prior information equation. Parameters ---------- par_names : list parameter names in the equation pilbl : str name to assign the prior information equation. If None, a generic equation name is formed. Default is None ...
def cache_id(self) -> str: """ Return identifier for archivable caches, computing it first and retaining it if need be. Raise AbsentPool if ledger configuration is not yet available. :param name: pool name :return: archivable cache identifier """ if self._cache_...
Return identifier for archivable caches, computing it first and retaining it if need be. Raise AbsentPool if ledger configuration is not yet available. :param name: pool name :return: archivable cache identifier
def xml(self): """ :rtype: str """ if six.PY3: data = ElementTree.tostring(self.et, encoding="unicode") else: data = ElementTree.tostring(self.et) return data
:rtype: str
def set_pixel(self, x, y, value): """Set pixel at position x, y to the given value. X and Y should be values of 0 to 7 and 0 to 15, resp. Value should be 0 for off and non-zero for on. """ if x < 0 or x > 7 or y < 0 or y > 15: # Ignore out of bounds pixels. retu...
Set pixel at position x, y to the given value. X and Y should be values of 0 to 7 and 0 to 15, resp. Value should be 0 for off and non-zero for on.
def toString(self): """ Returns the network layers as a string. """ output = "" for layer in reverse(self.layers): output += layer.toString() return output
Returns the network layers as a string.
def getreference(self, validate=True): """Return and validate the Phonetic Content's reference. Raises UnresolvableTextContent when invalid""" if self.offset is None: return None #nothing to test if self.ref: ref = self.doc[self.ref] else: ref = self.finddefaultr...
Return and validate the Phonetic Content's reference. Raises UnresolvableTextContent when invalid
def stSpectralEntropy(X, n_short_blocks=10): """Computes the spectral entropy""" L = len(X) # number of frame samples Eol = numpy.sum(X ** 2) # total spectral energy sub_win_len = int(numpy.floor(L / n_short_blocks)) # length of sub-frame if L != sub_win_len * n...
Computes the spectral entropy
def translate_item(self, item_dict): """cleanup item keys to match API json format""" if not item_dict.get('title'): return None # Skip attachments if item_dict.get('{wp}post_type', None) == 'attachment': return None ret_dict = {} # slugify post ti...
cleanup item keys to match API json format
def format_value(column_dict, value, key=None): """ Format a value coming from the database (for example converts datetimes to strings) :param column_dict: The column datas collected during inspection :param value: A value coming from the database :param key: The exportation key """ for...
Format a value coming from the database (for example converts datetimes to strings) :param column_dict: The column datas collected during inspection :param value: A value coming from the database :param key: The exportation key
def register_update(self, model_alias, code): """ Register tab update function, function is being called with (layout, object) :param model_alias: :param code: :return: """ model_alias = self.get_model_alias(model_alias) def wrapper(update_layout): ...
Register tab update function, function is being called with (layout, object) :param model_alias: :param code: :return:
def fcoe_fcoe_fabric_map_fcoe_fabric_map_fcmap(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fcoe = ET.SubElement(config, "fcoe", xmlns="urn:brocade.com:mgmt:brocade-fcoe") fcoe_fabric_map = ET.SubElement(fcoe, "fcoe-fabric-map") fcoe_fabric_ma...
Auto Generated Code
def get_batch(self): """ Returns a batch from the queue of augmented batches. If workers are still running and there are no batches in the queue, it will automatically wait for the next batch. Returns ------- out : None or imgaug.Batch One batch or N...
Returns a batch from the queue of augmented batches. If workers are still running and there are no batches in the queue, it will automatically wait for the next batch. Returns ------- out : None or imgaug.Batch One batch or None if all workers have finished.
def get_authorize_url(self, state=None): """ Gets the URL to use to authorize this app """ payload = {'client_id': self.client_id, 'response_type': 'code', 'redirect_uri': self.redirect_uri, 'scope': self.scope} urlparams = urllib...
Gets the URL to use to authorize this app
def bpoints2bezier(bpoints): """Converts a list of length 2, 3, or 4 to a CubicBezier, QuadraticBezier, or Line object, respectively. See also: poly2bez.""" order = len(bpoints) - 1 if order == 3: return CubicBezier(*bpoints) elif order == 2: return QuadraticBezier(*bpoints) ...
Converts a list of length 2, 3, or 4 to a CubicBezier, QuadraticBezier, or Line object, respectively. See also: poly2bez.
def nPr(n, r): """ Calculates nPr. Args: n (int): total number of items. r (int): items to permute Returns: nPr. """ f = math.factorial return int(f(n) / f(n-r))
Calculates nPr. Args: n (int): total number of items. r (int): items to permute Returns: nPr.
def getOverlayRenderingPid(self, ulOverlayHandle): """Gets the pid that is allowed to render to this overlay""" fn = self.function_table.getOverlayRenderingPid result = fn(ulOverlayHandle) return result
Gets the pid that is allowed to render to this overlay
def from_dict(cls, d): """ Create an instance from a dictionary. """ execution_request = super(ExecutionRequest, cls).from_dict(d) if isinstance(execution_request.simulation_group, dict): execution_request.simulation_group = SimulationGroup.from_dict(execution_request...
Create an instance from a dictionary.
def gauss_seidel(A, x, b, iterations=1, sweep='forward'): """Perform Gauss-Seidel iteration on the linear system Ax=b. Parameters ---------- A : csr_matrix, bsr_matrix Sparse NxN matrix x : ndarray Approximate solution (length N) b : ndarray Right-hand side (length N) ...
Perform Gauss-Seidel iteration on the linear system Ax=b. Parameters ---------- A : csr_matrix, bsr_matrix Sparse NxN matrix x : ndarray Approximate solution (length N) b : ndarray Right-hand side (length N) iterations : int Number of iterations to perform sw...
def polygon(self, *coords, color="black", outline=False, outline_color="black"): """ Draws a polygon from an list of co-ordinates :param int *coords: Pairs of x and y positions which make up the polygon. :param str color: The color of the shape. Defaults to `"bl...
Draws a polygon from an list of co-ordinates :param int *coords: Pairs of x and y positions which make up the polygon. :param str color: The color of the shape. Defaults to `"black"`. :param int outline: `0` or `False` is no outline. `True` or value > 1 set...
def parse_image_json(text): """ parses response output of AWS describe commands and returns the first (and only) item in array :param text: describe output :return: image json """ image_details = json.loads(text) if image_details.get('Images') is not None: try: image_deta...
parses response output of AWS describe commands and returns the first (and only) item in array :param text: describe output :return: image json
def _bracket_dim_suggest(self, variable): """Returns a dictionary of documentation for helping complete the dimensions of a variable.""" if variable is not None: #Look for <dimension> descriptors that are children of the variable #in its docstrings. dims = var...
Returns a dictionary of documentation for helping complete the dimensions of a variable.
def dropIndex(self, table, fields, where = '') : "DROPs an index created by RabaDb see createIndexes()" indexTable = self.makeIndexTableName(table, fields, where) self.dropIndexByName(indexTable)
DROPs an index created by RabaDb see createIndexes()
def _update_enabled(self, name, enabled_value): ''' Update whether an individual beacon is enabled ''' if isinstance(self.opts['beacons'][name], dict): # Backwards compatibility self.opts['beacons'][name]['enabled'] = enabled_value else: enabl...
Update whether an individual beacon is enabled
def neurite_root_section_ids(self): '''Get the section IDs of the intitial neurite sections''' sec = self.sections return [i for i, ss in enumerate(sec) if ss.pid > -1 and (sec[ss.pid].ntype == POINT_TYPE.SOMA and ss.ntype != POINT_TYPE.SOMA)]
Get the section IDs of the intitial neurite sections
def low(data, **kwargs): ''' Execute a single low data call This function is mostly intended for testing the state system CLI Example: .. code-block:: bash salt '*' state.low '{"state": "pkg", "fun": "installed", "name": "vi"}' ''' st_kwargs = __salt__.kwargs __opts__['grains'...
Execute a single low data call This function is mostly intended for testing the state system CLI Example: .. code-block:: bash salt '*' state.low '{"state": "pkg", "fun": "installed", "name": "vi"}'
def _citation_to_string(citation): """ Convert citation object to a string, using standard citation formatting. args: citation: a dictionary potentially containing all fields from pypif.obj.Reference, and possibly a few others TODO: This is tedious and fragile. Find a ...
Convert citation object to a string, using standard citation formatting. args: citation: a dictionary potentially containing all fields from pypif.obj.Reference, and possibly a few others TODO: This is tedious and fragile. Find a better way to get 'er done. TODO: This funct...
def create_markdown_cell(block): """Create a markdown cell from a block.""" kwargs = {'cell_type': block['type'], 'source': block['content']} markdown_cell = nbbase.new_markdown_cell(**kwargs) return markdown_cell
Create a markdown cell from a block.
def API_POST(self, courseid, taskid): # pylint: disable=arguments-differ """ Creates a new submissions. Takes as (POST) input the key of the subproblems, with the value assigned each time. Returns - an error 400 Bad Request if all the input is not (correctly) given, ...
Creates a new submissions. Takes as (POST) input the key of the subproblems, with the value assigned each time. Returns - an error 400 Bad Request if all the input is not (correctly) given, - an error 403 Forbidden if you are not allowed to create a new submission for this task ...
def deltas(self): """ Dictionary of relative offsets. The keys in the result are pairs of keys from the offset vector, (a, b), and the values are the relative offsets, (offset[b] - offset[a]). Raises ValueError if the offsetvector is empty (WARNING: this behaviour might change in the future). Example: ...
Dictionary of relative offsets. The keys in the result are pairs of keys from the offset vector, (a, b), and the values are the relative offsets, (offset[b] - offset[a]). Raises ValueError if the offsetvector is empty (WARNING: this behaviour might change in the future). Example: >>> x = offsetvector({"H...
def parse_division(l, c, line, root_node, last_section_node): """ Extracts a division node from a line :param l: The line number (starting from 0) :param c: The column number :param line: The line string (without indentation) :param root_node: The document root node. :return: tuple(last...
Extracts a division node from a line :param l: The line number (starting from 0) :param c: The column number :param line: The line string (without indentation) :param root_node: The document root node. :return: tuple(last_div_node, last_section_node)
def getVoxelsScalar(self, vmin=None, vmax=None): """ Return voxel content as a ``numpy.array``. :param float vmin: rescale scalar content to match `vmin` and `vmax` range. :param float vmax: rescale scalar content to match `vmin` and `vmax` range. """ n...
Return voxel content as a ``numpy.array``. :param float vmin: rescale scalar content to match `vmin` and `vmax` range. :param float vmax: rescale scalar content to match `vmin` and `vmax` range.
def parse_url(url): """Parses correctly url :param url: url to parse """ parsed = url if not url.startswith("http://") and not url.startswith( "https://"): # if url is like www.yahoo.com parsed = "http://" + parsed elif url.startswith("https...
Parses correctly url :param url: url to parse
def get_config(cls, key, default=None): """ Shortcut to access the application's config in your class :param key: The key to access :param default: The default value when None :returns mixed: """ return cls._app.config.get(key, default)
Shortcut to access the application's config in your class :param key: The key to access :param default: The default value when None :returns mixed:
def run(self, options): """ In general, you don't need to overwrite this method. :param options: :return: """ self.set_signal() self.check_exclusive_mode() slot = self.Handle(self) # start thread i = 0 while i < options.threads:...
In general, you don't need to overwrite this method. :param options: :return:
def plural(text): """ >>> plural('activity') 'activities' """ aberrant = { 'knife': 'knives', 'self': 'selves', 'elf': 'elves', 'life': 'lives', 'hoof': 'hooves', 'leaf': 'leaves', 'echo': 'echoes', 'embargo': 'embargoes', ...
>>> plural('activity') 'activities'
def write_job(self,fh): """ Write the DAG entry for this node's job to the DAG file descriptor. @param fh: descriptor of open DAG file. """ if isinstance(self.job(),CondorDAGManJob): # create an external subdag from this dag fh.write( ' '.join( ['SUBDAG EXTERNAL', self.__name, se...
Write the DAG entry for this node's job to the DAG file descriptor. @param fh: descriptor of open DAG file.
def _dict_refs(obj, named): '''Return key and value objects of a dict/proxy. ''' if named: for k, v in _items(obj): s = str(k) yield _NamedRef('[K] ' + s, k) yield _NamedRef('[V] ' + s + ': ' + _repr(v), v) else: for k, v in _items(obj): yi...
Return key and value objects of a dict/proxy.
def detect_anoms(data, k=0.49, alpha=0.05, num_obs_per_period=None, use_decomp=True, one_tail=True, upper_tail=True, verbose=False): """ # Detects anomalies in a time series using S-H-ESD. # # Args: # data: Time series to perform anomaly detection on. # k: Max...
# Detects anomalies in a time series using S-H-ESD. # # Args: # data: Time series to perform anomaly detection on. # k: Maximum number of anomalies that S-H-ESD will detect as a percentage of the data. # alpha: The level of statistical significance with which to accept or reject anomalies. # ...
def setComboValue(combo, value): """ Checks to see if there is a dataType custom property set to determine whether to return an integer or a string. :param combo | <QComboBox> :return <int> || <str> """ dataType = unwrapVariant(combo.property('dataType')) ...
Checks to see if there is a dataType custom property set to determine whether to return an integer or a string. :param combo | <QComboBox> :return <int> || <str>
def combining_setup(self): """ Setup for some special F2L cases. """ (slot_type, (corner_slot, edge_slot), (corner, edge)) = self.get_slot() cycle = ["FR", "RB", "BL", "LF"] if slot_type == "SLOTFREE": return ("FR", Formula(Step("y") * cycle.index(self.pair) o...
Setup for some special F2L cases.
def _add_arg_datasets(datasets, args): """Add data sets of the given args. :param datasets: The dict where to accumulate data sets. :type datasets: `dict` :param args: Tuple of unnamed data sets. :type args: `tuple` of varies """ for dataset in args: ...
Add data sets of the given args. :param datasets: The dict where to accumulate data sets. :type datasets: `dict` :param args: Tuple of unnamed data sets. :type args: `tuple` of varies
def draw_image(self, video_name, image_name, out, start, end, x, y, verbose=False): """ Draws an image over the video @param video_name : name of video input file @param image_name: name of image input file @param out : name of video output file @param ...
Draws an image over the video @param video_name : name of video input file @param image_name: name of image input file @param out : name of video output file @param start : when to start overlay @param end : when to end overlay @param x : x pos of image @param y :...
def train(input_dir, batch_size, max_steps, output_dir, checkpoint, cloud_train_config): """Train model in the cloud with CloudML trainer service.""" import google.datalab.ml as ml if checkpoint is None: checkpoint = _util._DEFAULT_CHECKPOINT_GSURL staging_package_url = _util.repackage_to_staging...
Train model in the cloud with CloudML trainer service.
def filter_pages(pages, pagenum, pagename): """ Choices pages by pagenum and pagename """ if pagenum: try: pages = [list(pages)[pagenum - 1]] except IndexError: raise IndexError('Invalid page number: %d' % pagenum) if pagename: pages = [page for page in pages...
Choices pages by pagenum and pagename
def _load_stopwords(file_path): ''' load stop words ''' global _stopwords if sys.version_info[0] < 3: words = open(file_path, 'r') else: words = open(file_path, 'r', encoding='utf-8') stopwords = words.readlines() for w in stopwords: _stopwords.add(any2unicode(w)....
load stop words
def task_search(self, task_str, **kwargs): """ Query for a subset of tasks by task_id. :param task_str: :return: """ self.prune() result = collections.defaultdict(dict) for task in self._state.get_active_tasks(): if task.id.find(task_str) != -...
Query for a subset of tasks by task_id. :param task_str: :return:
def load_model(): """ Load a n-gram language model for mathematics in ARPA format which gets shipped with hwrt. Returns ------- A NgramLanguageModel object """ logging.info("Load language model...") ngram_arpa_t = pkg_resources.resource_filename('hwrt', ...
Load a n-gram language model for mathematics in ARPA format which gets shipped with hwrt. Returns ------- A NgramLanguageModel object
def tab_navigate(self, delta=1): """Ctrl+Tab""" if delta > 0 and self.currentIndex() == self.count()-1: index = delta-1 elif delta < 0 and self.currentIndex() == 0: index = self.count()+delta else: index = self.currentIndex()+delta self...
Ctrl+Tab
def minify(compiled): """Perform basic minifications. Fails on non-tabideal indentation or a string with a #. """ compiled = compiled.strip() if compiled: out = [] for line in compiled.splitlines(): line = line.split("#", 1)[0].rstrip() if line: ...
Perform basic minifications. Fails on non-tabideal indentation or a string with a #.
def get_subassistants(self): """Return list of instantiated subassistants. Usually, this needs not be overriden in subclasses, you should just override get_subassistant_classes Returns: list of instantiated subassistants """ if not hasattr(self, '_subassista...
Return list of instantiated subassistants. Usually, this needs not be overriden in subclasses, you should just override get_subassistant_classes Returns: list of instantiated subassistants
def get_logger(name=None): ''' Get a logging handle. As with ``setup_logging``, a stream handler is added to the log handle. Arguments: name (str): Name of the log handle. Default is ``None``. ''' logger = logging.getLogger(name) if len(logger.handlers) == 0: logger = ...
Get a logging handle. As with ``setup_logging``, a stream handler is added to the log handle. Arguments: name (str): Name of the log handle. Default is ``None``.
def add_socket(self, socket): """ Add a socket to the multiplexer. :param socket: The socket. If it was added already, it won't be added a second time. """ if socket not in self._sockets: self._sockets.add(socket) socket.on_closed.connect(self...
Add a socket to the multiplexer. :param socket: The socket. If it was added already, it won't be added a second time.
def assert_matching_time_coord(arr1, arr2): """Check to see if two DataArrays have the same time coordinate. Parameters ---------- arr1 : DataArray or Dataset First DataArray or Dataset arr2 : DataArray or Dataset Second DataArray or Dataset Raises ------ ValueError ...
Check to see if two DataArrays have the same time coordinate. Parameters ---------- arr1 : DataArray or Dataset First DataArray or Dataset arr2 : DataArray or Dataset Second DataArray or Dataset Raises ------ ValueError If the time coordinates are not identical betw...
def set_data_location(self, current_extent, tag_location): # pylint: disable=unused-argument # type: (int, int) -> None ''' A method to set the new extent location that the data for this Directory Record should live at. Parameters: current_extent - The new extent. ...
A method to set the new extent location that the data for this Directory Record should live at. Parameters: current_extent - The new extent. Returns: Nothing.
def is_builtin_variable(id_node): # type: (Dict[str, Any]) -> bool """ Whether the specified node is a builtin identifier. """ # Builtin variables are always IDENTIFIER. if NodeType(id_node['type']) is not NodeType.IDENTIFIER: return False id_value = id_node['value'] if id_value.startswit...
Whether the specified node is a builtin identifier.
def from_dict(cls, dct, project=None, delim=' | '): r""" This method converts a correctly formatted dictionary into OpenPNM objects, and returns a handle to the *project* containing them. Parameters ---------- dct : dictionary The Python dictionary containing...
r""" This method converts a correctly formatted dictionary into OpenPNM objects, and returns a handle to the *project* containing them. Parameters ---------- dct : dictionary The Python dictionary containing the data. The nesting and labeling of the dict...
def get_event_times(self): """ Return event times of Fault, Breaker and other timed events Returns ------- list A sorted list of event times """ times = [] times.extend(self.Breaker.get_times()) for model in self.__dict__['Event'].al...
Return event times of Fault, Breaker and other timed events Returns ------- list A sorted list of event times
def custom_showwarning( message, category, filename="", lineno=-1, file=None, line=None ): """Hook to override default showwarning. https://stackoverflow.com/questions/2187269/python-print-only-the-message-on-warnings """ if file is None: file = sys.stderr if file is None: ...
Hook to override default showwarning. https://stackoverflow.com/questions/2187269/python-print-only-the-message-on-warnings
def insert_documents(self, documents, database_name=None, collection_name=None): """ Insert a list of new documents into an existing collection in the CosmosDB database. """ if documents is None: raise AirflowBadRequest("You cannot insert empty documents") created_do...
Insert a list of new documents into an existing collection in the CosmosDB database.
def _generate_lambda(self): """ Generate the lambda function and its IAM role, and add to self.tf_conf """ self.tf_conf['resource']['aws_lambda_function']['lambda_func'] = { 'filename': 'webhook2lambda2sqs_func.zip', 'function_name': self.resource_name, ...
Generate the lambda function and its IAM role, and add to self.tf_conf
def fetch(self, *args, **kwargs): """同步服务器的 Notification 数据 """ response = client.get('/tables/Notifications/{0}'.format(self.id)) self._update_data(response.json())
同步服务器的 Notification 数据
def handler(self, event): """Upper level handler of keyboard events.""" if self.escape(event): # A chance to escape self.stop() elif self.diagnostic: self._diagnostic(event) else: self._tap(event) #This is needed according to the pyHook tutor...
Upper level handler of keyboard events.
def _start_services(self, console_env): """Overrides superclass.""" self._ad.services.register('sl4a', sl4a_service.Sl4aService) console_env['s'] = self._ad.services.sl4a console_env['sl4a'] = self._ad.sl4a console_env['ed'] = self._ad.ed
Overrides superclass.
def jsonresolver_loader(url_map): """JSON resolver plugin that loads the schema endpoint. Injected into Invenio-Records JSON resolver. """ from flask import current_app from . import current_jsonschemas url_map.add(Rule( "{0}/<path:path>".format(current_app.config['JSONSCHEMAS_ENDPOINT'...
JSON resolver plugin that loads the schema endpoint. Injected into Invenio-Records JSON resolver.
def _linux_nqn(): ''' Return NVMe NQN from a Linux host. ''' ret = [] initiator = '/etc/nvme/hostnqn' try: with salt.utils.files.fopen(initiator, 'r') as _nvme: for line in _nvme: line = line.strip() if line.startswith('nqn.'): ...
Return NVMe NQN from a Linux host.
def rna_transcript_expression_dict_from_args(args): """ Returns a dictionary mapping Ensembl transcript IDs to FPKM expression values or None if neither Cufflinks tracking file nor StringTie GTF file were specified. """ if args.rna_transcript_fpkm_tracking_file: return load_cufflinks_fpk...
Returns a dictionary mapping Ensembl transcript IDs to FPKM expression values or None if neither Cufflinks tracking file nor StringTie GTF file were specified.
def get(self, name): """ Returns the struct, enum, or interface with the given name, or raises RpcException if no elements match that name. :Parameters: name Name of struct/enum/interface to return """ if self.structs.has_key(name): retu...
Returns the struct, enum, or interface with the given name, or raises RpcException if no elements match that name. :Parameters: name Name of struct/enum/interface to return
def to_python(self, data): """ Convert a data to python format. """ if data is None: return data if self.datatype: return self.datatype(data) else: return data
Convert a data to python format.
def delete_image(self, image_id): """ Removes only user created images. :param image_id: The unique ID of the image. :type image_id: ``str`` """ response = self._perform_request(url='/images/' + image_id, method='DELET...
Removes only user created images. :param image_id: The unique ID of the image. :type image_id: ``str``
def construct_api_url(api_url, **params): """Construct a Twitter API url, encoded, with parameters :param api_url: URL of the Twitter API endpoint you are attempting to construct :param \*\*params: Parameters that are accepted by Twitter for the endpoint you're requesting ...
Construct a Twitter API url, encoded, with parameters :param api_url: URL of the Twitter API endpoint you are attempting to construct :param \*\*params: Parameters that are accepted by Twitter for the endpoint you're requesting :rtype: string Usage:: >>> from...
def post(method, hmc, uri, uri_parms, body, logon_required, wait_for_completion): """Operation: Create Password Rule.""" assert wait_for_completion is True # synchronous operation try: console = hmc.consoles.lookup_by_oid(None) except KeyError: raise...
Operation: Create Password Rule.
def rename_fields(env, field_spec, no_deep=False): """Rename fields. Typically called in the pre script. WARNING: If using this on base module, pass the argument ``no_deep`` with True value for avoiding the using of the environment (which is not yet loaded). This, in contrast of ``rename_columns``, per...
Rename fields. Typically called in the pre script. WARNING: If using this on base module, pass the argument ``no_deep`` with True value for avoiding the using of the environment (which is not yet loaded). This, in contrast of ``rename_columns``, performs all the steps for completely rename a field from...
def get_machine_stats(self): ''' Gather spider based stats ''' self.logger.debug("Gathering machine stats") the_dict = {} keys = self.redis_conn.keys('stats:crawler:*:*:*:*') for key in keys: # break down key elements = key.split(":") ...
Gather spider based stats
def info_cmd(): """Print basic information about StagYY run.""" sdat = stagyydata.StagyyData(conf.core.path) lsnap = sdat.snaps.last lstep = sdat.steps.last print('StagYY run in {}'.format(sdat.path)) if lsnap.geom.threed: dimension = '{} x {} x {}'.format(lsnap.geom.nxtot, ...
Print basic information about StagYY run.
def euler_from_matrix(matrix, axes='sxyz'): """Return Euler angles from rotation matrix for specified axis sequence. axes : One of 24 axis sequences as string or encoded tuple Note that many Euler angle triplets can describe one matrix. >>> R0 = euler_matrix(1, 2, 3, 'syxz') >>> al, be, ga = eule...
Return Euler angles from rotation matrix for specified axis sequence. axes : One of 24 axis sequences as string or encoded tuple Note that many Euler angle triplets can describe one matrix. >>> R0 = euler_matrix(1, 2, 3, 'syxz') >>> al, be, ga = euler_from_matrix(R0, 'syxz') >>> R1 = euler_matrix...
def update_identities(self, identities): """UpdateIdentities. :param :class:`<VssJsonCollectionWrapper> <azure.devops.v5_0.identity.models.VssJsonCollectionWrapper>` identities: :rtype: [IdentityUpdateData] """ content = self._serialize.body(identities, 'VssJsonCollectionWrapper'...
UpdateIdentities. :param :class:`<VssJsonCollectionWrapper> <azure.devops.v5_0.identity.models.VssJsonCollectionWrapper>` identities: :rtype: [IdentityUpdateData]
def _get_required_args(fn): """Returns the distribution's required args.""" argspec = tf_inspect.getfullargspec(fn) args = argspec.args if tf_inspect.isclass(fn): args = args[1:] # Remove the `self` arg. if argspec.defaults: # Remove the args which have defaults. By convention we only feed # *req...
Returns the distribution's required args.
def print(self): """Print results table. >>> Results(['title'], [('Konosuba',), ('Oreimo',)]).print() # title --- -------- 1 Konosuba 2 Oreimo """ print(tabulate( ((i, *row) for i, row in enumerate(self.results, 1)), hea...
Print results table. >>> Results(['title'], [('Konosuba',), ('Oreimo',)]).print() # title --- -------- 1 Konosuba 2 Oreimo
def assign_highest_value(exposure, hazard): """Assign the highest hazard value to an indivisible feature. For indivisible polygon exposure layers such as buildings, we need to assigned the greatest hazard that each polygon touches and use that as the effective hazard class. Issue https://github.co...
Assign the highest hazard value to an indivisible feature. For indivisible polygon exposure layers such as buildings, we need to assigned the greatest hazard that each polygon touches and use that as the effective hazard class. Issue https://github.com/inasafe/inasafe/issues/3192 We follow the co...
def messages(self): '''A generator yielding the :class:`MacIndexMessage` structures in this index file.''' # The file contains the fixed-size file header followed by # fixed-size message structures, followed by minimal message # information (subject, from, to). Start after the ...
A generator yielding the :class:`MacIndexMessage` structures in this index file.
def get_pmg_structure(phonopy_structure): """ Convert a PhonopyAtoms object to pymatgen Structure object. Args: phonopy_structure (PhonopyAtoms): A phonopy structure object. """ lattice = phonopy_structure.get_cell() frac_coords = phonopy_structure.get_scaled_positions() symbols =...
Convert a PhonopyAtoms object to pymatgen Structure object. Args: phonopy_structure (PhonopyAtoms): A phonopy structure object.
def query_entities(self, table_name, filter=None, select=None, num_results=None, marker=None, accept=TablePayloadFormat.JSON_MINIMAL_METADATA, property_resolver=None, timeout=None): ''' Returns a generator to list the entities in the table specified. The ...
Returns a generator to list the entities in the table specified. The generator will lazily follow the continuation tokens returned by the service and stop when all entities have been returned or max_results is reached. If max_results is specified and the account has more than that nu...
async def _task(self): """ Main queue processor """ if self._handlers.values(): start_tasks = [h.start() for h in self._handlers.values()] await asyncio.wait(start_tasks, loop=self.loop) while self.running: if self.events: event, kwargs = awa...
Main queue processor
def add_tools(self, *tools): ''' Adds tools to the plot. Args: *tools (Tool) : the tools to add to the Plot Returns: None ''' for tool in tools: if not isinstance(tool, Tool): raise ValueError("All arguments to add_tool must ...
Adds tools to the plot. Args: *tools (Tool) : the tools to add to the Plot Returns: None
def validate(request: Union[Dict, List], schema: dict) -> Union[Dict, List]: """ Wraps jsonschema.validate, returning the same object passed in. Args: request: The deserialized-from-json request. schema: The jsonschema schema to validate against. Raises: jsonschema.ValidationEr...
Wraps jsonschema.validate, returning the same object passed in. Args: request: The deserialized-from-json request. schema: The jsonschema schema to validate against. Raises: jsonschema.ValidationError
def _write(self, stream, text, byte_order): ''' Write the data to a PLY file. ''' if text: self._write_txt(stream) else: if self._have_list: # There are list properties, so serialization is # slightly complicated. ...
Write the data to a PLY file.
def zip(self, enumerable, func): """ Merges 2 Enumerables using the given function. If the 2 collections are of unequal length, then merging continues until the end of one of the collections is reached :param enumerable: Enumerable collection to merge with :param func: a function...
Merges 2 Enumerables using the given function. If the 2 collections are of unequal length, then merging continues until the end of one of the collections is reached :param enumerable: Enumerable collection to merge with :param func: a function to perform the merging :return: Enumerable
def is_valid(self): """Test if the matrix is positive definite Hermitian. If the matrix decomposition is available, this test checks if all eigenvalues are positive. Otherwise, the test tries to calculate a Cholesky decomposition, which can be very time-consuming for large matri...
Test if the matrix is positive definite Hermitian. If the matrix decomposition is available, this test checks if all eigenvalues are positive. Otherwise, the test tries to calculate a Cholesky decomposition, which can be very time-consuming for large matrices. Sparse matrices ar...
def prepare(self): """Method to check if the impact function can be run. :return: A tuple with the status of the IF and an error message if needed. The status is PREPARE_SUCCESS if everything was fine. The status is PREPARE_FAILED_BAD_INPUT if the client should fix ...
Method to check if the impact function can be run. :return: A tuple with the status of the IF and an error message if needed. The status is PREPARE_SUCCESS if everything was fine. The status is PREPARE_FAILED_BAD_INPUT if the client should fix something. ...
def register_handler(self, callable_obj, entrypoint, methods=('GET',)): """Register a handler callable to a specific route. Args: entrypoint (str): The uri relative path. methods (tuple): A tuple of valid method strings. callable_obj (callable): The callable object. ...
Register a handler callable to a specific route. Args: entrypoint (str): The uri relative path. methods (tuple): A tuple of valid method strings. callable_obj (callable): The callable object. Returns: The Router instance (for chaining purposes). ...
def daemons_start(self, run_daemons=True): """Manage the list of the daemons in the configuration Check if the daemon needs to be started by the Arbiter. If so, starts the daemon if `run_daemons` is True :param run_daemons: run the daemons or make a simple check :type run_daem...
Manage the list of the daemons in the configuration Check if the daemon needs to be started by the Arbiter. If so, starts the daemon if `run_daemons` is True :param run_daemons: run the daemons or make a simple check :type run_daemons: bool :return: True if all daemons are ru...
def _request(self, request, proxies, timeout, verify, **_): """ This is where we apply rate limiting and make the HTTP request. """ settings = self.http.merge_environment_settings( request.url, proxies, False, verify, None) self._delay() response = self.http...
This is where we apply rate limiting and make the HTTP request.
def minimum_spanning_tree_kruskal(self, display = None, components = None): ''' API: minimum_spanning_tree_kruskal(self, display = None, components = None) Description: Determines a minimum spanning tree using Kruskal's Algorithm. Input:...
API: minimum_spanning_tree_kruskal(self, display = None, components = None) Description: Determines a minimum spanning tree using Kruskal's Algorithm. Input: display: Display method. component: component number. Post: ...
def contributor_group(self): """List of namedtuples representing contributors compiled by Scopus, in the form (given_name, initials, surname, indexed_name, role). """ items = listify(chained_get(self._head, ['source', 'contributor-group'], [])) out = [] fields = 'given_na...
List of namedtuples representing contributors compiled by Scopus, in the form (given_name, initials, surname, indexed_name, role).
def login(self, username=None, password=None, section='default'): """ Created the passport with ``username`` and ``password`` and log in. If either ``username`` or ``password`` is None or omitted, the credentials file will be parsed. :param str username: username t...
Created the passport with ``username`` and ``password`` and log in. If either ``username`` or ``password`` is None or omitted, the credentials file will be parsed. :param str username: username to login (email, phone number or user ID) :param str password: password :param str se...
def _strip_schema(url): """Returns the url without the s3:// part""" result = parse_url(url, allow_fragments=False) return result.netloc + result.path
Returns the url without the s3:// part
def move(src, dst): ''' Move a file or directory CLI Example: .. code-block:: bash salt '*' file.move /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('Source path must be ab...
Move a file or directory CLI Example: .. code-block:: bash salt '*' file.move /path/to/src /path/to/dst
def to_array(self): """ Serializes this VideoNote to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(VideoNote, self).to_array() array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str array[...
Serializes this VideoNote to a dictionary. :return: dictionary representation of this object. :rtype: dict
def list_hosts(): '''List the hosts of virtual folders that is accessible to the current user.''' with Session() as session: try: resp = session.VFolder.list_hosts() print(f"Default vfolder host: {resp['default']}") print(f"Usable hosts: {', '.join(resp['allowed'])}")...
List the hosts of virtual folders that is accessible to the current user.
def add_namespace(self, name, a_namespace): """as we build up argparse, the actions that define a subparser are translated into configman options. Each of those options must be tagged with the value of the subparse to which they correspond.""" # save a local copy of the namespace ...
as we build up argparse, the actions that define a subparser are translated into configman options. Each of those options must be tagged with the value of the subparse to which they correspond.