positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def restore_configuration_files(self): """ restore a previously saved postgresql.conf """ try: for f in self._configuration_to_save: config_file = os.path.join(self._config_dir, f) backup_file = os.path.join(self._data_dir, f + '.backup') if no...
restore a previously saved postgresql.conf
def remove(self, bw): """ Removes a buffer watch identifier. @type bw: L{BufferWatch} @param bw: Buffer watch identifier. @raise KeyError: The buffer watch identifier was already removed. """ try: self.__ranges.remove(bw) except ...
Removes a buffer watch identifier. @type bw: L{BufferWatch} @param bw: Buffer watch identifier. @raise KeyError: The buffer watch identifier was already removed.
def setup_foreground_minifollowups(workflow, coinc_file, single_triggers, tmpltbank_file, insp_segs, insp_data_name, insp_anal_name, dax_output, out_dir, tags=None): """ Create plots that followup the Nth loudest coincident injection from a statmap produced HDF file...
Create plots that followup the Nth loudest coincident injection from a statmap produced HDF file. Parameters ---------- workflow: pycbc.workflow.Workflow The core workflow instance we are populating coinc_file: single_triggers: list of pycbc.workflow.File A list cointaining the ...
def StringIO(*args, **kwargs): """StringIO constructor shim for the async wrapper.""" raw = sync_io.StringIO(*args, **kwargs) return AsyncStringIOWrapper(raw)
StringIO constructor shim for the async wrapper.
def _check_if_must_download(request_list, redownload): """ Updates request.will_download attribute of each request in request_list. **Note:** the function mutates the elements of the list! :param request_list: a list of ``DownloadRequest`` instances :type: list[DownloadRequest] :param redownlo...
Updates request.will_download attribute of each request in request_list. **Note:** the function mutates the elements of the list! :param request_list: a list of ``DownloadRequest`` instances :type: list[DownloadRequest] :param redownload: tells whether to download the data again or not :type: bool
def fit_freq_min_max(self, training_signal): """Defines a spectral mask based on training data using min and max values of each frequency component Args: training_signal: Training data """ window_length = len(self.window) window_weight = sum(...
Defines a spectral mask based on training data using min and max values of each frequency component Args: training_signal: Training data
def create_snapshot(self, xml_bytes): """Parse the XML returned by the C{CreateSnapshot} function. @param xml_bytes: XML bytes with a C{CreateSnapshotResponse} root element. @return: The L{Snapshot} instance created. TODO: ownerId, volumeSize, description. """ ...
Parse the XML returned by the C{CreateSnapshot} function. @param xml_bytes: XML bytes with a C{CreateSnapshotResponse} root element. @return: The L{Snapshot} instance created. TODO: ownerId, volumeSize, description.
def add_sample(self, name, labels, value, timestamp=None, exemplar=None): """Add a sample to the metric. Internal-only, do not use.""" self.samples.append(Sample(name, labels, value, timestamp, exemplar))
Add a sample to the metric. Internal-only, do not use.
def _make_field_info(self, field_name, field): """ Create the information that the template needs to render a form field for this field. """ supported_field_types = ( (Integer, 'integer'), (Float, 'float'), (Boolean, 'boolean'), (String, 's...
Create the information that the template needs to render a form field for this field.
def list_flavors(self, retrieve_all=True, **_params): """Fetches a list of all Neutron service flavors for a project.""" return self.list('flavors', self.flavors_path, retrieve_all, **_params)
Fetches a list of all Neutron service flavors for a project.
def gene_coordinates(host, org, gene, chr_exclude=[]) -> pd.DataFrame: """Retrieve gene coordinates for specific organism through BioMart. Parameters ---------- host : {{'www.ensembl.org', ...}} A valid BioMart host URL. Can be used to control genome build. org : {{'hsapiens', 'mmusculus', '...
Retrieve gene coordinates for specific organism through BioMart. Parameters ---------- host : {{'www.ensembl.org', ...}} A valid BioMart host URL. Can be used to control genome build. org : {{'hsapiens', 'mmusculus', 'drerio'}} Organism to query. Currently available are human ('hsapiens'...
def copy_config(self, original, new): ''' Copies collection configs into a new folder. Can be used to create new collections based on existing configs. Basically, copies all nodes under /configs/original to /configs/new. :param original str: ZK name of original config :param n...
Copies collection configs into a new folder. Can be used to create new collections based on existing configs. Basically, copies all nodes under /configs/original to /configs/new. :param original str: ZK name of original config :param new str: New name of the ZK config.
def email(value, allow_empty = False, **kwargs): """Validate that ``value`` is a valid email address. .. note:: Email address validation is...complicated. The methodology that we have adopted here is *generally* compliant with `RFC 5322 <https://tools.ietf.org/html/rfc532...
Validate that ``value`` is a valid email address. .. note:: Email address validation is...complicated. The methodology that we have adopted here is *generally* compliant with `RFC 5322 <https://tools.ietf.org/html/rfc5322>`_ and uses a combination of string parsing and regular expressions....
def _follow_link(self, value): '''Returns given `value` or, if it is a symlink, the `value` it names.''' seen_keys = set() while True: link_key = self._link_for_value(value) if not link_key: return value assert link_key not in seen_keys, 'circular symlink reference' seen_key...
Returns given `value` or, if it is a symlink, the `value` it names.
def quote_string_if_needed(arg: str) -> str: """ Quotes a string if it contains spaces and isn't already quoted """ if is_quoted(arg) or ' ' not in arg: return arg if '"' in arg: quote = "'" else: quote = '"' return quote + arg + quote
Quotes a string if it contains spaces and isn't already quoted
def PDFEmitter(target, source, env): """Strips any .aux or .log files from the input source list. These are created by the TeX Builder that in all likelihood was used to generate the .dvi file we're using as input, and we only care about the .dvi file. """ def strip_suffixes(n): return n...
Strips any .aux or .log files from the input source list. These are created by the TeX Builder that in all likelihood was used to generate the .dvi file we're using as input, and we only care about the .dvi file.
def pull_en_words() -> None: """ Fetches a repository containing English words. """ ENGLISH_WORDS_URL = "https://github.com/dwyl/english-words.git" en_words_path = Path(config.EN_WORDS_PATH) if not en_words_path.is_file(): subprocess.run(["git", "clone", ENGLISH_WORDS_UR...
Fetches a repository containing English words.
def map_indices_parent2child(child, parent_indices): """Map parent RTDCBase event indices to RTDC_Hierarchy Parameters ---------- parent: RTDC_Hierarchy hierarchy child parent_indices: 1d ndarray hierarchy parent (`child.hparent`) indices to map Returns ------- child_in...
Map parent RTDCBase event indices to RTDC_Hierarchy Parameters ---------- parent: RTDC_Hierarchy hierarchy child parent_indices: 1d ndarray hierarchy parent (`child.hparent`) indices to map Returns ------- child_indices: 1d ndarray child indices
def atlasdb_init( path, zonefile_dir, db, peer_seeds, peer_blacklist, recover=False, validate=False): """ Set up the atlas node: * create the db if it doesn't exist * go through all the names and verify that we have the *current* zonefiles * if we don't, queue them for fetching. * set up the pee...
Set up the atlas node: * create the db if it doesn't exist * go through all the names and verify that we have the *current* zonefiles * if we don't, queue them for fetching. * set up the peer db @db should be an instance of BlockstackDB @initial_peers should be a list of URLs Return the ne...
def validateState(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None, returnStateName=False): """Raises ValidationException if value is not a USA state. Returns the capitalized state abbreviation, unless returnStateName is True in which case it returns the titlecased s...
Raises ValidationException if value is not a USA state. Returns the capitalized state abbreviation, unless returnStateName is True in which case it returns the titlecased state name. * value (str): The value being validated as an email address. * blank (bool): If True, a blank string will be accepted....
def WaitForFlow(flow_urn, token=None, timeout=DEFAULT_TIMEOUT, max_sleep_time=1, min_sleep_time=0.2, dampening_multiplier=0.9): """Waits for a flow to finish, polling while we wait. Args: flow_urn: The urn of the flow to wait for. ...
Waits for a flow to finish, polling while we wait. Args: flow_urn: The urn of the flow to wait for. token: The datastore access token. timeout: How long to wait before giving up, usually because the client has gone away. max_sleep_time: The initial and longest time to wait in between polls. ...
def combine_first(self, other): """ Update null elements with value in the same location in `other`. Combine two DataFrame objects by filling null values in one DataFrame with non-null values from other DataFrame. The row and column indexes of the resulting DataFrame will be the...
Update null elements with value in the same location in `other`. Combine two DataFrame objects by filling null values in one DataFrame with non-null values from other DataFrame. The row and column indexes of the resulting DataFrame will be the union of the two. Parameters -----...
def create_container(self, conf, detach, tty): """Create a single container""" name = conf.name image_name = conf.image_name if conf.tag is not NotSpecified: image_name = conf.image_name_with_tag container_name = conf.container_name with conf.assumed_role():...
Create a single container
def img2wav(path, min_x, max_x, min_y, max_y, window_size=3): """Generate 1-D data ``y=f(x)`` from a black/white image. Suppose we have an image like that: .. image:: images/waveform.png :align: center Put some codes:: >>> from weatherlab.math.img2waveform import img2wav >>> ...
Generate 1-D data ``y=f(x)`` from a black/white image. Suppose we have an image like that: .. image:: images/waveform.png :align: center Put some codes:: >>> from weatherlab.math.img2waveform import img2wav >>> import matplotlib.pyplot as plt >>> x, y = img2wav(r"testdata...
def pformat(self, consumed_capacity=None): """ Pretty format for insertion into table pformat """ consumed_capacity = consumed_capacity or {} lines = [] parts = ["GLOBAL", self.index_type, "INDEX", self.name] if self.status != "ACTIVE": parts.insert(0, "[%s]" % self.s...
Pretty format for insertion into table pformat
async def cities(self, country: str, state: str) -> list: """Return a list of supported cities in a country/state.""" data = await self._request( 'get', 'cities', params={ 'state': state, 'country': country }) return [d['city'] for d in dat...
Return a list of supported cities in a country/state.
def get_objective_bank_lookup_session(self, *args, **kwargs): """Gets the OsidSession associated with the objective bank lookup service. return: (osid.learning.ObjectiveBankLookupSession) - an ObjectiveBankLookupSession raise: OperationFailed - unable to complete reques...
Gets the OsidSession associated with the objective bank lookup service. return: (osid.learning.ObjectiveBankLookupSession) - an ObjectiveBankLookupSession raise: OperationFailed - unable to complete request raise: Unimplemented - supports_objective_bank_lookup() is ...
def tajima_d(ac, pos=None, start=None, stop=None, min_sites=3): """Calculate the value of Tajima's D over a given region. Parameters ---------- ac : array_like, int, shape (n_variants, n_alleles) Allele counts array. pos : array_like, int, shape (n_items,), optional Variant position...
Calculate the value of Tajima's D over a given region. Parameters ---------- ac : array_like, int, shape (n_variants, n_alleles) Allele counts array. pos : array_like, int, shape (n_items,), optional Variant positions, using 1-based coordinates, in ascending order. start : int, opti...
def clean_by_request(self, request): ''' Remove all futures that were waiting for request `request` since it is done waiting ''' if request not in self.request_map: return for tag, matcher, future in self.request_map[request]: # timeout the future ...
Remove all futures that were waiting for request `request` since it is done waiting
def _get_signed_predecessors(im, node, polarity): """Get upstream nodes in the influence map. Return the upstream nodes along with the overall polarity of the path to that node by account for the polarity of the path to the given node and the polarity of the edge between the given node and its immediat...
Get upstream nodes in the influence map. Return the upstream nodes along with the overall polarity of the path to that node by account for the polarity of the path to the given node and the polarity of the edge between the given node and its immediate predecessors. Parameters ---------- im...
def __get_switch_arr(work_sheet, row_num): ''' if valud of the column of the row is `1`, it will be added to the array. ''' u_dic = [] for col_idx in FILTER_COLUMNS: cell_val = work_sheet['{0}{1}'.format(col_idx, row_num)].value if cell_val in [1, '1']: # Appending the ...
if valud of the column of the row is `1`, it will be added to the array.
def add_node(self, name, desc, layout, node_x, node_y): """ Add a node to a network. """ existing_node = get_session().query(Node).filter(Node.name==name, Node.network_id==self.id).first() if existing_node is not None: raise HydraError("A node with name %s is alre...
Add a node to a network.
def detect(filename, include_confidence=False): """ Detect the encoding of a file. Returns only the predicted current encoding as a string. If `include_confidence` is True, Returns tuple containing: (str encoding, float confidence) """ f = open(filename) detection = chardet.detect(f.r...
Detect the encoding of a file. Returns only the predicted current encoding as a string. If `include_confidence` is True, Returns tuple containing: (str encoding, float confidence)
def call_for_each_tower(self, tower_fn): """ Call the function `tower_fn` under :class:`TowerContext` for each tower. Returns: a list, contains the return values of `tower_fn` on each tower. """ ps_device = 'cpu' if len(self.towers) >= 4 else 'gpu' raw_devic...
Call the function `tower_fn` under :class:`TowerContext` for each tower. Returns: a list, contains the return values of `tower_fn` on each tower.
def source(self, format='xml', accessible=False): """ Args: format (str): only 'xml' and 'json' source types are supported accessible (bool): when set to true, format is always 'json' """ if accessible: return self.http.get('/wda/accessibleSource').val...
Args: format (str): only 'xml' and 'json' source types are supported accessible (bool): when set to true, format is always 'json'
def find_layer_idx(model, layer_name): """Looks up the layer index corresponding to `layer_name` from `model`. Args: model: The `keras.models.Model` instance. layer_name: The name of the layer to lookup. Returns: The layer index if found. Raises an exception otherwise. """ ...
Looks up the layer index corresponding to `layer_name` from `model`. Args: model: The `keras.models.Model` instance. layer_name: The name of the layer to lookup. Returns: The layer index if found. Raises an exception otherwise.
def create_dcnm_in_nwk(self, tenant_id, fw_dict, is_fw_virt=False): """Create the DCNM In Network and store the result in DB. """ tenant_name = fw_dict.get('tenant_name') ret = self._create_service_nwk(tenant_id, tenant_name, 'in') if ret: res = fw_const.DCNM_IN_NETWORK_CREAT...
Create the DCNM In Network and store the result in DB.
def list_knowledge_bases(project_id): """Lists the Knowledge bases belonging to a project. Args: project_id: The GCP project linked with the agent.""" import dialogflow_v2beta1 as dialogflow client = dialogflow.KnowledgeBasesClient() project_path = client.project_path(project_id) print...
Lists the Knowledge bases belonging to a project. Args: project_id: The GCP project linked with the agent.
def _is_viable_phone_number(number): """Checks to see if a string could possibly be a phone number. At the moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation commonly found in phone numbers. This method does not require the number to be normalized in advance ...
Checks to see if a string could possibly be a phone number. At the moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation commonly found in phone numbers. This method does not require the number to be normalized in advance - but does assume that leading non-numbe...
def with_wrapper(self, wrapper=None, name=None): """ Copy this BarSet, and return a new BarSet with the specified name and wrapper. If no name is given, `{self.name}_custom_wrapper` is used. If no wrapper is given, the new BarSet will have no wrapper. """ name...
Copy this BarSet, and return a new BarSet with the specified name and wrapper. If no name is given, `{self.name}_custom_wrapper` is used. If no wrapper is given, the new BarSet will have no wrapper.
def _process_response(self, response, marker_elems=None): """ Helper to process the xml response from AWS """ body = response.read() #print body if '<Errors>' not in body: rs = ResultSet(marker_elems) h = handler.XmlHandler(rs, self) xm...
Helper to process the xml response from AWS
def add_vcenter(self, **kwargs): """ Add vCenter on the switch Args: id(str) : Name of an established vCenter url (bool) : vCenter URL username (str): Username of the vCenter password (str): Password of the vCenter callback (function):...
Add vCenter on the switch Args: id(str) : Name of an established vCenter url (bool) : vCenter URL username (str): Username of the vCenter password (str): Password of the vCenter callback (function): A function executed upon completion of the ...
def list_tags(self, pattern=None): """ List all tags made on this project. :param pattern: filters the starting letters of the return value :return: """ request_url = "{}tags".format(self.create_basic_url()) params = None if pattern: params = ...
List all tags made on this project. :param pattern: filters the starting letters of the return value :return:
def _send_request(url_id, data=None, json=None, req_type=None): """ Send request to Seeder's API. Args: url_id (str): ID used as identification in Seeder. data (obj, default None): Optional parameter for data. json (obj, default None): Optional parameter for JSON body. req_t...
Send request to Seeder's API. Args: url_id (str): ID used as identification in Seeder. data (obj, default None): Optional parameter for data. json (obj, default None): Optional parameter for JSON body. req_type (fn, default None): Request method used to send/download the ...
def _is_possible_loh(rec, vcf_rec, params, somatic_info, use_status=False, max_normal_depth=None): """Check if the VCF record is a het in the normal with sufficient support. Only returns SNPs, since indels tend to have less precise frequency measurements. """ if _is_biallelic_snp(rec) and _passes_plus_...
Check if the VCF record is a het in the normal with sufficient support. Only returns SNPs, since indels tend to have less precise frequency measurements.
def _auto_unlock_key_position(self): """Find the open sesame password in the default keyring """ found_pos = None default_keyring_ids = gkr.list_item_ids_sync(self.default_keyring) for pos in default_keyring_ids: item_attrs = gkr.item_get_attributes_sync(self.default_...
Find the open sesame password in the default keyring
def namedb_get_names_owned_by_address( cur, address, current_block ): """ Get the list of non-expired, non-revoked names owned by an address. Only works if there is a *singular* address for the name. """ unexpired_fragment, unexpired_args = namedb_select_where_unexpired_names( current_block ) ...
Get the list of non-expired, non-revoked names owned by an address. Only works if there is a *singular* address for the name.
def from_string(cls, string, relpath=None, encoding=None, is_sass=None): """Read Sass source from the contents of a string. The origin is always None. `relpath` defaults to "string:...". """ if isinstance(string, six.text_type): # Already decoded; we don't know what encodin...
Read Sass source from the contents of a string. The origin is always None. `relpath` defaults to "string:...".
def calculate_token(self, text, seed=None): """ Calculate the request token (`tk`) of a string :param text: str The text to calculate a token for :param seed: str The seed to use. By default this is the number of hours since epoch """ if seed is None: seed = self._ge...
Calculate the request token (`tk`) of a string :param text: str The text to calculate a token for :param seed: str The seed to use. By default this is the number of hours since epoch
def open(self): """ Open the Sender using the supplied conneciton. If the handler has previously been redirected, the redirect context will be used to create a new handler before opening it. :param connection: The underlying client shared connection. :type: connection: ~...
Open the Sender using the supplied conneciton. If the handler has previously been redirected, the redirect context will be used to create a new handler before opening it. :param connection: The underlying client shared connection. :type: connection: ~uamqp.connection.Connection
def set_attributes_all(target, attributes, discard_others=True): """ Set Attributes in bulk and optionally discard others. Sets each Attribute in turn (modifying it in place if possible if it is already present) and optionally discarding all other Attributes not explicitly set. This function yields muc...
Set Attributes in bulk and optionally discard others. Sets each Attribute in turn (modifying it in place if possible if it is already present) and optionally discarding all other Attributes not explicitly set. This function yields much greater performance than the required individual calls to ``set_att...
def complete_delivery_note(self, delivery_note_id, complete_dict): """ Completes an delivery note :param complete_dict: the complete dict with the template id :param delivery_note_id: the delivery note id :return: Response """ return self._create_put_request( ...
Completes an delivery note :param complete_dict: the complete dict with the template id :param delivery_note_id: the delivery note id :return: Response
def _dates(p_word_before_cursor): """ Generator for date completion. """ to_absolute = lambda s: relative_date_to_date(s).isoformat() start_value_pos = p_word_before_cursor.find(':') + 1 value = p_word_before_cursor[start_value_pos:] for reldate in date_suggestions(): if not reldate.starts...
Generator for date completion.
def copy(self): """Create a shallow copy of the sorted set.""" return self._fromset(set(self._set), key=self._key)
Create a shallow copy of the sorted set.
def call_func(self, *args, **kwargs): """Called. Take care of exceptions using gather""" asyncio.gather( self.cron(*args, **kwargs), loop=self.loop, return_exceptions=True ).add_done_callback(self.set_result)
Called. Take care of exceptions using gather
def reduce_by(fn: Callable[[T1, T1], T1]) -> Callable[[ActualIterable[T1]], T1]: """ >>> from Redy.Collections import Traversal, Flow >>> def mul(a: int, b: int): return a * b >>> lst: Iterable[int] = [1, 2, 3] >>> x = Flow(lst)[Traversal.reduce_by(mul)].unbox >>> assert x is 6 """ retur...
>>> from Redy.Collections import Traversal, Flow >>> def mul(a: int, b: int): return a * b >>> lst: Iterable[int] = [1, 2, 3] >>> x = Flow(lst)[Traversal.reduce_by(mul)].unbox >>> assert x is 6
def from_string(cls, s): """ Init a new object from a string. Args: s (string): raw email Returns: Instance of MailParser """ log.debug("Parsing email from string") message = email.message_from_string(s) return cls(message)
Init a new object from a string. Args: s (string): raw email Returns: Instance of MailParser
def boundingbox(self): """Compute the bounding box of the compound. Returns ------- mb.Box The bounding box for this Compound """ xyz = self.xyz return Box(mins=xyz.min(axis=0), maxs=xyz.max(axis=0))
Compute the bounding box of the compound. Returns ------- mb.Box The bounding box for this Compound
def decode_async_options(options): """Decode Async options from JSON decoding.""" async_options = copy.deepcopy(options) # JSON don't like datetimes. eta = async_options.get('task_args', {}).get('eta') if eta: from datetime import datetime async_options['task_args']['eta'] = dateti...
Decode Async options from JSON decoding.
def findNodeById( self, objectId ): """ Looks up the node based on the unique node identifier. :param nodeId """ for item in self.items(): if ( isinstance(item, XNode) and item.objectId() == objectId): return item return None
Looks up the node based on the unique node identifier. :param nodeId
def stop_recording(self): """Stop recording from the audio source.""" self._stop_recording.set() with self._source_lock: self._source.stop() self._recording = False
Stop recording from the audio source.
def keyPressEvent( self, event ): """ Looks for the Esc key to close the popup. :param event | <QKeyEvent> """ if ( event.key() == Qt.Key_Escape ): self.reject() event.accept() return elif ( event.key()...
Looks for the Esc key to close the popup. :param event | <QKeyEvent>
def _get_match(self, host_object): """Get an item matching the given host object. The item may be either a parent domain or identical value. Parent domains and existing identical values always precede insertion point for given value - therefore, we treat an item just before inse...
Get an item matching the given host object. The item may be either a parent domain or identical value. Parent domains and existing identical values always precede insertion point for given value - therefore, we treat an item just before insertion point as potential match. :para...
def get_begin_cursor(self, project_name, logstore_name, shard_id): """ Get begin cursor from log service for batch pull logs Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type logstore_name: string ...
Get begin cursor from log service for batch pull logs Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type logstore_name: string :param logstore_name: the logstore name :type shard_id: int ...
def main(): """I provide a command-line interface for this module """ print() print("-~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~-") print(lorem_gotham_title().center(50)) print("-~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~-") print() poem = lorem_gotham() for n in range(16...
I provide a command-line interface for this module
async def wait_loop(self): """ Waits on a loop for reactions to the message. This should not be called manually - it is handled by `send_to`. """ start, back, forward, end, close = self.emojis def check(payload: discord.RawReactionActionEvent): """ Check...
Waits on a loop for reactions to the message. This should not be called manually - it is handled by `send_to`.
def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes): """Produce standard documentation for memberdef_nodes.""" for n in memberdef_nodes: self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: ...
Produce standard documentation for memberdef_nodes.
def get_volumes_for_instance(self, arg, device=None): """ Return all EC2 Volume objects attached to ``arg`` instance name or ID. May specify ``device`` to limit to the (single) volume attached as that device. """ instance = self.get(arg) filters = {'attachment.in...
Return all EC2 Volume objects attached to ``arg`` instance name or ID. May specify ``device`` to limit to the (single) volume attached as that device.
def get_definition(self): """ Add Definition to XMLBIF Return ------ dict: dict of type {variable: definition tag} Examples -------- >>> writer = XMLBIFWriter(model) >>> writer.get_definition() {'hear-bark': <Element DEFINITION at 0x7f1d4...
Add Definition to XMLBIF Return ------ dict: dict of type {variable: definition tag} Examples -------- >>> writer = XMLBIFWriter(model) >>> writer.get_definition() {'hear-bark': <Element DEFINITION at 0x7f1d48977408>, 'family-out': <Element DEFI...
def scores(self, result, add_new_line=True): """Prints out the scores in a pretty format""" if result.goalsHomeTeam > result.goalsAwayTeam: homeColor, awayColor = (self.colors.WIN, self.colors.LOSE) elif result.goalsHomeTeam < result.goalsAwayTeam: homeColor, awayColor = ...
Prints out the scores in a pretty format
def set_default(nick, location, session, send, apikey): """Sets nick's default location to location.""" if valid_location(location, apikey): send("Setting default location") default = session.query(Weather_prefs).filter(Weather_prefs.nick == nick).first() if default is None: ...
Sets nick's default location to location.
def get_external_subprocess_output(command_list, print_output=False, indent_string="", split_lines=True, ignore_called_process_errors=False, env=None): """Run the command and arguments in the command_list. Will search the system PATH. Returns the output as a list of lines. If print_out...
Run the command and arguments in the command_list. Will search the system PATH. Returns the output as a list of lines. If print_output is True the output is echoed to stdout, indented (or otherwise prefixed) by indent_string. Waits for command completion. Called process errors can be set to be igno...
def get_current_temperature(self, refresh=False): """Get current temperature""" if refresh: self.refresh() try: return float(self.get_value('temperature')) except (TypeError, ValueError): return None
Get current temperature
def parse_skypos(ra, dec): """ Function to parse RA and Dec input values and turn them into decimal degrees Input formats could be: ["nn","nn","nn.nn"] "nn nn nn.nnn" "nn:nn:nn.nn" "nnH nnM nn.nnS" or "nnD nnM nn.nnS" nn.nnnnnnnn "nn.nnnnnnn" """ ...
Function to parse RA and Dec input values and turn them into decimal degrees Input formats could be: ["nn","nn","nn.nn"] "nn nn nn.nnn" "nn:nn:nn.nn" "nnH nnM nn.nnS" or "nnD nnM nn.nnS" nn.nnnnnnnn "nn.nnnnnnn"
def from_bytes(cls, bitstream): ''' Parse the given record and update properties accordingly ''' record = cls() # Convert to ConstBitStream (if not already provided) if not isinstance(bitstream, ConstBitStream): if isinstance(bitstream, Bits): ...
Parse the given record and update properties accordingly
def on_network_adapter_change(self, network_adapter, change_adapter): """Triggered when settings of a network adapter of the associated virtual machine have changed. in network_adapter of type :class:`INetworkAdapter` in change_adapter of type bool raises :class:`VBoxErrorInva...
Triggered when settings of a network adapter of the associated virtual machine have changed. in network_adapter of type :class:`INetworkAdapter` in change_adapter of type bool raises :class:`VBoxErrorInvalidVmState` Session state prevents operation. raises...
def closeContentsWidget( self ): """ Closes the current contents widget. """ widget = self.currentContentsWidget() if ( not widget ): return widget.close() widget.setParent(None) widget.deleteLater()
Closes the current contents widget.
def NewFromLab(l, a, b, alpha=1.0, wref=_DEFAULT_WREF): '''Create a new instance based on the specifed CIE-LAB values. Parameters: :l: The L component [0...100] :a: The a component [-1...1] :b: The a component [-1...1] :alpha: The color transparency [0......
Create a new instance based on the specifed CIE-LAB values. Parameters: :l: The L component [0...100] :a: The a component [-1...1] :b: The a component [-1...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint refer...
def write_csv(path, data): """This function writes comma-separated <data> to <path>. Parameter <path> is either a pathname or a file-like object that supports the |write()| method.""" fd = _try_open_file(path, 'w', 'The first argument must be a pathname or an object that support...
This function writes comma-separated <data> to <path>. Parameter <path> is either a pathname or a file-like object that supports the |write()| method.
def numRegisteredForRole(self, role, includeTemporaryRegs=False): ''' Accepts a DanceRole object and returns the number of registrations of that role. ''' count = self.eventregistration_set.filter(cancelled=False,dropIn=False,role=role).count() if includeTemporaryRegs: ...
Accepts a DanceRole object and returns the number of registrations of that role.
def p_arr_assignment(p): """ statement : ARRAY_ID arg_list EQ expr | LET ARRAY_ID arg_list EQ expr """ i = 2 if p[1].upper() == 'LET' else 1 id_ = p[i] arg_list = p[i + 1] expr = p[i + 3] p[0] = None if arg_list is None or expr is None: return # There were err...
statement : ARRAY_ID arg_list EQ expr | LET ARRAY_ID arg_list EQ expr
def evaluate_extracted_tokens(gold_content, extr_content): """ Evaluate the similarity between gold-standard and extracted content, typically for a single HTML document, as another way of evaluating the performance of an extractor model. Args: gold_content (str or Sequence[str]): Gold-stand...
Evaluate the similarity between gold-standard and extracted content, typically for a single HTML document, as another way of evaluating the performance of an extractor model. Args: gold_content (str or Sequence[str]): Gold-standard content, either as a string or as an already-tokenized ...
def _get_repr_list(self): """ Get some representation data common to all HDU types """ spacing = ' '*2 text = [''] text.append("%sfile: %s" % (spacing, self._filename)) text.append("%sextension: %d" % (spacing, self._info['hdunum']-1)) text.append( ...
Get some representation data common to all HDU types
def get_ip_interface_input_request_type_get_request_interface_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_ip_interface = ET.Element("get_ip_interface") config = get_ip_interface input = ET.SubElement(get_ip_interface, "input") ...
Auto Generated Code
def _band8(ins): """ Pops top 2 operands out of the stack, and does 1st AND (bitwise) 2nd operand (top of the stack), pushes the result. 8 bit un/signed version """ op1, op2 = tuple(ins.quad[2:]) if _int_ops(op1, op2) is not None: op1, op2 = _int_ops(op1, op2) o...
Pops top 2 operands out of the stack, and does 1st AND (bitwise) 2nd operand (top of the stack), pushes the result. 8 bit un/signed version
def load_time_series(filename, delimiter=r'\s+'): r"""Import a time series from an annotation file. The file should consist of two columns of numeric values corresponding to the time and value of each sample of the time series. Parameters ---------- filename : str Path to the annotatio...
r"""Import a time series from an annotation file. The file should consist of two columns of numeric values corresponding to the time and value of each sample of the time series. Parameters ---------- filename : str Path to the annotation file delimiter : str Separator regular e...
def start_background_task(self, target, *args, **kwargs): """Start a background task using the appropriate async model. This is a utility function that applications can use to start a background task using the method that is compatible with the selected async mode. :param targe...
Start a background task using the appropriate async model. This is a utility function that applications can use to start a background task using the method that is compatible with the selected async mode. :param target: the target function to execute. :param args: arguments to ...
def precmd(self, line): """Handle alias expansion and ';;' separator.""" if not line.strip(): return line args = line.split() while args[0] in self.aliases: line = self.aliases[args[0]] ii = 1 for tmpArg in args[1:]: line = ...
Handle alias expansion and ';;' separator.
def tidyHTML(dirtyHTML): """ Runs an arbitrary HTML string through Tidy. """ try: from tidylib import tidy_document except ImportError as e: raise ImportError(("%s\nYou need to install pytidylib.\n" + "e.g. sudo pip install pytidylib") % e) options = { 'outpu...
Runs an arbitrary HTML string through Tidy.
def quoted(s): """ quotes a string if necessary. """ # strip any existing quotes s = s.strip(u'"') # don't add quotes for minus or leading space if s[0] in (u'-', u' '): return s if u' ' in s or u'/' in s: return u'"%s"' % s else: return s
quotes a string if necessary.
def mount(self, volume): """Performs mount actions on a LVM. Scans for active volume groups from the loopback device, activates it and fills :attr:`volumes` with the logical volumes. :raises NoLoopbackAvailableError: when no loopback was available :raises IncorrectFilesystemError: when ...
Performs mount actions on a LVM. Scans for active volume groups from the loopback device, activates it and fills :attr:`volumes` with the logical volumes. :raises NoLoopbackAvailableError: when no loopback was available :raises IncorrectFilesystemError: when the volume is not a volume group
def repl_member_add(self, params): """create new mongod instances and add it to the replica set. Args: params - mongod params return True if operation success otherwise False """ repl_config = self.config member_id = max([member['_id'] for member in repl_confi...
create new mongod instances and add it to the replica set. Args: params - mongod params return True if operation success otherwise False
def ub_to_str(string): """ converts py2 unicode / py3 bytestring into str Args: string (unicode, byte_string): string to be converted Returns: (str) """ if not isinstance(string, str): if six.PY2: return str(string) else: return st...
converts py2 unicode / py3 bytestring into str Args: string (unicode, byte_string): string to be converted Returns: (str)
def unsupported_media_type(content_type): """ Creates a Lambda Service UnsupportedMediaType Response Parameters ---------- content_type str Content Type of the request that was made Returns ------- Flask.Response A response object...
Creates a Lambda Service UnsupportedMediaType Response Parameters ---------- content_type str Content Type of the request that was made Returns ------- Flask.Response A response object representing the UnsupportedMediaType Error
def change_state_id(self, state_id=None): """ Changes the id of the state to a new id. This functions replaces the old state_id with the new state_id in all data flows and transitions. :param state_id: The new state if of the state """ old_state_id = self.state_id ...
Changes the id of the state to a new id. This functions replaces the old state_id with the new state_id in all data flows and transitions. :param state_id: The new state if of the state
def _trim(self): """ Removes oldest backups that exceed the limit configured in backup_count option. Does not write back to file system, make sure to call self._write() afterwards. """ index = self._get_index() backup_limit = config().backup_count() - 1 ...
Removes oldest backups that exceed the limit configured in backup_count option. Does not write back to file system, make sure to call self._write() afterwards.
def __parseResponseServer(self): """Parses the response of the server. Exception --------- A Sitools2Exception is raised when the server does not send back a success.""" self.__logger.debug(Sitools2Abstract.getBaseUrl(self) + SITools2Instance.PROJECTS_URI) ...
Parses the response of the server. Exception --------- A Sitools2Exception is raised when the server does not send back a success.
async def AddCharm(self, channel, url): ''' channel : str url : str Returns -> None ''' # map input types to rpc msg _params = dict() msg = dict(type='Client', request='AddCharm', version=1, params=_...
channel : str url : str Returns -> None
def _check_endings(self): """Check begin/end of slug, raises Error if malformed.""" if self.slug.startswith("/") and self.slug.endswith("/"): raise InvalidSlugError( _("Invalid slug. Did you mean {}, without the leading and trailing slashes?".format(self.slug.strip("/")))) ...
Check begin/end of slug, raises Error if malformed.
def get_missing_bins(original, trimmed): """Retrieve indices of a trimmed matrix with respect to the original matrix. Fairly fast but is only correct if diagonal values are different, which is always the case in practice. """ original_diag = np.diag(original) trimmed_diag = np.diag(trimmed) ...
Retrieve indices of a trimmed matrix with respect to the original matrix. Fairly fast but is only correct if diagonal values are different, which is always the case in practice.