code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _query_mysql(self): """ Queries mysql and returns a cursor to the results. """ mysql = MySqlHook(mysql_conn_id=self.mysql_conn_id) conn = mysql.get_conn() cursor = conn.cursor() cursor.execute(self.sql) return cursor
Queries mysql and returns a cursor to the results.
def path(string): """ Define the 'path' data type that can be used by apps. """ if not os.path.exists(string): msg = "Path %s not found!" % string raise ArgumentTypeError(msg) return string
Define the 'path' data type that can be used by apps.
def add_arc(self, src, dst, char): """Adds a new Arc Args: src (int): The source state identifier dst (int): The destination state identifier char (str): The character for the transition Returns: None """ if src not in self.automato...
Adds a new Arc Args: src (int): The source state identifier dst (int): The destination state identifier char (str): The character for the transition Returns: None
def itertrain(self, train, valid=None, **kwargs): '''Train a model using a training and validation set. This method yields a series of monitor values to the caller. After every iteration, a pair of monitor dictionaries is generated: one evaluated on the training dataset, and another eva...
Train a model using a training and validation set. This method yields a series of monitor values to the caller. After every iteration, a pair of monitor dictionaries is generated: one evaluated on the training dataset, and another evaluated on the validation dataset. The validation moni...
def _resolve_dut_count(self): """ Calculates total amount of resources required and their types. :return: Nothing, modifies _dut_count, _hardware_count and _process_count :raises: ValueError if total count does not match counts of types separately. """ self._dut_...
Calculates total amount of resources required and their types. :return: Nothing, modifies _dut_count, _hardware_count and _process_count :raises: ValueError if total count does not match counts of types separately.
def assign_reads_to_otus(original_fasta, filtered_fasta, output_filepath=None, log_name="assign_reads_to_otus.log", perc_id_blast=0.97, global_alignment=True, HALT_EXEC=F...
Uses original fasta file, blasts to assign reads to filtered fasta original_fasta = filepath to original query fasta filtered_fasta = filepath to enumerated, filtered fasta output_filepath = output path to clusters (uc) file log_name = string specifying output log name perc_id_blast = percent ID fo...
def reverse(cls, value, prop, visitor): """Like :py:meth:`normalize.visitor.VisitorPattern.apply` but called for ``cast`` operations. The default implementation passes through but squashes exceptions, just like apply. """ return ( None if isinstance(value, (Attribute...
Like :py:meth:`normalize.visitor.VisitorPattern.apply` but called for ``cast`` operations. The default implementation passes through but squashes exceptions, just like apply.
def create(cls, currency, all_co_owner, description=None, daily_limit=None, overdraft_limit=None, alias=None, avatar_uuid=None, status=None, sub_status=None, reason=None, reason_description=None, notification_filters=None, setting=None, custom_headers=None): """ ...
:type user_id: int :param currency: The currency of the MonetaryAccountJoint as an ISO 4217 formatted currency code. :type currency: str :param all_co_owner: The users the account will be joint with. :type all_co_owner: list[object_.CoOwner] :param description: The descri...
def set_session_cache_mode(self, mode): """ Set the behavior of the session cache used by all connections using this Context. The previously set mode is returned. See :const:`SESS_CACHE_*` for details about particular modes. :param mode: One or more of the SESS_CACHE_* flags (...
Set the behavior of the session cache used by all connections using this Context. The previously set mode is returned. See :const:`SESS_CACHE_*` for details about particular modes. :param mode: One or more of the SESS_CACHE_* flags (combine using bitwise or) :returns: The ...
def create_manually(cls, validation_function_name, # type: str var_name, # type: str var_value, validation_outcome=None, # type: Any help_msg=None, # type: str ...
Creates an instance without using a Validator. This method is not the primary way that errors are created - they should rather created by the validation entry points. However it can be handy in rare edge cases. :param validation_function_name: :param var_name: :param var_value:...
def start(self): """ Start a concurrent operation. If we are below the limit, we increment the concurrency count and fire the deferred we return. If not, we add the deferred to the waiters list and return it unfired. """ # While the implemetation matches the desc...
Start a concurrent operation. If we are below the limit, we increment the concurrency count and fire the deferred we return. If not, we add the deferred to the waiters list and return it unfired.
def bytes2uuid(b): """ Return standard human-friendly UUID. """ if b.strip(chr(0)) == '': return None s = b.encode('hex') return "%s-%s-%s-%s-%s" % (s[0:8], s[8:12], s[12:16], s[16:20], s[20:])
Return standard human-friendly UUID.
def _get_input(self, length): """! @brief Extract requested amount of data from the read buffer.""" self._buffer_lock.acquire() try: if length == -1: actualLength = len(self._buffer) else: actualLength = min(length, len(self._buffer)) ...
! @brief Extract requested amount of data from the read buffer.
def get_asset_search_session(self, proxy): """Gets an asset search session. arg proxy (osid.proxy.Proxy): a proxy return: (osid.repository.AssetSearchSession) - an AssetSearchSession raise: OperationFailed - unable to complete request raise: Unimplemented -...
Gets an asset search session. arg proxy (osid.proxy.Proxy): a proxy return: (osid.repository.AssetSearchSession) - an AssetSearchSession raise: OperationFailed - unable to complete request raise: Unimplemented - supports_asset_search() is false compliance: ...
def zip_response(request, filename, files): """Return a Response object that is a zipfile with name filename. :param request: The request object. :param filename: The filename the browser should save the file as. :param files: A list of mappings between filenames (path/.../file) to file objects...
Return a Response object that is a zipfile with name filename. :param request: The request object. :param filename: The filename the browser should save the file as. :param files: A list of mappings between filenames (path/.../file) to file objects.
def max_layout_dimensions(dimensions): """ Take the maximum of a list of :class:`.LayoutDimension` instances. """ min_ = max([d.min for d in dimensions if d.min is not None]) max_ = max([d.max for d in dimensions if d.max is not None]) preferred = max([d.preferred for d in dimensions]) retu...
Take the maximum of a list of :class:`.LayoutDimension` instances.
def update_model_params(self, **params): r"""Update given model parameter if they are set to specific values""" for key, value in params.items(): if not hasattr(self, key): setattr(self, key, value) # set parameter for the first time. elif getattr(self, key) is N...
r"""Update given model parameter if they are set to specific values
def is_tagged(required_tags, has_tags): """Checks if tags match""" if not required_tags and not has_tags: return True elif not required_tags: return False found_tags = [] for tag in required_tags: if tag in has_tags: found_tags.append(tag) return len(found_t...
Checks if tags match
def from_json(value, **kwargs): """Convert a PNG Image from base64-encoded JSON""" if not value.startswith(PNG_PREAMBLE): raise ValueError('Not a valid base64-encoded PNG image') infile = BytesIO() rep = base64.b64decode(value[len(PNG_PREAMBLE):].encode('utf-8')) infi...
Convert a PNG Image from base64-encoded JSON
def diamond_functions(xx, yy, y_x0, x_y0): """ Method that creates two upper and lower functions based on points xx and yy as well as intercepts defined by y_x0 and x_y0. The resulting functions form kind of a distorted diamond-like structure aligned from point xx to point yy. Schematically : ...
Method that creates two upper and lower functions based on points xx and yy as well as intercepts defined by y_x0 and x_y0. The resulting functions form kind of a distorted diamond-like structure aligned from point xx to point yy. Schematically : xx is symbolized by x, yy is symbolized by y, y_x0 ...
def idPlayerResults(cfg, rawResult): """interpret standard rawResult for all players with known IDs""" result = {} knownPlayers = [] dictResult = {plyrRes.player_id : plyrRes.result for plyrRes in rawResult} for p in cfg.players: if p.playerID and p.playerID in dictResult: # identified playe...
interpret standard rawResult for all players with known IDs
def PositionedPhoneme(phoneme, word_initial = False, word_final = False, syllable_initial = False, syllable_final = False, env_start = False, env_end = False): ''' A decorator for phonemes, used in applying rules over words. Returns a copy of the input phoneme, with additional attributes, specifying whe...
A decorator for phonemes, used in applying rules over words. Returns a copy of the input phoneme, with additional attributes, specifying whether the phoneme occurs at a word or syllable boundary, or its position in an environment.
def start(self) -> None: """ Start the internal control loop. Potentially blocking, depending on the value of `_run_control_loop` set by the initializer. """ self._setup() if self._run_control_loop: asyncio.set_event_loop(asyncio.new_event_loop()) ...
Start the internal control loop. Potentially blocking, depending on the value of `_run_control_loop` set by the initializer.
def region(self): """ Get the region :class:`language_tags.Subtag.Subtag` of the tag. :return: region :class:`language_tags.Subtag.Subtag` that is part of the tag. The return can be None. """ region_item = [subtag for subtag in self.subtags if subtag.type == 'region...
Get the region :class:`language_tags.Subtag.Subtag` of the tag. :return: region :class:`language_tags.Subtag.Subtag` that is part of the tag. The return can be None.
def bluemix(cls, vcap_services, instance_name=None, service_name=None, **kwargs): """ Create a Cloudant session using a VCAP_SERVICES environment variable. :param vcap_services: VCAP_SERVICES environment variable :type vcap_services: dict or str :param str instance_name: Optiona...
Create a Cloudant session using a VCAP_SERVICES environment variable. :param vcap_services: VCAP_SERVICES environment variable :type vcap_services: dict or str :param str instance_name: Optional Bluemix instance name. Only required if multiple Cloudant instances are available. ...
def main(argv=None): """Generates documentation for signature generation pipeline""" parser = argparse.ArgumentParser(description=DESCRIPTION) parser.add_argument( 'pipeline', help='Python dotted path to rules pipeline to document' ) parser.add_argument('output', help='output file') ...
Generates documentation for signature generation pipeline
def mobile(self): """ Access the mobile :returns: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileList :rtype: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileList """ if self._mobile is None: self._mobile = MobileList(self._...
Access the mobile :returns: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileList :rtype: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileList
def get_context_data(self, **kwargs): """ Insert the form into the context dict. """ for key in self.get_form_class_keys(): kwargs['{}_form'.format(key)] = self.get_form(key) return super(FormMixin, self).get_context_data(**kwargs)
Insert the form into the context dict.
def _get_dx_tree(xy, degree): """ 0 1*(0, 0) 0 2*(1, 0) 1*(0, 1) 0 3*(2, 0) 2*(1, 1) 1*(0, 2) 0 ... ... ... ... """ x, y = xy # build smaller tree one = numpy.array([numpy.ones...
0 1*(0, 0) 0 2*(1, 0) 1*(0, 1) 0 3*(2, 0) 2*(1, 1) 1*(0, 2) 0 ... ... ... ...
def update_annotations(self): """Update annotations made by the user, including bookmarks and events. Depending on the settings, it might add the bookmarks to overview and traces. """ start_time = self.parent.overview.start_time if self.parent.notes.annot is None: ...
Update annotations made by the user, including bookmarks and events. Depending on the settings, it might add the bookmarks to overview and traces.
def run(cmd, printOutput=False, exceptionOnError=False, warningOnError=True, parseForRegEx=None, regExFlags=0, printOutputIfParsed=False, printErrorsIfParsed=False, exceptionIfParsed=False, dryrun=None): """Run cmd and return (status,output,parsedOutput). Unless dryrun is set Tr...
Run cmd and return (status,output,parsedOutput). Unless dryrun is set True, cmd is run using subprocess.Popen. It returns the exit status from cmd, its output, and any output found by searching for the regular expression parseForRegEx. cmd is logged at the debug level. The parameters are: cmd...
def is_fe_ready(self): '''Get FEI4 status of module. If FEI4 is not ready, resetting service records is necessary to bring the FEI4 to a defined state. Returns ------- value : bool True if FEI4 is ready, False if the FEI4 was powered up recently and is not ready. ''' with...
Get FEI4 status of module. If FEI4 is not ready, resetting service records is necessary to bring the FEI4 to a defined state. Returns ------- value : bool True if FEI4 is ready, False if the FEI4 was powered up recently and is not ready.
def to_yaml(cls, representer, node): """How to serialize this class back to yaml.""" return representer.represent_scalar(cls.yaml_tag, node.value)
How to serialize this class back to yaml.
def OnCut(self, event): """Clipboard cut event handler""" entry_line = \ self.main_window.entry_line_panel.entry_line_panel.entry_line if wx.Window.FindFocus() != entry_line: selection = self.main_window.grid.selection with undo.group(_("Cut")): ...
Clipboard cut event handler
def reset_caches(self, **kwargs): """ Called by ``__init__()`` to initialise the caches for a helper instance. It is also called by Django's ``setting_changed`` signal to clear the caches when changes to settings are made. Although it requires slightly more memory, separate dict...
Called by ``__init__()`` to initialise the caches for a helper instance. It is also called by Django's ``setting_changed`` signal to clear the caches when changes to settings are made. Although it requires slightly more memory, separate dictionaries are used for raw values, models, modu...
def to_list(self): """ Set the current encoder output to :class:`giraffez.Row` objects and returns the cursor. This is the default value so it is not necessary to select this unless the encoder settings have been changed already. """ self.conn.set_encoding(ROW_EN...
Set the current encoder output to :class:`giraffez.Row` objects and returns the cursor. This is the default value so it is not necessary to select this unless the encoder settings have been changed already.
def gitrepo(cwd): """Return hash of Git data that can be used to display more information to users. Example: "git": { "head": { "id": "5e837ce92220be64821128a70f6093f836dd2c05", "author_name": "Wil Gieseler", "author_email": "wil@example.c...
Return hash of Git data that can be used to display more information to users. Example: "git": { "head": { "id": "5e837ce92220be64821128a70f6093f836dd2c05", "author_name": "Wil Gieseler", "author_email": "wil@example.com", "com...
def patch_related_object_descriptor_caching(ro_descriptor): """ Patch SingleRelatedObjectDescriptor or ReverseSingleRelatedObjectDescriptor to use language-aware caching. """ class NewSingleObjectDescriptor(LanguageCacheSingleObjectDescriptor, ro_descriptor.__class__): pass if django.VE...
Patch SingleRelatedObjectDescriptor or ReverseSingleRelatedObjectDescriptor to use language-aware caching.
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the ProtocolVersion struct to a stream. Args: output_stream (stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStre...
Write the data encoding the ProtocolVersion struct to a stream. Args: output_stream (stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining th...
def unpack_scalar(cls, dataset, data): """ Given a dataset object and data in the appropriate format for the interface, return a simple scalar. """ if (len(data.data_vars) == 1 and len(data[dataset.vdims[0].name].shape) == 0): return data[dataset.vdims[0]....
Given a dataset object and data in the appropriate format for the interface, return a simple scalar.
def show_minimum_needs(self): """Show the minimum needs dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.minimum_needs.needs_calculator_dialog import ( NeedsCalculatorDialog ) dialog = NeedsCalculatorDialog(self.iface.mainWindow()) ...
Show the minimum needs dialog.
def append_child_field(self, linenum, indent, field_name, field_value): """ :param linenum: The line number of the frame. :type linenum: int :param indent: The indentation level of the frame. :type indent: int :param path: :type path: Path :param field_nam...
:param linenum: The line number of the frame. :type linenum: int :param indent: The indentation level of the frame. :type indent: int :param path: :type path: Path :param field_name: :type field_name: str :param field_value: :type field_value: str
def prsint(string): """ Parse a string as an integer, encapsulating error handling. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/prsint_c.html :param string: String representing an integer. :type string: str :return: Integer value obtained by parsing string. :rtype: int """ ...
Parse a string as an integer, encapsulating error handling. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/prsint_c.html :param string: String representing an integer. :type string: str :return: Integer value obtained by parsing string. :rtype: int
def expression(callable, rule_name, grammar): """Turn a plain callable into an Expression. The callable can be of this simple form:: def foo(text, pos): '''If this custom expression matches starting at text[pos], return the index where it stops matching. Otherwise, return None....
Turn a plain callable into an Expression. The callable can be of this simple form:: def foo(text, pos): '''If this custom expression matches starting at text[pos], return the index where it stops matching. Otherwise, return None.''' if the expression matched: ...
def taubin(script, iterations=10, t_lambda=0.5, t_mu=-0.53, selected=False): """ The lambda & mu Taubin smoothing, it make two steps of smoothing, forth and back, for each iteration. Based on: Gabriel Taubin "A signal processing approach to fair surface design" Siggraph 1995 Args: ...
The lambda & mu Taubin smoothing, it make two steps of smoothing, forth and back, for each iteration. Based on: Gabriel Taubin "A signal processing approach to fair surface design" Siggraph 1995 Args: script: the FilterScript object or script filename to write the filte...
def main(args=None): """Command line interface. :param list args: command line options (defaults to sys.argv) :returns: exit code :rtype: int """ parser = ArgumentParser( prog='baseline', description=DESCRIPTION) parser.add_argument( 'path', nargs='*', help...
Command line interface. :param list args: command line options (defaults to sys.argv) :returns: exit code :rtype: int
def load_xml(self, filepath): """Loads the values of the configuration variables from an XML path.""" from os import path import xml.etree.ElementTree as ET #Make sure the file exists and then import it as XML and read the values out. uxpath = path.expanduser(filepath) if...
Loads the values of the configuration variables from an XML path.
def _find_relations(self): """Find all relevant relation elements and return them in a list.""" # Get all extractions extractions = \ list(self.tree.execute("$.extractions[(@.@type is 'Extraction')]")) # Get relations from extractions relations = [] for e in ...
Find all relevant relation elements and return them in a list.
def from_credentials_db(client_secrets, storage, api_version="v3", readonly=False, http_client=None, ga_hook=None): """Create a client for a web or installed application. Create a client with a credentials stored in stagecraft db. Args: client_secrets: dict, client secrets ...
Create a client for a web or installed application. Create a client with a credentials stored in stagecraft db. Args: client_secrets: dict, client secrets (downloadable from Google API Console) storage: stagecraft.apps.collectors.libs.ga.CredentialStorage, ...
def tgt_vocab(self): """Target Vocabulary of the Dataset. Returns ------- tgt_vocab : Vocab Target vocabulary. """ if self._tgt_vocab is None: tgt_vocab_file_name, tgt_vocab_hash = \ self._data_file[self._pair_key]['vocab' + '_' + ...
Target Vocabulary of the Dataset. Returns ------- tgt_vocab : Vocab Target vocabulary.
def notifications(self): """ Access the notifications :returns: twilio.rest.notify.v1.service.notification.NotificationList :rtype: twilio.rest.notify.v1.service.notification.NotificationList """ if self._notifications is None: self._notifications = Notificat...
Access the notifications :returns: twilio.rest.notify.v1.service.notification.NotificationList :rtype: twilio.rest.notify.v1.service.notification.NotificationList
def file_arg(arg): """ Parses a file argument, i.e. starts with file:// """ prefix = 'file://' if arg.startswith(prefix): return os.path.abspath(arg[len(prefix):]) else: msg = 'Invalid file argument "{}", does not begin with "file://"' raise argparse.ArgumentTypeError(ms...
Parses a file argument, i.e. starts with file://
def serialize(self, data): """ Write a sequence of uniform hazard spectra to the specified file. :param data: Iterable of UHS data. Each datum must be an object with the following attributes: * imls: A sequence of Intensity Measure Levels * locat...
Write a sequence of uniform hazard spectra to the specified file. :param data: Iterable of UHS data. Each datum must be an object with the following attributes: * imls: A sequence of Intensity Measure Levels * location: An object representing the location of the...
def add_hash(self, value): """Add a Node based on a precomputed, hex encoded, hash value. """ self.leaves.append(Node(codecs.decode(value, 'hex_codec'), prehashed=True))
Add a Node based on a precomputed, hex encoded, hash value.
async def reply_voice(self, voice: typing.Union[base.InputFile, base.String], caption: typing.Union[base.String, None] = None, duration: typing.Union[base.Integer, None] = None, disable_notification: typing.Union[base.Boolean, None] = None, ...
Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document). Source: https://core.telegram.org/bots/api#sendvoi...
def send(self, data=None, headers=None, ttl=0, gcm_key=None, reg_id=None, content_encoding="aes128gcm", curl=False, timeout=None): """Encode and send the data to the Push Service. :param data: A serialized block of data (see encode() ). :type data: str :param headers: A dic...
Encode and send the data to the Push Service. :param data: A serialized block of data (see encode() ). :type data: str :param headers: A dictionary containing any additional HTTP headers. :type headers: dict :param ttl: The Time To Live in seconds for this message if the ...
def complete_io(self, iocb, msg): """Called by a handler to return data to the client.""" if _debug: IOController._debug("complete_io %r %r", iocb, msg) # if it completed, leave it alone if iocb.ioState == COMPLETED: pass # if it already aborted, leave it alone ...
Called by a handler to return data to the client.
def validate_units(self): """Ensure that wavelenth unit belongs to the correct class. There is no check for throughput because it is unitless. Raises ------ TypeError Wavelength unit is not `~pysynphot.units.WaveUnits`. """ if (not isinstance(self.wa...
Ensure that wavelenth unit belongs to the correct class. There is no check for throughput because it is unitless. Raises ------ TypeError Wavelength unit is not `~pysynphot.units.WaveUnits`.
def add_hook_sub(self, address, topics, callback): """Specify a *callback* in the same stream (thread) as the main receive loop. The callback will be called with the received messages from the specified subscription. Good for operations, which is required to be done in the same thread a...
Specify a *callback* in the same stream (thread) as the main receive loop. The callback will be called with the received messages from the specified subscription. Good for operations, which is required to be done in the same thread as the main recieve loop (e.q operations on the underly...
def start(self): """ Starts the watchdog timer. """ self._timer = Timer(self.time, self.handler) self._timer.daemon = True self._timer.start() return
Starts the watchdog timer.
def use_options(allowed): """ Decorator that logs warnings when unpermitted options are passed into its wrapped function. Requires that wrapped function has an keyword-only argument named `options`. If wrapped function has {options} in its docstring, fills in with the docs for allowed options. ...
Decorator that logs warnings when unpermitted options are passed into its wrapped function. Requires that wrapped function has an keyword-only argument named `options`. If wrapped function has {options} in its docstring, fills in with the docs for allowed options. Args: allowed (list str):...
def record_manifest(self): """ Returns a dictionary representing a serialized state of the service. """ data = super(RabbitMQSatchel, self).record_manifest() params = sorted(list(self.get_user_vhosts())) # [(user, password, vhost)] data['rabbitmq_all_site_vhosts'] = param...
Returns a dictionary representing a serialized state of the service.
def metadata(self, exportFormat="default", output=None, saveFolder=None, fileName=None): """ exports metadata to the various supported formats Inputs: exportFormats - export metadata to the following formats: fgdc, ...
exports metadata to the various supported formats Inputs: exportFormats - export metadata to the following formats: fgdc, inspire, iso19139, iso19139-3.2, iso19115, arcgis, and default. default means the value will be ISO 19139 Metadata Implementation Specification GML...
def create(cls, datacenter, memory, cores, ip_version, bandwidth, login, password, hostname, image, run, background, sshkey, size, vlan, ip, script, script_args, ssh): """Create a new virtual machine.""" from gandi.cli.modules.network import Ip, Iface if not backgro...
Create a new virtual machine.
def _get_core_keywords(skw_matches, ckw_matches, spires=False): """Return the output for the field codes. :var skw_matches: dict of {keyword: [info,...]} :var ckw_matches: dict of {keyword: [info,...]} :keyword spires: bool, to get the spires output :return: list of formatted core keywords """ ...
Return the output for the field codes. :var skw_matches: dict of {keyword: [info,...]} :var ckw_matches: dict of {keyword: [info,...]} :keyword spires: bool, to get the spires output :return: list of formatted core keywords
def _stub_obj(obj): ''' Stub an object directly. ''' # Annoying circular reference requires importing here. Would like to see # this cleaned up. @AW from .mock import Mock # Return an existing stub if isinstance(obj, Stub): return obj # If a Mock object, stub its __call__ ...
Stub an object directly.
def replicate(ctx, args): """Make node to be the slave of a master. """ slave = ClusterNode.from_uri(args.node) master = ClusterNode.from_uri(args.master) if not master.is_master(): ctx.abort("Node {!r} is not a master.".format(args.master)) try: slave.replicate(master.name) ...
Make node to be the slave of a master.
def map_structprop_resnums_to_seqprop_resnums(self, resnums, structprop=None, chain_id=None, seqprop=None, use_representatives=False): """Map a residue number in any StructProp + chain ID to any SeqProp's residue number. Args: resnums (int, ...
Map a residue number in any StructProp + chain ID to any SeqProp's residue number. Args: resnums (int, list): Residue numbers in the structure structprop (StructProp): StructProp object chain_id (str): Chain ID to map from seqprop (SeqProp): SeqProp object ...
def zipWithIndex(self): """ Zips this RDD with its element indices. The ordering is first based on the partition index and then the ordering of items within each partition. So the first item in the first partition gets index 0, and the last item in the last partition rec...
Zips this RDD with its element indices. The ordering is first based on the partition index and then the ordering of items within each partition. So the first item in the first partition gets index 0, and the last item in the last partition receives the largest index. This metho...
def infer_newX(self, Y_new, optimize=True): """ Infer X for the new observed data *Y_new*. :param Y_new: the new observed data for inference :type Y_new: numpy.ndarray :param optimize: whether to optimize the location of new X (True by default) :type optimize: boolean ...
Infer X for the new observed data *Y_new*. :param Y_new: the new observed data for inference :type Y_new: numpy.ndarray :param optimize: whether to optimize the location of new X (True by default) :type optimize: boolean :return: a tuple containing the posterior estimation of X ...
def parse_meta(content, meta_name, source_descr, content_attr_name="content"): """ Return list of strings parsed from `content` attribute from ``<meta>`` tags with given `meta_name`. """ dom = dhtmlparser.parseString(content) meta_tags = dom.find( "meta", fn=lambda x: x.params.g...
Return list of strings parsed from `content` attribute from ``<meta>`` tags with given `meta_name`.
def license_loader(lic_dir=LIC_DIR): """Loads licenses from the given directory.""" lics = [] for ln in os.listdir(lic_dir): lp = os.path.join(lic_dir, ln) with open(lp) as lf: txt = lf.read() lic = License(txt) lics.append(lic) return lics
Loads licenses from the given directory.
def formatted_filters(self): """ Cache and return filters as a comprehensive WQL clause. """ if not self._formatted_filters: filters = deepcopy(self.filters) self._formatted_filters = self._format_filter(filters, self._and_props) return self._formatted_fil...
Cache and return filters as a comprehensive WQL clause.
def to_json_file(graph: BELGraph, file: TextIO, **kwargs) -> None: """Write this graph as Node-Link JSON to a file.""" graph_json_dict = to_json(graph) json.dump(graph_json_dict, file, ensure_ascii=False, **kwargs)
Write this graph as Node-Link JSON to a file.
def _headers(self): """Ensure the Authorization Header has a valid Access Token.""" if not self.access_token or not self.access_token_expires: self._basic_login() elif datetime.now() > self.access_token_expires - timedelta(seconds=30): self._basic_login() return...
Ensure the Authorization Header has a valid Access Token.
def nodeids(self, ivs=None, quantifier=None): """ Return the list of nodeids given by *ivs*, or all nodeids. Args: ivs: the intrinsic variables of the predications to select; if `None`, return all nodeids (but see *quantifier*) quantifier: if `True`, only...
Return the list of nodeids given by *ivs*, or all nodeids. Args: ivs: the intrinsic variables of the predications to select; if `None`, return all nodeids (but see *quantifier*) quantifier: if `True`, only return nodeids of quantifiers; if `False`, only r...
def rados_df(self, host_list=None, remote_user=None, remote_pass=None): ''' Invoked the rados df command and return output to user ''' result, failed_hosts = self.runner.ansible_perform_operation( host_list=host_list, ...
Invoked the rados df command and return output to user
def validate(self, options): """ Validate the options or exit() """ try: codecs.getencoder(options.char_encoding) except LookupError: self.parser.error("invalid 'char-encoding' %s" % options.char_encoding)
Validate the options or exit()
def _read_http_settings(self, size, kind, flag): """Read HTTP/2 SETTINGS frames. Structure of HTTP/2 SETTINGS frame [RFC 7540]: +-----------------------------------------------+ | Length (24) | +---------------+---------------+------...
Read HTTP/2 SETTINGS frames. Structure of HTTP/2 SETTINGS frame [RFC 7540]: +-----------------------------------------------+ | Length (24) | +---------------+---------------+---------------+ | Type (8) | Flags (8) | ...
def access_storage_list(**kwargs): """ Shows collections with ACL. """ ctx = Context(**kwargs) ctx.execute_action('access:storage:list', **{ 'storage': ctx.repo.create_secure_service('storage'), })
Shows collections with ACL.
def get_current_thread_id(thread): ''' Note: the difference from get_current_thread_id to get_thread_id is that for the current thread we can get the thread id while the thread.ident is still not set in the Thread instance. ''' try: # Fast path without getting lock. tid = thread....
Note: the difference from get_current_thread_id to get_thread_id is that for the current thread we can get the thread id while the thread.ident is still not set in the Thread instance.
def metadata_and_cell_to_header(notebook, metadata, text_format, ext): """ Return the text header corresponding to a notebook, and remove the first cell of the notebook if it contained the header """ header = [] lines_to_next_cell = None if notebook.cells: cell = notebook.cells[0] ...
Return the text header corresponding to a notebook, and remove the first cell of the notebook if it contained the header
def destroy(self, request, pk=None, parent_lookup_organization=None): '''Remove a user from an organization.''' user = get_object_or_404(User, pk=pk) org = get_object_or_404( SeedOrganization, pk=parent_lookup_organization) self.check_object_permissions(request, org) ...
Remove a user from an organization.
def frequency(self, mapping): """ Returns frequency of a given :class:`caspo.core.mapping.Mapping` Parameters ---------- mapping : :class:`caspo.core.mapping.Mapping` A logical conjuntion mapping Returns ------- float Frequency of...
Returns frequency of a given :class:`caspo.core.mapping.Mapping` Parameters ---------- mapping : :class:`caspo.core.mapping.Mapping` A logical conjuntion mapping Returns ------- float Frequency of the given mapping over all logical networks ...
def err(r): """ Input: { return - return code error - error text } Output: Nothing; quits program """ import sys rc=r['return'] re=r['error'] out('Error: '+re) sys.exit(rc)
Input: { return - return code error - error text } Output: Nothing; quits program
def _gen_form_data(self) -> multipart.MultipartWriter: """Encode a list of fields using the multipart/form-data MIME format""" for dispparams, headers, value in self._fields: try: if hdrs.CONTENT_TYPE in headers: part = payload.get_payload( ...
Encode a list of fields using the multipart/form-data MIME format
def write_outro (self): """Write outro comments.""" self.stoptime = time.time() duration = self.stoptime - self.starttime self.comment(_("Stopped checking at %(time)s (%(duration)s)") % {"time": strformat.strtime(self.stoptime), "duration": strformat.strduratio...
Write outro comments.
def member_ids(self): """Members of this group.""" info = self.raw.get(ATTR_MEMBERS, {}) if not info or ROOT_DEVICES2 not in info: return [] return info[ROOT_DEVICES2].get(ATTR_ID, [])
Members of this group.
def guess_depth(self, root_dir): """ Try to guess the depth of a directory repository (i.e. whether it has sub-folders for multiple subjects or visits, depending on where files and/or derived label files are found in the hierarchy of sub-directories under the root dir. P...
Try to guess the depth of a directory repository (i.e. whether it has sub-folders for multiple subjects or visits, depending on where files and/or derived label files are found in the hierarchy of sub-directories under the root dir. Parameters ---------- root_dir : str ...
def astype(self, dtype): """Returns a view that does on the fly type conversion of the underlying data. Parameters ---------- dtype : string or dtype NumPy dtype. Notes ----- This method returns a new Array object which is a view on the same ...
Returns a view that does on the fly type conversion of the underlying data. Parameters ---------- dtype : string or dtype NumPy dtype. Notes ----- This method returns a new Array object which is a view on the same underlying chunk data. Modifying any...
def _plot_connectivity_helper(self, ii, ji, mat_datai, data, lims=[1, 8]): """ A debug function used to plot the adjacency/connectivity matrix. """ from matplotlib.pyplot import quiver, colorbar, clim, matshow I = ~np.isnan(mat_datai) & (ji != -1) & (mat_datai >= 0) mat_...
A debug function used to plot the adjacency/connectivity matrix.
def clone_g0_inputs_on_ngpus(self, inputs, outputs, g0_inputs): """ Clone variables unused by the attack on all GPUs. Specifically, the ground-truth label, y, has to be preserved until the training step. :param inputs: A list of dictionaries as the inputs to each step. :param outputs: A list of dic...
Clone variables unused by the attack on all GPUs. Specifically, the ground-truth label, y, has to be preserved until the training step. :param inputs: A list of dictionaries as the inputs to each step. :param outputs: A list of dictionaries as the outputs of each step. :param g0_inputs: Initial variabl...
def bit_size(self): """ :return: The bit size of the private key, as an integer """ if self._bit_size is None: if self.algorithm == 'rsa': prime = self['private_key'].parsed['modulus'].native elif self.algorithm == 'dsa': ...
:return: The bit size of the private key, as an integer
def destroy_list(self, list_id): """ Destroy a list :param list_id: list ID number :return: The destroyed list object :rtype: :class:`~responsebot.models.List` """ return List(tweepy_list_to_json(self._client.destroy_list(list_id=list_id)))
Destroy a list :param list_id: list ID number :return: The destroyed list object :rtype: :class:`~responsebot.models.List`
def _compose_restart(services): """Well, this is annoying. Compose 1.2 shipped with the restart functionality fucking broken, so we can't set a faster timeout than 10 seconds (which is way too long) using Compose. We are therefore resigned to trying to hack this together ourselves. Lame. Releva...
Well, this is annoying. Compose 1.2 shipped with the restart functionality fucking broken, so we can't set a faster timeout than 10 seconds (which is way too long) using Compose. We are therefore resigned to trying to hack this together ourselves. Lame. Relevant fix which will make it into the next...
def pmbb(self,*args,**kwargs): """ NAME: pmbb PURPOSE: return proper motion in Galactic latitude (in mas/yr) INPUT: t - (optional) time at which to get pmbb (can be Quantity) obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of obse...
NAME: pmbb PURPOSE: return proper motion in Galactic latitude (in mas/yr) INPUT: t - (optional) time at which to get pmbb (can be Quantity) obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of observer in the Galactocentri...
def _pull_and_tag_image(self, image, build_json, nonce): """Docker pull the image and tag it uniquely for use by this build""" image = image.copy() first_library_exc = None for _ in range(20): # retry until pull and tag is successful or definitively fails. # shoul...
Docker pull the image and tag it uniquely for use by this build
def html2md(html_string): """ Convert a string or html file to a markdown table string. Parameters ---------- html_string : str Either the html string, or the filepath to the html Returns ------- str The html table converted to a Markdown table Notes ----- ...
Convert a string or html file to a markdown table string. Parameters ---------- html_string : str Either the html string, or the filepath to the html Returns ------- str The html table converted to a Markdown table Notes ----- This function requires BeautifulSoup_ ...
def sizeof(s): """ Return the size of an object when packed """ if hasattr(s, '_size_'): return s._size_ elif isinstance(s, bytes): return len(s) raise ValueError(s)
Return the size of an object when packed
def isDirect(self): """Test if the message is a direct message type.""" direct = (self._messageType == 0x00) if self.isDirectACK or self.isDirectNAK: direct = True return direct
Test if the message is a direct message type.