code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _check_and_send(self): """Check and send all pending/queued messages that are not waiting on retry timeout After composing the to-be-sent message, also message queue from messages that are not present in the respective SendMessageEvent queue anymore """ if self.transport._st...
Check and send all pending/queued messages that are not waiting on retry timeout After composing the to-be-sent message, also message queue from messages that are not present in the respective SendMessageEvent queue anymore
def labels(self, *labelvalues, **labelkwargs): """Return the child for the given labelset. All metrics can have labels, allowing grouping of related time series. Taking a counter as an example: from prometheus_client import Counter c = Counter('my_requests_total', 'HTT...
Return the child for the given labelset. All metrics can have labels, allowing grouping of related time series. Taking a counter as an example: from prometheus_client import Counter c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint']) c.labels(...
def get_self_uri(self, content_type): "return the first self uri with the content_type" try: return [self_uri for self_uri in self.self_uri_list if self_uri.content_type == content_type][0] except IndexError: return None
return the first self uri with the content_type
def infer_delimiter(filename, comment_char="#", n_lines=3): """ Given a file which contains data separated by one of the following: - commas - tabs - spaces Return the most likely separator by sniffing the first few lines of the file's contents. """ lines = [] with op...
Given a file which contains data separated by one of the following: - commas - tabs - spaces Return the most likely separator by sniffing the first few lines of the file's contents.
def child_task(self): '''child process - this holds all the GUI elements''' from MAVProxy.modules.lib import mp_util import wx_processguard from wx_loader import wx from wxsettings_ui import SettingsDlg mp_util.child_close_fds() app = wx.App(False) ...
child process - this holds all the GUI elements
def indirect(self, interface): """ Indirect the implementation of L{IWebViewer} to L{_AnonymousWebViewer}. """ if interface == IWebViewer: return _AnonymousWebViewer(self.store) return super(AnonymousSite, self).indirect(interface)
Indirect the implementation of L{IWebViewer} to L{_AnonymousWebViewer}.
def p_func_args(self, p): 'func_args : func_args COMMA expression' p[0] = p[1] + (p[3],) p.set_lineno(0, p.lineno(1))
func_args : func_args COMMA expression
def admin_view_reverse_fk_links(modeladmin: ModelAdmin, obj, reverse_fk_set_field: str, missing: str = "(None)", use_str: bool = True, separator: str = "<br>", ...
Get multiple Django admin site URL for multiple objects linked to our object of interest (where the other objects have foreign keys to our object).
def bugreport(dest_file="default.log"): """ Prints dumpsys, dumpstate, and logcat data to the screen, for the purposes of bug reporting :return: result of _exec_command() execution """ adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_BUGREPORT] try: dest_file_handler = open(dest_file,...
Prints dumpsys, dumpstate, and logcat data to the screen, for the purposes of bug reporting :return: result of _exec_command() execution
def pass_session_attributes(self): """Copies request attributes to response""" for key, value in six.iteritems(self.request.session.attributes): self.response.sessionAttributes[key] = value
Copies request attributes to response
def mimeData(self, items): """ Returns the mime data for dragging for this instance. :param items | [<QTreeWidgetItem>, ..] """ func = self.dataCollector() if func: return func(self, items) # extract the records from th...
Returns the mime data for dragging for this instance. :param items | [<QTreeWidgetItem>, ..]
def dlogprior(self, param): """Value of derivative of prior depends on value of `prior`.""" assert param in self.freeparams, "Invalid param: {0}".format(param) return self._dlogprior[param]
Value of derivative of prior depends on value of `prior`.
def get_authinfo(request): """Get authentication info from the encrypted message.""" if (("files_iv" not in request.session) or ("files_text" not in request.session) or ("files_key" not in request.COOKIES)): return False """ Decrypt the password given the SERVER-side IV, SERVER-side ...
Get authentication info from the encrypted message.
def upload_logs(self, release_singleton=True): ''' uploads a log to a server using the method and gui specifed in self.pcfg singleton mode can be disabled so a new version can be restarted whille uploading oges on typicallin in the case of uploadnig after a crash or sys exit ...
uploads a log to a server using the method and gui specifed in self.pcfg singleton mode can be disabled so a new version can be restarted whille uploading oges on typicallin in the case of uploadnig after a crash or sys exit set self.cfg log_upload_interface to gui/cli/or background
def txt(self, diff, f): """ Generate a text report for a diff. """ env = Environment( loader=PackageLoader('clan', 'templates'), trim_blocks=True, lstrip_blocks=True ) template = env.get_template('diff.txt') def format_row(lab...
Generate a text report for a diff.
def check_token(func): """检查 access token 是否有效.""" @wraps(func) def wrapper(*args, **kwargs): response = func(*args, **kwargs) if response.status_code == 401: raise InvalidToken('Access token invalid or no longer valid') else: return response return wrappe...
检查 access token 是否有效.
def checkInfo(email=None, username=None, api_key=None): ''' Method that checks if the given hash is stored in the pipl.com website. :param email: queries to be launched. :param api_key: api_key to be used in pipl.com. If not provided, the API key will be searched in the config_api_keys.py...
Method that checks if the given hash is stored in the pipl.com website. :param email: queries to be launched. :param api_key: api_key to be used in pipl.com. If not provided, the API key will be searched in the config_api_keys.py file. :return: Python structure for the Json received. It ha...
def values(self): """list of _ColumnPairwiseSignificance tests. Result has as many elements as there are coliumns in the slice. Each significance test contains `p_vals` and `t_stats` significance tests. """ # TODO: Figure out how to intersperse pairwise objects for columns ...
list of _ColumnPairwiseSignificance tests. Result has as many elements as there are coliumns in the slice. Each significance test contains `p_vals` and `t_stats` significance tests.
def token_view(token): """Show token details.""" if request.method == "POST" and 'delete' in request.form: db.session.delete(token) db.session.commit() return redirect(url_for('.index')) show_token = session.pop('show_personal_access_token', False) form = TokenForm(request.form...
Show token details.
def community_post_comments(self, post_id, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/post_comments#list-comments" api_path = "/api/v2/community/posts/{post_id}/comments.json" api_path = api_path.format(post_id=post_id) return self.call(api_path, **kwargs)
https://developer.zendesk.com/rest_api/docs/help_center/post_comments#list-comments
def set_contrast(self, contrast): """ Adjusts the image contrast. Contrast refers to the rate of change of color with color level. At low contrast, color changes gradually over many intensity levels, while at high contrast it can change rapidly within a few levels ...
Adjusts the image contrast. Contrast refers to the rate of change of color with color level. At low contrast, color changes gradually over many intensity levels, while at high contrast it can change rapidly within a few levels Args: contrast: float A numbe...
def dispense(self): '''dispense a card if ready, otherwise throw an Exception''' self.sendcommand(Vendapin.DISPENSE) # wait for the reply time.sleep(1) # parse the reply response = self.receivepacket() print('Vendapin.dispense(): ' + str(response)) if not ...
dispense a card if ready, otherwise throw an Exception
def normalizer(text, exclusion=OPERATIONS_EXCLUSION, lower=True, separate_char='-', **kwargs): """ Clean text string of simbols only alphanumeric chars. """ clean_str = re.sub(r'[^\w{}]'.format( "".join(exclusion)), separate_char, text.strip()) or '' clean_lowerbar = clean_str_without_accent...
Clean text string of simbols only alphanumeric chars.
def unpack_rawr_zip_payload(table_sources, payload): """unpack a zipfile and turn it into a callable "tables" object.""" # the io we get from S3 is streaming, so we can't seek on it, but zipfile # seems to require that. so we buffer it all in memory. RAWR tiles are # generally up to around 100MB in size...
unpack a zipfile and turn it into a callable "tables" object.
def init(envVarName, enableColorOutput=False): """ Initialize the logging system and parse the environment variable of the given name. Needs to be called before starting the actual application. """ global _initialized if _initialized: return global _ENV_VAR_NAME _ENV_VAR_NA...
Initialize the logging system and parse the environment variable of the given name. Needs to be called before starting the actual application.
def create_app(app_id, app_name, source_id, region, app_data): """ insert app record when stack run as a app """ try: create_at = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') conn = get_conn() c = conn.cursor() #check old app c.execute("SELECT count(*) F...
insert app record when stack run as a app
def add_semantic_data(self, path_as_list, value, key): """ Adds a semantic data entry. :param list path_as_list: The path in the vividict to enter the value :param value: The value of the new entry. :param key: The key of the new entry. :return: """ assert isinst...
Adds a semantic data entry. :param list path_as_list: The path in the vividict to enter the value :param value: The value of the new entry. :param key: The key of the new entry. :return:
def evolve_genomes(rng, pop, params, recorder=None): """ Evolve a population without tree sequence recordings. In other words, complete genomes must be simulated and tracked. :param rng: random number generator :type rng: :class:`fwdpy11.GSLrng` :param pop: A population :type pop: :class:`...
Evolve a population without tree sequence recordings. In other words, complete genomes must be simulated and tracked. :param rng: random number generator :type rng: :class:`fwdpy11.GSLrng` :param pop: A population :type pop: :class:`fwdpy11.DiploidPopulation` :param params: simulation paramete...
def Parse(self): """Iterator returning dict for each entry in history.""" for data in self.Query(self.EVENTS_QUERY): (timestamp, agent_bundle_identifier, agent_name, url, sender, sender_address, type_number, title, referrer, referrer_alias) = data yield [ timestamp, "OSX_QUARANTINE"...
Iterator returning dict for each entry in history.
def tops(opts): ''' Returns the tops modules ''' if 'master_tops' not in opts: return {} whitelist = list(opts['master_tops'].keys()) ret = LazyLoader( _module_dirs(opts, 'tops', 'top'), opts, tag='top', whitelist=whitelist, ) return FilterDictWrap...
Returns the tops modules
def _init_os_api(self): """ Initialise client objects for talking to OpenStack API. This is in a separate function so to be called by ``__init__`` and ``__setstate__``. """ if not self.nova_client: log.debug("Initializing OpenStack API clients:" ...
Initialise client objects for talking to OpenStack API. This is in a separate function so to be called by ``__init__`` and ``__setstate__``.
def ae_partial_waves(self): """Dictionary with the AE partial waves indexed by state.""" ae_partial_waves = OrderedDict() for mesh, values, attrib in self._parse_all_radfuncs("ae_partial_wave"): state = attrib["state"] #val_state = self.valence_states[state] a...
Dictionary with the AE partial waves indexed by state.
def rotate(obj, axis, angle, origin=None): ''' Rotation around unit vector following the right hand rule Parameters: obj : obj to be rotated (e.g. neurite, neuron). Must implement a transform method. axis : unit vector for the axis of rotation angle : rotation angle in r...
Rotation around unit vector following the right hand rule Parameters: obj : obj to be rotated (e.g. neurite, neuron). Must implement a transform method. axis : unit vector for the axis of rotation angle : rotation angle in rads Returns: A copy of the object with the...
def next(self): """ Goes to the previous page for this wizard. """ curr_page = self.currentPage() if not curr_page: return elif not curr_page.validatePage(): return pageId = curr_page.nextId() try: next_page = self._pag...
Goes to the previous page for this wizard.
def proxy_for(widget): """Create a proxy for a Widget :param widget: A gtk.Widget to proxy This will raise a KeyError if there is no proxy type registered for the widget type. """ proxy_type = widget_proxies.get(widget.__class__) if proxy_type is None: raise KeyError('There is no p...
Create a proxy for a Widget :param widget: A gtk.Widget to proxy This will raise a KeyError if there is no proxy type registered for the widget type.
def set_aesthetic(palette="yellowbrick", font="sans-serif", font_scale=1, color_codes=True, rc=None): """ Set aesthetic parameters in one step. Each set of parameters can be set directly or temporarily, see the referenced functions below for more information. Parameters -----...
Set aesthetic parameters in one step. Each set of parameters can be set directly or temporarily, see the referenced functions below for more information. Parameters ---------- palette : string or sequence Color palette, see :func:`color_palette` font : string Font family, see m...
def run(self, fnames=None): """Run Python scripts""" if fnames is None: fnames = self.get_selected_filenames() for fname in fnames: self.sig_run.emit(fname)
Run Python scripts
def _fill_missing_values(df, range_values, fill_value=0, fill_method=None): """ Will get the names of the index colums of df, obtain their ranges from range_values dict and return a reindexed version of df with the given range values. :param df: pandas DataFrame :param ...
Will get the names of the index colums of df, obtain their ranges from range_values dict and return a reindexed version of df with the given range values. :param df: pandas DataFrame :param range_values: dict or array-like Must contain for each index column of df an entry with ...
def delete_topic_rule(ruleName, region=None, key=None, keyid=None, profile=None): ''' Given a rule name, delete it. Returns {deleted: true} if the rule was deleted and returns {deleted: false} if the rule was not deleted. CLI Example: .. code-block:: bash salt myminion bo...
Given a rule name, delete it. Returns {deleted: true} if the rule was deleted and returns {deleted: false} if the rule was not deleted. CLI Example: .. code-block:: bash salt myminion boto_iot.delete_rule myrule
def reindex(self, request): """ Recreate the Search Index. """ r = redis.StrictRedis.from_url(request.registry.settings["celery.scheduler_url"]) try: with SearchLock(r, timeout=30 * 60, blocking_timeout=30): p = urllib.parse.urlparse(request.registry.settings["elasticsearch.url"]...
Recreate the Search Index.
def parametrized_class(decorator): '''Decorator used to make simple class decorator with arguments. Doesn't really do anything, just here to have a central implementation of the simple class decorator.''' def decorator_builder(*args, **kwargs): def meta_decorator(cls): return decor...
Decorator used to make simple class decorator with arguments. Doesn't really do anything, just here to have a central implementation of the simple class decorator.
def nodes(self, tree): """ Returns the relevant nodes for the spec's frequency """ # Run the match against the tree if self.frequency == 'per_session': nodes = [] for subject in tree.subjects: for sess in subject.sessions: ...
Returns the relevant nodes for the spec's frequency
def env(self, key, value=None, unset=False, asap=False): """Processes (sets/unsets) environment variable. If is not given in `set` mode value will be taken from current env. :param str|unicode key: :param value: :param bool unset: Whether to unset this variable. :par...
Processes (sets/unsets) environment variable. If is not given in `set` mode value will be taken from current env. :param str|unicode key: :param value: :param bool unset: Whether to unset this variable. :param bool asap: If True env variable will be set as soon as possible.
def getLinkProperties(self, wanInterfaceId=1, timeout=1): """Execute GetCommonLinkProperties action to get WAN link properties. :param int wanInterfaceId: the id of the WAN device :param float timeout: the timeout to wait for the action to be executed :return: WAN link properties ...
Execute GetCommonLinkProperties action to get WAN link properties. :param int wanInterfaceId: the id of the WAN device :param float timeout: the timeout to wait for the action to be executed :return: WAN link properties :rtype: WanLinkProperties
def _instance_callable(obj): """Given an object, return True if the object is callable. For classes, return True if instances would be callable.""" if not isinstance(obj, ClassTypes): # already an instance return getattr(obj, '__call__', None) is not None if six.PY3: # *could* b...
Given an object, return True if the object is callable. For classes, return True if instances would be callable.
def register_as_guest(self): """ Register a guest account on this HS. Note: HS must have guest registration enabled. Returns: str: Access Token Raises: MatrixRequestError """ response = self.api.register(auth_body=None, kind='guest') return...
Register a guest account on this HS. Note: HS must have guest registration enabled. Returns: str: Access Token Raises: MatrixRequestError
def insert_record(self, table: str, fields: Sequence[str], values: Sequence[Any], update_on_duplicate_key: bool = False) -> int: """Inserts a record into database, table "table", using the list of fieldnames and the ...
Inserts a record into database, table "table", using the list of fieldnames and the list of values. Returns the new PK (or None).
def _get_inherited_field_types(class_to_field_type_overrides, schema_graph): """Return a dictionary describing the field type overrides in subclasses.""" inherited_field_type_overrides = dict() for superclass_name, field_type_overrides in class_to_field_type_overrides.items(): for subclass_name in s...
Return a dictionary describing the field type overrides in subclasses.
def place_objects(self): """Places objects randomly until no collisions or max iterations hit.""" pos_arr, quat_arr = self.initializer.sample() for k, obj_name in enumerate(self.objects): self.objects[obj_name].set("pos", array_to_string(pos_arr[k])) self.objects[obj_name...
Places objects randomly until no collisions or max iterations hit.
def visit_List(self, node): """ List construction depend on each elements type dependency. """ if node.elts: return list(set(sum([self.visit(elt) for elt in node.elts], []))) else: return [frozenset()]
List construction depend on each elements type dependency.
def show_batch_runner(self): """Show the batch runner dialog.""" from safe.gui.tools.batch.batch_dialog import BatchDialog dialog = BatchDialog( parent=self.iface.mainWindow(), iface=self.iface, dock=self.dock_widget) dialog.exec_()
Show the batch runner dialog.
def check_no_signature(self, function, docstring): # def context """D402: First line should not be function's or method's "signature". The one-line docstring should NOT be a "signature" reiterating the function/method parameters (which can be obtained by introspection). """ if...
D402: First line should not be function's or method's "signature". The one-line docstring should NOT be a "signature" reiterating the function/method parameters (which can be obtained by introspection).
def init_progress_bar(self): """Initialize and return a progress bar.""" # Forked worker processes can't show progress bars. disable = MapReduce._forked or not config.PROGRESS_BARS # Don't materialize iterable unless we have to: huge iterables # (e.g. of `KCuts`) eat memory. ...
Initialize and return a progress bar.
def spin(self): """:class:`.BinaryQuadraticModel`: An instance of the Ising model subclass of the :class:`.BinaryQuadraticModel` superclass, corresponding to a binary quadratic model with spins as its variables. Enables access to biases for the spin-valued binary quadratic model ...
:class:`.BinaryQuadraticModel`: An instance of the Ising model subclass of the :class:`.BinaryQuadraticModel` superclass, corresponding to a binary quadratic model with spins as its variables. Enables access to biases for the spin-valued binary quadratic model regardless of the :class:`...
def to_file(file_): """Serializes file to id string :param file_: object to serialize :return: string id """ from sevenbridges.models.file import File if not file_: raise SbgError('File is required!') elif isinstance(file_, File): return fi...
Serializes file to id string :param file_: object to serialize :return: string id
def get_ilo_firmware_version_as_major_minor(self): """Gets the ilo firmware version for server capabilities Parse the get_host_health_data() to retreive the firmware details. :param data: the output returned by get_host_health_data() :returns: String with the format "<major>.<m...
Gets the ilo firmware version for server capabilities Parse the get_host_health_data() to retreive the firmware details. :param data: the output returned by get_host_health_data() :returns: String with the format "<major>.<minor>" or None.
def point_in_triangle(p, v1, v2, v3): """Checks whether a point is within the given triangle The function checks, whether the given point p is within the triangle defined by the the three corner point v1, v2 and v3. This is done by checking whether the point is on all three half-planes defined by the t...
Checks whether a point is within the given triangle The function checks, whether the given point p is within the triangle defined by the the three corner point v1, v2 and v3. This is done by checking whether the point is on all three half-planes defined by the three edges of the triangle. :param p: The...
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True): ''' Perform a query directly against the Azure REST API ''' certificate_path = config.get_cloud_config_value( 'certificate_path', get_configured_provider(), __opts__, search_global=False ) subsc...
Perform a query directly against the Azure REST API
def get_index2data(model_description): """ Get a dictionary that maps indices to a list of (1) the id in the hwrt symbol database (2) the latex command (3) the unicode code point (4) a font family and (5) a font style. Parameters ---------- model_description : string A model descrip...
Get a dictionary that maps indices to a list of (1) the id in the hwrt symbol database (2) the latex command (3) the unicode code point (4) a font family and (5) a font style. Parameters ---------- model_description : string A model description file that points to a feature folder where an ...
def ancestors(self): """Returns a list of the ancestors of this node.""" ancestors = set([]) self._depth_ascend(self, ancestors) try: ancestors.remove(self) except KeyError: # we weren't ancestor of ourself, that's ok pass return list(...
Returns a list of the ancestors of this node.
def queue_emission(self, msg): """ queue an emission of a message for all output plugins """ if not msg: return for _emitter in self._emit: if not hasattr(_emitter, 'emit'): continue def emit(emitter=_emitter): s...
queue an emission of a message for all output plugins
async def save(proxies, filename): """Save proxies to a file.""" with open(filename, 'w') as f: while True: proxy = await proxies.get() if proxy is None: break proto = 'https' if 'HTTPS' in proxy.types else 'http' row = '%s://%s:%d\n' % (pr...
Save proxies to a file.
def service(name, action): """ Open/close access to a service :param name: could be a service name defined in `/etc/services` or a port number. :param action: `open` or `close` """ if action == 'open': subprocess.check_output(['ufw', 'allow', str(name)], ...
Open/close access to a service :param name: could be a service name defined in `/etc/services` or a port number. :param action: `open` or `close`
def open_files(by_pid=False): ''' Return a list of all physical open files on the system. CLI Examples: .. code-block:: bash salt '*' file.open_files salt '*' file.open_files by_pid=True ''' # First we collect valid PIDs pids = {} procfs = os.listdir('/proc/') for ...
Return a list of all physical open files on the system. CLI Examples: .. code-block:: bash salt '*' file.open_files salt '*' file.open_files by_pid=True
def normalize(alias): """ Normalizes an alias by removing adverbs defined in IGNORED_WORDS """ # Convert from CamelCase to snake_case alias = re.sub(r'([a-z])([A-Z])', r'\1_\2', alias) # Ignore words words = alias.lower().split('_') words = filter(lambda w: w not in IGNORED_WORDS, words) ...
Normalizes an alias by removing adverbs defined in IGNORED_WORDS
def ref_file( ticker: str, fld: str, has_date=False, cache=False, ext='parq', **kwargs ) -> str: """ Data file location for Bloomberg reference data Args: ticker: ticker name fld: field has_date: whether add current date to data file cache: if has_date is True, wheth...
Data file location for Bloomberg reference data Args: ticker: ticker name fld: field has_date: whether add current date to data file cache: if has_date is True, whether to load file from latest cached ext: file extension **kwargs: other overrides passed to ref functi...
def _ExtractPathSpecsFromFile(self, file_entry): """Extracts path specification from a file. Args: file_entry (dfvfs.FileEntry): file entry that refers to the file. Yields: dfvfs.PathSpec: path specification of a file entry found in the file. """ produced_main_path_spec = False for...
Extracts path specification from a file. Args: file_entry (dfvfs.FileEntry): file entry that refers to the file. Yields: dfvfs.PathSpec: path specification of a file entry found in the file.
def remove_role(role): """Remove a action for a role.""" def processor(action, argument): ActionRoles.query_by_action(action, argument=argument).filter( ActionRoles.role_id == role.id ).delete(synchronize_session=False) return processor
Remove a action for a role.
def set_time_zone(self, item): """ Work out the time zone and create a shim tzinfo. We return True if all is good or False if there was an issue and we need to re check the time zone. see issue #1375 """ # parse i3status date i3s_time = item["full_text"].encode(...
Work out the time zone and create a shim tzinfo. We return True if all is good or False if there was an issue and we need to re check the time zone. see issue #1375
def find_mof(self, classname): """ Find the MOF file that defines a particular CIM class, in the search path of the MOF compiler. The MOF file is found based on its file name: It is assumed that the base part of the file name is the CIM class name. Example: The class "C...
Find the MOF file that defines a particular CIM class, in the search path of the MOF compiler. The MOF file is found based on its file name: It is assumed that the base part of the file name is the CIM class name. Example: The class "CIM_ComputerSystem" is expected to be in a file ...
def to_native(self, obj, name, value): # pylint:disable=unused-argument """Transform the MongoDB value into a Marrow Mongo value.""" if self.mapping: for original, new in self.mapping.items(): value = value.replace(original, new) return load(value, self.namespace)
Transform the MongoDB value into a Marrow Mongo value.
def score_samples(self, X): """Return the log-likelihood of each sample. See. "Pattern Recognition and Machine Learning" by C. Bishop, 12.2.1 p. 574 or http://www.miketipping.com/papers/met-mppca.pdf Parameters ---------- X : array, shape(n_samples, n_features) ...
Return the log-likelihood of each sample. See. "Pattern Recognition and Machine Learning" by C. Bishop, 12.2.1 p. 574 or http://www.miketipping.com/papers/met-mppca.pdf Parameters ---------- X : array, shape(n_samples, n_features) The data. Returns ...
def flush_redis_unsafe(redis_client=None): """This removes some non-critical state from the primary Redis shard. This removes the log files as well as the event log from Redis. This can be used to try to address out-of-memory errors caused by the accumulation of metadata in Redis. However, it will only...
This removes some non-critical state from the primary Redis shard. This removes the log files as well as the event log from Redis. This can be used to try to address out-of-memory errors caused by the accumulation of metadata in Redis. However, it will only partially address the issue as much of the da...
def get_pk(self, field_val): """convenience method for running is_pk(_id).get_one() since this is so common""" field_name = self.schema.pk.name return self.is_field(field_name, field_val).get_one()
convenience method for running is_pk(_id).get_one() since this is so common
def create_object_id(collection, vault, name, version): """ :param collection: The resource collection type. :type collection: str :param vault: The vault URI. :type vault: str :param name: The resource name. :type name: str :param version: The resource ve...
:param collection: The resource collection type. :type collection: str :param vault: The vault URI. :type vault: str :param name: The resource name. :type name: str :param version: The resource version. :type version: str :rtype: KeyVaultId
def parse_options(): """ Commandline options arguments parsing. """ # build options and help version = "%%prog {version}".format(version=__version__) parser = OptionParser(version=version) parser.add_option( "-u", "--username", action="store", dest="username", type="string",...
Commandline options arguments parsing.
def _load_hooks_settings(self): """load hooks settings""" log.debug("executing _load_hooks_settings") hook_show_widget = self.get_widget("hook_show") hook_show_setting = self.settings.hooks.get_string("show") if hook_show_widget is not None: if hook_show_setting is no...
load hooks settings
def poll(self): """ Poll for coordinator events. Only applicable if group_id is set, and broker version supports GroupCoordinators. This ensures that the coordinator is known, and if using automatic partition assignment, ensures that the consumer has joined the group. This also h...
Poll for coordinator events. Only applicable if group_id is set, and broker version supports GroupCoordinators. This ensures that the coordinator is known, and if using automatic partition assignment, ensures that the consumer has joined the group. This also handles periodic offset commi...
def set_terms(self,*terms, **kw_terms): """ Create or set top level terms in the section. After python 3.6.0, the terms entries should maintain the same order as the argument list. The term arguments can have any of these forms: * For position argument, a Term object * For kw ar...
Create or set top level terms in the section. After python 3.6.0, the terms entries should maintain the same order as the argument list. The term arguments can have any of these forms: * For position argument, a Term object * For kw arguments: - 'TermName=TermValue' - 'T...
def getSearchUrl(self, album, artist): """ See CoverSource.getSearchUrl. """ params = collections.OrderedDict() params["search-alias"] = "popular" params["field-artist"] = artist params["field-title"] = album params["sort"] = "relevancerank" return __class__.assembleUrl(self.base_url, params...
See CoverSource.getSearchUrl.
def get_certificates( self, vault_base_url, maxresults=None, include_pending=None, custom_headers=None, raw=False, **operation_config): """List certificates in a specified key vault. The GetCertificates operation returns the set of certificates resources in the specified key vault. ...
List certificates in a specified key vault. The GetCertificates operation returns the set of certificates resources in the specified key vault. This operation requires the certificates/list permission. :param vault_base_url: The vault name, for example https://myvault.vault.az...
def p_opt_order(self, p): '''opt_order : | ORDER LPAREN IDENTIFIER RPAREN''' if len(p) > 1: if p[3] not in 'CF': raise PythranSyntaxError("Invalid Pythran spec. " "Unknown order '{}'".format(p[3])) p[0]...
opt_order : | ORDER LPAREN IDENTIFIER RPAREN
def plot(self, x=None, y=None, z=None, what="count(*)", vwhat=None, reduce=["colormap"], f=None, normalize="normalize", normalize_axis="what", vmin=None, vmax=None, shape=256, vshape=32, limits=None, grid=None, colormap="afmhot", # colors=["red", "green", "blue"], figsize=None, xlab...
Viz data in a 2d histogram/heatmap. Declarative plotting of statistical plots using matplotlib, supports subplots, selections, layers. Instead of passing x and y, pass a list as x argument for multiple panels. Give what a list of options to have multiple panels. When both are present then will be origaniz...
def oauth2_token_setter(remote, resp, token_type='', extra_data=None): """Set an OAuth2 token. The refresh_token can be used to obtain a new access_token after the old one is expired. It is saved in the database for long term use. A refresh_token will be present only if `access_type=offline` is include...
Set an OAuth2 token. The refresh_token can be used to obtain a new access_token after the old one is expired. It is saved in the database for long term use. A refresh_token will be present only if `access_type=offline` is included in the authorization code request. :param remote: The remote applic...
def save(self, filename): """ Saves the xml data to the inputed filename. :param filename | <str> """ projex.text.xmlindent(self.xmlElement()) try: f = open(filename, 'w') except IOError: logger.exception('Could not s...
Saves the xml data to the inputed filename. :param filename | <str>
def addFASTACommandLineOptions(parser): """ Add standard command-line options to an argparse parser. @param parser: An C{argparse.ArgumentParser} instance. """ parser.add_argument( '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME', help=('The name of the FASTA input f...
Add standard command-line options to an argparse parser. @param parser: An C{argparse.ArgumentParser} instance.
def feather_links(self, factor=0.01, include_self=False): """ Feather the links of connected nodes. Go through every node in the network and make it inherit the links of the other nodes it is connected to. Because the link weight sum for any given node can be very different with...
Feather the links of connected nodes. Go through every node in the network and make it inherit the links of the other nodes it is connected to. Because the link weight sum for any given node can be very different within a graph, the weights of inherited links are made proportional to th...
def result_report_class_wise(self): """Report class-wise results Returns ------- str result report in string format """ results = self.results_class_wise_metrics() output = self.ui.section_header('Class-wise metrics', indent=2) + '\n' outp...
Report class-wise results Returns ------- str result report in string format
def read_until(self, expected_commands, timeout): """Read AdbMessages from this transport until we get an expected command. The ADB protocol specifies that before a successful CNXN handshake, any other packets must be ignored, so this method provides the ability to ignore unwanted commands. It's prima...
Read AdbMessages from this transport until we get an expected command. The ADB protocol specifies that before a successful CNXN handshake, any other packets must be ignored, so this method provides the ability to ignore unwanted commands. It's primarily used during the initial connection to the device...
def ValidOptions(cls): """Returns a list of valid option names.""" valid_options = [] for obj_name in dir(cls): obj = getattr(cls, obj_name) if inspect.isclass(obj) and issubclass(obj, cls.OptionBase): valid_options.append(obj_name) return valid_options
Returns a list of valid option names.
def adapter_add_nio_binding(self, adapter_number, port_number, nio): """ Adds a adapter NIO binding. :param adapter_number: adapter number :param port_number: port number :param nio: NIO instance to add to the adapter/port """ try: adapter = self._ad...
Adds a adapter NIO binding. :param adapter_number: adapter number :param port_number: port number :param nio: NIO instance to add to the adapter/port
def install_nginx(instance, dbhost, dbname, port, hostname=None): """Install nginx configuration""" _check_root() log("Installing nginx configuration") if hostname is None: try: configuration = _get_system_configuration(dbhost, dbname) hostname = configuration.hostname...
Install nginx configuration
def unserializers(self, value): """ Setter for **self.__unserializers** attribute. :param value: Attribute value. :type value: dict """ raise foundations.exceptions.ProgrammingError( "{0} | '{1}' attribute is read only!".format(self.__class__.__name__, "unse...
Setter for **self.__unserializers** attribute. :param value: Attribute value. :type value: dict
def validate_call(kwargs, returns, is_method=False): """ Decorator which runs validation on a callable's arguments and its return value. Pass a schema for the kwargs and for the return value. Positional arguments are not supported. """ def decorator(func): @wraps(func) def inner(...
Decorator which runs validation on a callable's arguments and its return value. Pass a schema for the kwargs and for the return value. Positional arguments are not supported.
def plot(darray, row=None, col=None, col_wrap=None, ax=None, hue=None, rtol=0.01, subplot_kws=None, **kwargs): """ Default plot of DataArray using matplotlib.pyplot. Calls xarray plotting function based on the dimensions of darray.squeeze() =============== =========================== ...
Default plot of DataArray using matplotlib.pyplot. Calls xarray plotting function based on the dimensions of darray.squeeze() =============== =========================== Dimensions Plotting function --------------- --------------------------- 1 :py:func:`xarray.plot.line` ...
def _commonprefix(files): """Retrieve a common prefix for files without extra _R1 _I1 extensions. Allows alternative naming schemes (R1/R2/R3) (R1/R2/I1). """ out = os.path.commonprefix(files) out = out.rstrip("_R") out = out.rstrip("_I") out = out.rstrip("_") return out
Retrieve a common prefix for files without extra _R1 _I1 extensions. Allows alternative naming schemes (R1/R2/R3) (R1/R2/I1).
def extern_store_utf8(self, context_handle, utf8_ptr, utf8_len): """Given a context and UTF8 bytes, return a new Handle to represent the content.""" c = self._ffi.from_handle(context_handle) return c.to_value(self._ffi.string(utf8_ptr, utf8_len).decode('utf-8'))
Given a context and UTF8 bytes, return a new Handle to represent the content.
def splitext_files_only(filepath): "Custom version of splitext that doesn't perform splitext on directories" return ( (filepath, '') if os.path.isdir(filepath) else os.path.splitext(filepath) )
Custom version of splitext that doesn't perform splitext on directories
def get_proficiencies_by_search(self, proficiency_query, proficiency_search): """Pass through to provider ProficiencySearchSession.get_proficiencies_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resources_by_search_template if not self._c...
Pass through to provider ProficiencySearchSession.get_proficiencies_by_search
async def acquire(self, command=None, args=()): """Acquires a connection from free pool. Creates new connection if needed. """ if self.closed: raise PoolClosedError("Pool is closed") async with self._cond: if self.closed: raise PoolClosedE...
Acquires a connection from free pool. Creates new connection if needed.