code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def reply_regexp(self, user, regexp): """Prepares a trigger for the regular expression engine. :param str user: The user ID invoking a reply. :param str regexp: The original trigger text to be turned into a regexp. :return regexp: The final regexp object.""" if regexp in self....
Prepares a trigger for the regular expression engine. :param str user: The user ID invoking a reply. :param str regexp: The original trigger text to be turned into a regexp. :return regexp: The final regexp object.
def resize(self, shape): """ Resize all attached buffers with the given shape Parameters ---------- shape : tuple of two integers New buffer shape (h, w), to be applied to all currently attached buffers. For buffers that are a texture, the number of c...
Resize all attached buffers with the given shape Parameters ---------- shape : tuple of two integers New buffer shape (h, w), to be applied to all currently attached buffers. For buffers that are a texture, the number of color channels is preserved.
def update(self, get_running_apps=True): """Get the state of the device, the current app, and the running apps. :param get_running_apps: whether or not to get the ``running_apps`` property :return state: the state of the device :return current_app: the current app :return runnin...
Get the state of the device, the current app, and the running apps. :param get_running_apps: whether or not to get the ``running_apps`` property :return state: the state of the device :return current_app: the current app :return running_apps: the running apps
def ignore(name): ''' Ignore a specific program update. When an update is ignored the '-' and version number at the end will be omitted, so "SecUpd2014-001-1.0" becomes "SecUpd2014-001". It will be removed automatically if present. An update is successfully ignored when it no longer shows up after l...
Ignore a specific program update. When an update is ignored the '-' and version number at the end will be omitted, so "SecUpd2014-001-1.0" becomes "SecUpd2014-001". It will be removed automatically if present. An update is successfully ignored when it no longer shows up after list_updates. :param name:...
def _prep_subsampled_bams(data, work_dir): """Prepare a subsampled BAM file with discordants from samblaster and minimal correct pairs. This attempts to minimize run times by pre-extracting useful reads mixed with subsampled normal pairs to estimate paired end distributions: https://groups.google.com/...
Prepare a subsampled BAM file with discordants from samblaster and minimal correct pairs. This attempts to minimize run times by pre-extracting useful reads mixed with subsampled normal pairs to estimate paired end distributions: https://groups.google.com/d/msg/delly-users/xmia4lwOd1Q/uaajoBkahAIJ Su...
def bool_value(self): """Infer the truth value for an Instance The truth value of an instance is determined by these conditions: * if it implements __bool__ on Python 3 or __nonzero__ on Python 2, then its bool value will be determined by calling this special metho...
Infer the truth value for an Instance The truth value of an instance is determined by these conditions: * if it implements __bool__ on Python 3 or __nonzero__ on Python 2, then its bool value will be determined by calling this special method and checking its result. ...
def add_op(state, op_func, *args, **kwargs): ''' Prepare & add an operation to ``pyinfra.state`` by executing it on all hosts. Args: state (``pyinfra.api.State`` obj): the deploy state to add the operation to op_func (function): the operation function from one of the modules, ie ``s...
Prepare & add an operation to ``pyinfra.state`` by executing it on all hosts. Args: state (``pyinfra.api.State`` obj): the deploy state to add the operation to op_func (function): the operation function from one of the modules, ie ``server.user`` args/kwargs: passed to the operation...
def netloc_no_www(url): """ For a given URL return the netloc with any www. striped. """ ext = tldextract.extract(url) if ext.subdomain and ext.subdomain != 'www': return '%s.%s.%s' % (ext.subdomain, ext.domain, ext.tld) else: return '%s.%s' % (ext.domain, ext.tld)
For a given URL return the netloc with any www. striped.
def recipients(cls, bigchain): """Convert validator dictionary to a recipient list for `Transaction`""" recipients = [] for public_key, voting_power in cls.get_validators(bigchain).items(): recipients.append(([public_key], voting_power)) return recipients
Convert validator dictionary to a recipient list for `Transaction`
def read_uint(data, start, length): """Extract a uint from a position in a sequence.""" return int.from_bytes(data[start:start+length], byteorder='big')
Extract a uint from a position in a sequence.
def resizeEvent(self, event): """ Moves the widgets around the system. :param event | <QtGui.QResizeEvent> """ super(XWalkthroughWidget, self).resizeEvent(event) if self.isVisible(): self.autoLayout()
Moves the widgets around the system. :param event | <QtGui.QResizeEvent>
def remove_root_vault(self, vault_id): """Removes a root vault from this hierarchy. arg: vault_id (osid.id.Id): the ``Id`` of a vault raise: NotFound - ``vault_id`` not a parent of ``child_id`` raise: NullArgument - ``vault_id`` or ``child_id`` is ``null`` raise: Operation...
Removes a root vault from this hierarchy. arg: vault_id (osid.id.Id): the ``Id`` of a vault raise: NotFound - ``vault_id`` not a parent of ``child_id`` raise: NullArgument - ``vault_id`` or ``child_id`` is ``null`` raise: OperationFailed - unable to complete request raise:...
def init_remote(self): ''' Initialize/attach to a remote using GitPython. Return a boolean which will let the calling function know whether or not a new repo was initialized by this function. ''' new = False if not os.listdir(self.cachedir): # Repo cac...
Initialize/attach to a remote using GitPython. Return a boolean which will let the calling function know whether or not a new repo was initialized by this function.
def _get_horoscope(self, day='today'): """gets a horoscope from site html :param day: day for which to get horoscope. Default is 'today' :returns: dictionary of horoscope details """ if not is_valid_day(day): raise HoroscopeException("Invalid day. Allowed days: [tod...
gets a horoscope from site html :param day: day for which to get horoscope. Default is 'today' :returns: dictionary of horoscope details
def select_all(self, serial_numbers): """Select rows for identification for a list of serial_number. Args: serial_numbers: list (or ndarray) of serial numbers Returns: pandas.DataFrame """ sheet = self.table col = self.db_sheet_cols.id ro...
Select rows for identification for a list of serial_number. Args: serial_numbers: list (or ndarray) of serial numbers Returns: pandas.DataFrame
def filter_batch(self, batch): """ Receives the batch, filters it, and returns it. """ for item in batch: if self.filter(item): yield item else: self.set_metadata('filtered_out', self.get_metadata('...
Receives the batch, filters it, and returns it.
def _set_transmitted_stp_type(self, v, load=False): """ Setter method for transmitted_stp_type, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_mst_detail/output/cist/port/transmitted_stp_type (stp-type) If this variable is read-only (config: false) in the source YANG file, then _set_transmitted...
Setter method for transmitted_stp_type, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_mst_detail/output/cist/port/transmitted_stp_type (stp-type) If this variable is read-only (config: false) in the source YANG file, then _set_transmitted_stp_type is considered as a private method. Backends lookin...
def rlmb_ppo_quick(): """Base setting but quicker with only 2 epochs.""" hparams = rlmb_ppo_base() hparams.epochs = 2 hparams.model_train_steps = 25000 hparams.ppo_epochs_num = 700 hparams.ppo_epoch_length = 50 return hparams
Base setting but quicker with only 2 epochs.
def expect(self, use_proportions=True): """ The Expectation step of the CEM algorithm """ changed = self.get_changed(self.partition, self.prev_partition) lk_table = self.generate_lktable(self.partition, changed, use_proportions) self.table = self.likelihood_table_to_probs(lk_table)
The Expectation step of the CEM algorithm
def get_identities(self, item): ''' Return the identities from an item ''' item = item['data'] # Creators if 'event_hosts' in item: user = self.get_sh_identity(item['event_hosts'][0]) yield user # rsvps rsvps = item.get('rsvps', []) for...
Return the identities from an item
def Chisholm_Armand(x, rhol, rhog): r'''Calculates void fraction in two-phase flow according to the model presented in [1]_ based on that of [2]_ as shown in [3]_, [4]_, and [5]_. .. math:: \alpha = \frac{\alpha_h}{\alpha_h + (1-\alpha_h)^{0.5}} Parameters ---------- x : float ...
r'''Calculates void fraction in two-phase flow according to the model presented in [1]_ based on that of [2]_ as shown in [3]_, [4]_, and [5]_. .. math:: \alpha = \frac{\alpha_h}{\alpha_h + (1-\alpha_h)^{0.5}} Parameters ---------- x : float Quality at the specific tube int...
def analysis(self): """Get ANALYSIS segment of the FCS file.""" if self._analysis is None: with open(self.path, 'rb') as f: self.read_analysis(f) return self._analysis
Get ANALYSIS segment of the FCS file.
def gross_lev(positions): """ Calculates the gross leverage of a strategy. Parameters ---------- positions : pd.DataFrame Daily net position values. - See full explanation in tears.create_full_tear_sheet. Returns ------- pd.Series Gross leverage. """ e...
Calculates the gross leverage of a strategy. Parameters ---------- positions : pd.DataFrame Daily net position values. - See full explanation in tears.create_full_tear_sheet. Returns ------- pd.Series Gross leverage.
def _get_connection(self, uri, headers=None): """Opens a socket connection to the server to set up an HTTP request. Args: uri: The full URL for the request as a Uri object. headers: A dict of string pairs containing the HTTP headers for the request. """ connection = None i...
Opens a socket connection to the server to set up an HTTP request. Args: uri: The full URL for the request as a Uri object. headers: A dict of string pairs containing the HTTP headers for the request.
def zyz_circuit(t0: float, t1: float, t2: float, q0: Qubit) -> Circuit: """Circuit equivalent of 1-qubit ZYZ gate""" circ = Circuit() circ += TZ(t0, q0) circ += TY(t1, q0) circ += TZ(t2, q0) return circ
Circuit equivalent of 1-qubit ZYZ gate
def set_hr_widths(result): """ We want the hrs indented by hirarchy... A bit 2 much effort to calc, maybe just fixed with 10 style seps would have been enough visually: β—ˆβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β—ˆ """ # set all hrs to max width of text: mw = 0 hrs = [] if not hr_marker in result: retu...
We want the hrs indented by hirarchy... A bit 2 much effort to calc, maybe just fixed with 10 style seps would have been enough visually: β—ˆβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β—ˆ
def _timestamp(when): """ Python 2 compatibility for `datetime.timestamp()`. """ return (time.mktime(when.timetuple()) if sys.version_info < (3,) else when.timestamp())
Python 2 compatibility for `datetime.timestamp()`.
def convert(self, value, *args, **kwargs): # pylint: disable=arguments-differ """Take a path with $HOME variables and resolve it to full path.""" value = os.path.expanduser(value) return super(ExpandPath, self).convert(value, *args, **kwargs)
Take a path with $HOME variables and resolve it to full path.
def description(self): """string or None if unknown""" name = None try: name = self._TYPE_NAMES[self.audioObjectType] except IndexError: pass if name is None: return if self.sbrPresentFlag == 1: name += "+SBR" if se...
string or None if unknown
def valid_input(val): """ Ensure the input the user gave is of a valid format """ # looks for 3 nums followed by a dot 3 times and then ending with # 3 nums, can be proceeded by any number of spaces ip_value = re.compile(r'(\d{1,3}\.){3}\d{1,3}$') # looks for only numbers and com...
Ensure the input the user gave is of a valid format
def remove_allocated_node_name(self, name): """ Removes an allocated node name :param name: allocated node name """ if name in self._allocated_node_names: self._allocated_node_names.remove(name)
Removes an allocated node name :param name: allocated node name
def retrieve(self, request, *args, **kwargs): """ User fields can be updated by account owner or user with staff privilege (is_staff=True). Following user fields can be updated: - organization (deprecated, use `organization plugin <http://waldur_core-organization.readthedocs.o...
User fields can be updated by account owner or user with staff privilege (is_staff=True). Following user fields can be updated: - organization (deprecated, use `organization plugin <http://waldur_core-organization.readthedocs.org/en/stable/>`_ instead) - full_name - native_nam...
def check_qt(): """Check Qt binding requirements""" qt_infos = dict(pyqt5=("PyQt5", "5.6")) try: import qtpy package_name, required_ver = qt_infos[qtpy.API] actual_ver = qtpy.PYQT_VERSION if LooseVersion(actual_ver) < LooseVersion(required_ver): show_warni...
Check Qt binding requirements
def sign_extend(self, new_length): """ Unary operation: SignExtend :param new_length: New length after sign-extension :return: A new StridedInterval """ msb = self.extract(self.bits - 1, self.bits - 1).eval(2) if msb == [ 0 ]: # All positive numbers ...
Unary operation: SignExtend :param new_length: New length after sign-extension :return: A new StridedInterval
def keep_folder(raw_path): """ Keep only folders that don't contain patterns in `DIR_EXCLUDE_PATTERNS`. """ keep = True for pattern in DIR_EXCLUDE_PATTERNS: if pattern in raw_path: LOGGER.debug('rejecting', raw_path) keep = False return keep
Keep only folders that don't contain patterns in `DIR_EXCLUDE_PATTERNS`.
def eval_permission(self, token, resource, scope, submit_request=False): """ Evalutes if user has permission for scope on resource. :param str token: client access token :param str resource: resource to access :param str scope: scope on resource :param boolean submit_req...
Evalutes if user has permission for scope on resource. :param str token: client access token :param str resource: resource to access :param str scope: scope on resource :param boolean submit_request: submit request if not allowed to access? rtype: boolean
def paths(self): """Iterates through all files in the set""" if self.format is None: raise ArcanaFileFormatError( "Cannot get paths of fileset ({}) that hasn't had its format " "set".format(self)) if self.format.directory: return chain(*((o...
Iterates through all files in the set
def log(self, message, severity=INFO, tag=u""): """ Add a given message to the log, and return its time. :param string message: the message to be added :param severity: the severity of the message :type severity: :class:`~aeneas.logger.Logger` :param string tag: the tag...
Add a given message to the log, and return its time. :param string message: the message to be added :param severity: the severity of the message :type severity: :class:`~aeneas.logger.Logger` :param string tag: the tag associated with the message; usually, th...
def parse(args): """\ Parses the arguments and returns the result. """ parser = make_parser() if not len(args): parser.print_help() sys.exit(1) parsed_args = parser.parse_args(args) if parsed_args.error == '-': parsed_args.error = None # 'micro' is False by defaul...
\ Parses the arguments and returns the result.
def filter_queryset(self, request, queryset, view): """ Filter out any artifacts which the requesting user does not have permission to view. """ if request.user.is_superuser: return queryset return queryset.filter(status__user=request.user)
Filter out any artifacts which the requesting user does not have permission to view.
def remove_stale_javascripts(portal): """Removes stale javascripts """ logger.info("Removing stale javascripts ...") for js in JAVASCRIPTS_TO_REMOVE: logger.info("Unregistering JS %s" % js) portal.portal_javascripts.unregisterResource(js)
Removes stale javascripts
def visit_NameConstant(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s name as string.""" return str(node.value)
Return `node`s name as string.
def plot_magnitude_time_scatter( catalogue, plot_error=False, fmt_string='o', filename=None, figure_size=(8, 6), filetype='png', dpi=300, ax=None): """ Creates a simple scatter plot of magnitude with time :param catalogue: Earthquake catalogue as instance of :class: openquak...
Creates a simple scatter plot of magnitude with time :param catalogue: Earthquake catalogue as instance of :class: openquake.hmtk.seismicity.catalogue.Catalogue :param bool plot_error: Choose to plot error bars (True) or not (False) :param str fmt_string: Symbology of plot
def createDbusProxyObject(bus_name, object_path, bus=None): ''' Create dbus proxy object ''' bus = bus or dbus.SessionBus.get_session() return bus.get_object(bus_name, object_path)
Create dbus proxy object
def data(self, index, role): """use zipped icon.png as icon""" if index.column() == 0 and role == QtCore.Qt.DecorationRole: if self.isPyz(index): with ZipFile(str(self.filePath(index)), 'r') as myzip: # print myzip.namelist() t...
use zipped icon.png as icon
def std_ratio(sim=None, obs=None, node=None, skip_nan=False): """Calculate the ratio between the standard deviation of the simulated and the observed values. >>> from hydpy import round_ >>> from hydpy import std_ratio >>> round_(std_ratio(sim=[1.0, 2.0, 3.0], obs=[1.0, 2.0, 3.0])) 0.0 >>> ...
Calculate the ratio between the standard deviation of the simulated and the observed values. >>> from hydpy import round_ >>> from hydpy import std_ratio >>> round_(std_ratio(sim=[1.0, 2.0, 3.0], obs=[1.0, 2.0, 3.0])) 0.0 >>> round_(std_ratio(sim=[1.0, 1.0, 1.0], obs=[1.0, 2.0, 3.0])) -1.0 ...
def remove_file(path, conn=None): ''' Remove a single file from the file system ''' if conn is None: conn = init() log.debug('Removing package file %s', path) os.remove(path)
Remove a single file from the file system
def zero_extend(self, duration_s=None, num_samples=None): """ Adds a number of zeros (digital silence) to the AudioSegment (returning a new one). :param duration_s: The number of seconds of zeros to add. If this is specified, `num_samples` must be None. :param num_samples: The number of...
Adds a number of zeros (digital silence) to the AudioSegment (returning a new one). :param duration_s: The number of seconds of zeros to add. If this is specified, `num_samples` must be None. :param num_samples: The number of zeros to add. If this is specified, `duration_s` must be None. :retur...
def _parse(data: str) -> list: """ Parses the given data string and returns a list of rule objects. """ if isinstance(data, bytes): data = data.decode('utf-8') lines = ( item for item in (item.strip() for item in data.split('\n')) ...
Parses the given data string and returns a list of rule objects.
def log_verbose(self, message): """ Logs a message only when logging level is verbose. :param str|list[str] message: The message. """ if self.get_verbosity() >= Output.VERBOSITY_VERBOSE: self.writeln(message)
Logs a message only when logging level is verbose. :param str|list[str] message: The message.
def update_conversation(self, conversation): """Update the internal state of the conversation. This method is used by :class:`.ConversationList` to maintain this instance. Args: conversation: ``Conversation`` message. """ # StateUpdate.conversation is actual...
Update the internal state of the conversation. This method is used by :class:`.ConversationList` to maintain this instance. Args: conversation: ``Conversation`` message.
def load_stylesheet(self, id, path): """ Proper way to dynamically inject a stylesheet in a page. :param path: Path of the stylesheet to inject. """ self.add_child(HeadLink(id=id, link_type="stylesheet", path=path))
Proper way to dynamically inject a stylesheet in a page. :param path: Path of the stylesheet to inject.
def send_file_external(self, url_json, chunk): """ Send chunk to external store specified in url_json. Raises ValueError on upload failure. :param data_service: data service to use for sending chunk :param url_json: dict contains where/how to upload chunk :param chunk: da...
Send chunk to external store specified in url_json. Raises ValueError on upload failure. :param data_service: data service to use for sending chunk :param url_json: dict contains where/how to upload chunk :param chunk: data to be uploaded
def normalize(l): """ Normalizes input list. Parameters ---------- l: list The list to be normalized Returns ------- The normalized list or numpy array Raises ------ ValueError, if the list sums to zero """ s = float(sum(l)) if s == 0: raise Va...
Normalizes input list. Parameters ---------- l: list The list to be normalized Returns ------- The normalized list or numpy array Raises ------ ValueError, if the list sums to zero
def load_raw(args): """ Read the actual file *as is* without parsing/modifiying it so that it can be written maintaining its same properties. :param args: Will be used to infer the proper configuration name :paran path: alternatively, use a path for any configuration file loading """ path =...
Read the actual file *as is* without parsing/modifiying it so that it can be written maintaining its same properties. :param args: Will be used to infer the proper configuration name :paran path: alternatively, use a path for any configuration file loading
def _maybe_download_corpus(tmp_dir, vocab_type): """Download and unpack the corpus. Args: tmp_dir: directory containing dataset. vocab_type: which vocabulary are we using. Returns: The list of names of files. """ filename = os.path.basename(PTB_URL) compressed_filepath = generator_utils.maybe_...
Download and unpack the corpus. Args: tmp_dir: directory containing dataset. vocab_type: which vocabulary are we using. Returns: The list of names of files.
def p_expr_LT_expr(p): """ expr : expr LT expr """ p[0] = make_binary(p.lineno(2), 'LT', p[1], p[3], lambda x, y: x < y)
expr : expr LT expr
def get_html(grafs): """ Renders the grafs provided in HTML by wrapping them in <p> tags. Linebreaks are replaced with <br> tags. """ html = [format_html('<p>{}</p>', p) for p in grafs] html = [p.replace("\n", "<br>") for p in html] return format_html(six.text_type('\n\n'.join(html)))
Renders the grafs provided in HTML by wrapping them in <p> tags. Linebreaks are replaced with <br> tags.
def insertDatasetWOannex(self, dataset, blockcontent, otptIdList, conn, insertDataset = True, migration = False): """ _insertDatasetOnly_ Insert the dataset and only the dataset Meant to be called after everything else is put into place. The insertD...
_insertDatasetOnly_ Insert the dataset and only the dataset Meant to be called after everything else is put into place. The insertDataset flag is set to false if the dataset already exists
def serialize(exc): """ Serialize `self.exc` into a data dictionary representing it. """ return { 'exc_type': type(exc).__name__, 'exc_path': get_module_path(type(exc)), 'exc_args': list(map(safe_for_serialization, exc.args)), 'value': safe_for_serialization(exc), }
Serialize `self.exc` into a data dictionary representing it.
def delete_record(self, instance): """Deletes the record.""" adapter = self.get_adapter_from_instance(instance) adapter.delete_record(instance)
Deletes the record.
def perpendicular_vector(n): """ Get a random vector perpendicular to the given vector """ dim = len(n) if dim == 2: return n[::-1] # More complex in 3d for ix in range(dim): _ = N.zeros(dim) # Try to keep axes near the global projection # by finding vecto...
Get a random vector perpendicular to the given vector
def get_utm_zone(longitude): """Return utm zone.""" zone = int((math.floor((longitude + 180.0) / 6.0) + 1) % 60) if zone == 0: zone = 60 return zone
Return utm zone.
def delete(self): """ Delete the cloud from the list of added clouds in mist.io service. :returns: A list of mist.clients' updated clouds. """ req = self.request(self.mist_client.uri + '/clouds/' + self.id) req.delete() self.mist_client.update_clouds()
Delete the cloud from the list of added clouds in mist.io service. :returns: A list of mist.clients' updated clouds.
def _grid_distance(self, index): """ Calculate the distance grid for a single index position. This is pre-calculated for fast neighborhood calculations later on (see _calc_influence). """ # Take every dimension but the first in reverse # then reverse that list ag...
Calculate the distance grid for a single index position. This is pre-calculated for fast neighborhood calculations later on (see _calc_influence).
def save(self, path=None, filter_name=None): """ Saves this document to a local file system. The optional first argument defaults to the document's path. Accept optional second argument which defines type of the saved file. Use one of FILTER_* constants or see list of ...
Saves this document to a local file system. The optional first argument defaults to the document's path. Accept optional second argument which defines type of the saved file. Use one of FILTER_* constants or see list of available filters at http://wakka.net/archives/7 or http:...
def isMember(userid, password, group): """Test to see if the given userid/password combo is an authenticated member of group. userid: CADC Username (str) password: CADC Password (str) group: CADC GMS group (str) """ try: certfile = getCert(userid, password) group_url = get...
Test to see if the given userid/password combo is an authenticated member of group. userid: CADC Username (str) password: CADC Password (str) group: CADC GMS group (str)
def sample_stats_prior_to_xarray(self): """Extract sample_stats_prior from prior.""" prior = self.prior data = get_sample_stats(prior) return dict_to_dataset(data, library=self.pystan, coords=self.coords, dims=self.dims)
Extract sample_stats_prior from prior.
def parse_favorites(self, favorites_page): """Parses the DOM and returns character favorites attributes. :type favorites_page: :class:`bs4.BeautifulSoup` :param favorites_page: MAL character favorites page's DOM :rtype: dict :return: Character favorites attributes. """ character_info = se...
Parses the DOM and returns character favorites attributes. :type favorites_page: :class:`bs4.BeautifulSoup` :param favorites_page: MAL character favorites page's DOM :rtype: dict :return: Character favorites attributes.
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_game( # receiver, self.media, disable_notification=...
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
def literal(node): """ Inline code """ rendered = [] try: if node.info is not None: l = Lexer(node.literal, node.info, tokennames="long") for _ in l: rendered.append(node.inline(classes=_[0], text=_[1])) except: pass classes = ['code']...
Inline code
def create_dampening(self, trigger_id, dampening): """ Create a new dampening. :param trigger_id: TriggerId definition attached to the dampening :param dampening: Dampening definition to be created. :type dampening: Dampening :return: Created dampening """ ...
Create a new dampening. :param trigger_id: TriggerId definition attached to the dampening :param dampening: Dampening definition to be created. :type dampening: Dampening :return: Created dampening
def draw_path_collection(self, paths, path_coordinates, path_transforms, offsets, offset_coordinates, offset_order, styles, mplobj=None): """ Draw a collection of paths. The paths, offsets, and styles are all iterables, and the number of ...
Draw a collection of paths. The paths, offsets, and styles are all iterables, and the number of paths is max(len(paths), len(offsets)). By default, this is implemented via multiple calls to the draw_path() function. For efficiency, Renderers may choose to customize this implementation. ...
def boolean(value): """Parse the string ``"true"`` or ``"false"`` as a boolean (case insensitive). Also accepts ``"1"`` and ``"0"`` as ``True``/``False`` (respectively). If the input is from the request JSON body, the type is already a native python boolean, and will be passed through without furthe...
Parse the string ``"true"`` or ``"false"`` as a boolean (case insensitive). Also accepts ``"1"`` and ``"0"`` as ``True``/``False`` (respectively). If the input is from the request JSON body, the type is already a native python boolean, and will be passed through without further parsing.
def parse(str_, lsep=",", avsep=":", vssep=",", avssep=";"): """Generic parser""" if avsep in str_: return parse_attrlist(str_, avsep, vssep, avssep) if lsep in str_: return parse_list(str_, lsep) return parse_single(str_)
Generic parser
def extension_context(extension_name='cpu', **kw): """Get the context of the specified extension. All extension's module must provide `context(**kw)` function. Args: extension_name (str) : Module path relative to `nnabla_ext`. kw (dict) : Additional keyword arguments for context function i...
Get the context of the specified extension. All extension's module must provide `context(**kw)` function. Args: extension_name (str) : Module path relative to `nnabla_ext`. kw (dict) : Additional keyword arguments for context function in a extension module. Returns: :class:`nnabla...
def qc_to_rec(samples): """CWL: Convert a set of input samples into records for parallelization. """ samples = [utils.to_single_data(x) for x in samples] samples = cwlutils.assign_complex_to_samples(samples) to_analyze, extras = _split_samples_by_qc(samples) recs = cwlutils.samples_to_records([u...
CWL: Convert a set of input samples into records for parallelization.
def url(self, host): """Generate url for coap client.""" path = '/'.join(str(v) for v in self._path) return 'coaps://{}:5684/{}'.format(host, path)
Generate url for coap client.
def activate_output(self, universe: int) -> None: """ Activates a universe that's then starting to sending every second. See http://tsp.esta.org/tsp/documents/docs/E1-31-2016.pdf for more information :param universe: the universe to activate """ check_universe(universe) ...
Activates a universe that's then starting to sending every second. See http://tsp.esta.org/tsp/documents/docs/E1-31-2016.pdf for more information :param universe: the universe to activate
def clear(self, database, callback=None): """ Wipe the given database. This only affects items inserted remotely; items inserted on the watch (e.g. alarm clock timeline pins) are not removed. :param database: The database to wipe. :type database: .BlobDatabaseID :param c...
Wipe the given database. This only affects items inserted remotely; items inserted on the watch (e.g. alarm clock timeline pins) are not removed. :param database: The database to wipe. :type database: .BlobDatabaseID :param callback: A callback to be called on success or failure.
def _download_article(self, article_number, max_retries=10): """Download a given article. :type article_number: str :param article_number: the article number to download. :type group: str :param group: the group that contains the article to be downloaded. :returns: nnt...
Download a given article. :type article_number: str :param article_number: the article number to download. :type group: str :param group: the group that contains the article to be downloaded. :returns: nntplib article response object if successful, else False.
def get_signing_key(self, key_type="", owner="", kid=None, **kwargs): """ Shortcut to use for signing keys only. :param key_type: Type of key (rsa, ec, oct, ..) :param owner: Who is the owner of the keys, "" == me (default) :param kid: A Key Identifier :param kwargs: Ext...
Shortcut to use for signing keys only. :param key_type: Type of key (rsa, ec, oct, ..) :param owner: Who is the owner of the keys, "" == me (default) :param kid: A Key Identifier :param kwargs: Extra key word arguments :return: A possibly empty list of keys
def running_covar(xx=True, xy=False, yy=False, remove_mean=False, symmetrize=False, sparse_mode='auto', modify_data=False, column_selection=None, diag_only=False, nsave=5): """ Returns a running covariance estimator Returns an estimator object that can be fed chunks of X and Y data, and t...
Returns a running covariance estimator Returns an estimator object that can be fed chunks of X and Y data, and that can generate on-the-fly estimates of mean, covariance, running sum and second moment matrix. Parameters ---------- xx : bool Estimate the covariance of X xy : bool ...
def stop_notifications(self): """Stop the notifications thread. :returns: """ with self._notifications_lock: if not self.has_active_notification_thread: return thread = self._notifications_thread self._notifications_thread = None ...
Stop the notifications thread. :returns:
def __is_current(filepath): '''Checks whether file is current''' if not __DOWNLOAD_PARAMS['auto_update']: return True if not os.path.isfile(filepath): return False return datetime.datetime.utcfromtimestamp(os.path.getmtime(filepath)) \ > __get_last_update_time()
Checks whether file is current
def convert_json_node(self, json_input): """ Dispatch JSON input according to the outermost type and process it to generate the super awesome HTML format. We try to adhere to duck typing such that users can just pass all kinds of funky objects to json2html that *b...
Dispatch JSON input according to the outermost type and process it to generate the super awesome HTML format. We try to adhere to duck typing such that users can just pass all kinds of funky objects to json2html that *behave* like dicts and lists and other basic JSON type...
def initialize_connection(self): # noqa: E501 pylint:disable=too-many-statements, too-many-branches """Initialize a socket to a Chromecast, retrying as necessary.""" tries = self.tries if self.socket is not None: self.socket.close() self.socket = None # Make su...
Initialize a socket to a Chromecast, retrying as necessary.
def to_json(self): """Return a header as a dictionary.""" a_per = self.analysis_period.to_json() if self.analysis_period else None return {'data_type': self.data_type.to_json(), 'unit': self.unit, 'analysis_period': a_per, 'metadata': self.metadata...
Return a header as a dictionary.
async def run(*cmd): """Run the given subprocess command in a coroutine. Args: *cmd: the command to run and its arguments. Returns: The output that the command wrote to stdout as a list of strings, one line per element (stderr output is piped to stdout). Raises: RuntimeError: if the command r...
Run the given subprocess command in a coroutine. Args: *cmd: the command to run and its arguments. Returns: The output that the command wrote to stdout as a list of strings, one line per element (stderr output is piped to stdout). Raises: RuntimeError: if the command returns a non-zero result.
def _get_color(self): """Return the color of the button, depending on its state""" if self.clicked and self.hovered: # the mouse is over the button color = mix(self.color, BLACK, 0.8) elif self.hovered and not self.flags & self.NO_HOVER: color = mix(self.color, BLACK, 0...
Return the color of the button, depending on its state
def do_add_signature(input_file, output_file, signature_file): """Add a signature to the MAR file.""" signature = open(signature_file, 'rb').read() if len(signature) == 256: hash_algo = 'sha1' elif len(signature) == 512: hash_algo = 'sha384' else: raise ValueError() with...
Add a signature to the MAR file.
def generate_by_deltas(cls, options, width, put_inner_lte_delta, call_inner_lte_delta): """ totally just playing around ideas for the API. this IC sells - credit put spread - credit call spread the approach - set width for the wing spr...
totally just playing around ideas for the API. this IC sells - credit put spread - credit call spread the approach - set width for the wing spread (eg, 1, ie, 1 unit width spread) - set delta for inner leg of the put credit spread (eg, -0.2) - set delta for inne...
def init_app(self, app): """ This callback can be used to initialize an application for the use with this prometheus reporter setup. This is usually used with a flask "app factory" configuration. Please see: http://flask.pocoo.org/docs/1.0/patterns/appfactories/ Note, t...
This callback can be used to initialize an application for the use with this prometheus reporter setup. This is usually used with a flask "app factory" configuration. Please see: http://flask.pocoo.org/docs/1.0/patterns/appfactories/ Note, that you need to use `PrometheusMetrics(app=No...
def load_plugins(): """ Load all availabe plugins. Returns ------- plugin_cls : dict mapping from plugin names to plugin classes """ plugin_cls = {} for entry_point in pkg_resources.iter_entry_points('docker_interface.plugins'): cl...
Load all availabe plugins. Returns ------- plugin_cls : dict mapping from plugin names to plugin classes
def save_raw_pickle(hwr_objects): """ Parameters ---------- hwr_objects : list of hwr objects """ converted_hwr = [] translate = {} translate_id = {} model_path = pkg_resources.resource_filename('hwrt', 'misc/') translation_csv = os.path.join(model_path, 'latex2writemathindex.cs...
Parameters ---------- hwr_objects : list of hwr objects
def convert(self): """Initiate one-shot conversion. The current settings are used, with the exception of continuous mode.""" c = self.config c &= (~MCP342x._continuous_mode_mask & 0x7f) # Force one-shot c |= MCP342x._not_ready_mask # Convert logger.debu...
Initiate one-shot conversion. The current settings are used, with the exception of continuous mode.
def has_no_checked_field(self, locator, **kwargs): """ Checks if the page or current node has no radio button or checkbox with the given label, value, or id that is currently checked. Args: locator (str): The label, name, or id of a checked field. **kwargs: Arbit...
Checks if the page or current node has no radio button or checkbox with the given label, value, or id that is currently checked. Args: locator (str): The label, name, or id of a checked field. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. Returns: ...
def set_value_all(self, twig=None, value=None, check_default=False, **kwargs): """ Set the value of all returned :class:`Parameter`s in this ParameterSet. Any :class:`Parameter` that would be included in the resulting ParameterSet from a :func:`filter` call with the same arguments will ...
Set the value of all returned :class:`Parameter`s in this ParameterSet. Any :class:`Parameter` that would be included in the resulting ParameterSet from a :func:`filter` call with the same arguments will have their value set. Note: setting the value of a Parameter in a ParameterSet WIL...
def get_event_attendee(self, id, attendee_id, **data): """ GET /events/:id/attendees/:attendee_id/ Returns a single :format:`attendee` by ID, as the key ``attendee``. """ return self.get("/events/{0}/attendees/{0}/".format(id,attendee_id), data=data)
GET /events/:id/attendees/:attendee_id/ Returns a single :format:`attendee` by ID, as the key ``attendee``.
def require_parents(packages): """ Exclude any apparent package that apparently doesn't include its parent. For example, exclude 'foo.bar' if 'foo' is not present. """ found = [] for pkg in packages: base, sep, child = pkg.rpartition('.') ...
Exclude any apparent package that apparently doesn't include its parent. For example, exclude 'foo.bar' if 'foo' is not present.