code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def main():
"""Entry point for the script"""
desc = 'Converts between geodetic, modified apex, quasi-dipole and MLT'
parser = argparse.ArgumentParser(description=desc, prog='apexpy')
parser.add_argument('source', metavar='SOURCE',
choices=['geo', 'apex', 'qd', 'mlt'],
... | Entry point for the script |
def get_and_alter(self, function):
"""
Alters the currently stored reference by applying a function on it on and gets the old value.
:param function: (Function), A stateful serializable object which represents the Function defined on
server side.
This object must have a ... | Alters the currently stored reference by applying a function on it on and gets the old value.
:param function: (Function), A stateful serializable object which represents the Function defined on
server side.
This object must have a serializable Function counter part registered on server... |
def from_weight_map(cls, pixel_scale, weight_map):
"""Setup the noise-map from a weight map, which is a form of noise-map that comes via HST image-reduction and \
the software package MultiDrizzle.
The variance in each pixel is computed as:
Variance = 1.0 / sqrt(weight_map).
T... | Setup the noise-map from a weight map, which is a form of noise-map that comes via HST image-reduction and \
the software package MultiDrizzle.
The variance in each pixel is computed as:
Variance = 1.0 / sqrt(weight_map).
The weight map may contain zeros, in which cause the variances ... |
def validate(self):
"""method traverse tree and performs following activities:
* requests a job record in STATE_EMBRYO if no job record is currently assigned to the node
* requests nodes for reprocessing, if STATE_PROCESSED node relies on unfinalized nodes
* requests node for skipping if... | method traverse tree and performs following activities:
* requests a job record in STATE_EMBRYO if no job record is currently assigned to the node
* requests nodes for reprocessing, if STATE_PROCESSED node relies on unfinalized nodes
* requests node for skipping if it is daily node and all 24 of... |
def find(self, resource, req, sub_resource_lookup):
"""Find documents for resource."""
args = getattr(req, 'args', request.args if request else {}) or {}
source_config = config.SOURCES[resource]
if args.get('source'):
query = json.loads(args.get('source'))
if 'fi... | Find documents for resource. |
def solveConsAggShock(solution_next,IncomeDstn,LivPrb,DiscFac,CRRA,PermGroFac,
PermGroFacAgg,aXtraGrid,BoroCnstArt,Mgrid,AFunc,Rfunc,wFunc,DeprFac):
'''
Solve one period of a consumption-saving problem with idiosyncratic and
aggregate shocks (transitory and permanent). This is a basic... | Solve one period of a consumption-saving problem with idiosyncratic and
aggregate shocks (transitory and permanent). This is a basic solver that
can't handle cubic splines, nor can it calculate a value function.
Parameters
----------
solution_next : ConsumerSolution
The solution to the suc... |
def get_position_d(self):
""" Get the D value of the current PID for position
"""
data = []
data.append(0x09)
data.append(self.servoid)
data.append(RAM_READ_REQ)
data.append(POSITION_KD_RAM)
data.append(BYTE2)
send_data(data)
rxdata = []
... | Get the D value of the current PID for position |
def discardID(self, idVal):
"""Checks if the collected items contains the give _idVal_ and discards it if it is found, will not raise an exception if item is not found
# Parameters
_idVal_ : `str`
> The discarded id string
"""
for i in self:
if i.id == idVa... | Checks if the collected items contains the give _idVal_ and discards it if it is found, will not raise an exception if item is not found
# Parameters
_idVal_ : `str`
> The discarded id string |
def get_alignment_df(a_aln_seq, b_aln_seq, a_seq_id=None, b_seq_id=None):
"""Summarize two alignment strings in a dataframe.
Args:
a_aln_seq (str): Aligned sequence string
b_aln_seq (str): Aligned sequence string
a_seq_id (str): Optional ID of a_seq
b_seq_id (str): Optional ID o... | Summarize two alignment strings in a dataframe.
Args:
a_aln_seq (str): Aligned sequence string
b_aln_seq (str): Aligned sequence string
a_seq_id (str): Optional ID of a_seq
b_seq_id (str): Optional ID of b_aln_seq
Returns:
DataFrame: a per-residue level annotation of th... |
def _load_values(self, db_key: str) -> dict:
"""Load values from the db at the specified key, db_key.
FIXME(BMo): Could also be extended to load scalar types (instead of
just list and hash)
"""
if self._db.type(db_key) == 'list':
db_values = self._db.lra... | Load values from the db at the specified key, db_key.
FIXME(BMo): Could also be extended to load scalar types (instead of
just list and hash) |
def addCases(self, tupesValStmnts):
"""
Add multiple case statements from iterable of tuleles
(caseVal, statements)
"""
s = self
for val, statements in tupesValStmnts:
s = s.Case(val, statements)
return s | Add multiple case statements from iterable of tuleles
(caseVal, statements) |
def search_playlist(self, playlist_name, quiet=False, limit=9):
"""Search playlist by playlist name.
:params playlist_name: playlist name.
:params quiet: automatically select the best one.
:params limit: playlist count returned by weapi.
:return: a Playlist object.
"""
... | Search playlist by playlist name.
:params playlist_name: playlist name.
:params quiet: automatically select the best one.
:params limit: playlist count returned by weapi.
:return: a Playlist object. |
def groupby(self, dimensions=None, container_type=None, group_type=None, **kwargs):
"""Groups DynamicMap by one or more dimensions
Applies groupby operation over the specified dimensions
returning an object of type container_type (expected to be
dictionary-like) containing the groups.
... | Groups DynamicMap by one or more dimensions
Applies groupby operation over the specified dimensions
returning an object of type container_type (expected to be
dictionary-like) containing the groups.
Args:
dimensions: Dimension(s) to group by
container_type: Type... |
def trigger(self, event, filter=None, update=None, documents=None, ids=None, replacements=None):
""" Trigger the after_save hook on documents, if present. """
if not self.has_trigger(event):
return
if documents is not None:
pass
elif ids is not None:
... | Trigger the after_save hook on documents, if present. |
def Process(self, path):
"""Processes a given path.
Args:
path: Path (as a string) to post-process.
Returns:
A list of paths with environment variables replaced with their
values. If the mapping had a list of values for a particular variable,
instead of just one value, then all pos... | Processes a given path.
Args:
path: Path (as a string) to post-process.
Returns:
A list of paths with environment variables replaced with their
values. If the mapping had a list of values for a particular variable,
instead of just one value, then all possible replacements will be
... |
def _set_af_vrf(self, v, load=False):
"""
Setter method for af_vrf, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv4/ipv4_unicast/af_vrf (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_af_vrf is considered as a private
method. Backen... | Setter method for af_vrf, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv4/ipv4_unicast/af_vrf (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_af_vrf is considered as a private
method. Backends looking to populate this variable should
do... |
def create_filename_parser(self, base_dir):
"""Create a :class:`trollsift.parser.Parser` object for later use."""
# just in case a writer needs more complex file patterns
# Set a way to create filenames if we were given a pattern
if base_dir and self.file_pattern:
file_patter... | Create a :class:`trollsift.parser.Parser` object for later use. |
def formatTextException(*args):
"""
Formats given exception as a text.
:param \*args: Arguments.
:type \*args: \*
:return: Exception text.
:rtype: unicode
"""
format = lambda x: re.sub(r"^(\s+)", lambda y: "{0} ".format("." * len(y.group(0))), x.rstrip()... | Formats given exception as a text.
:param \*args: Arguments.
:type \*args: \*
:return: Exception text.
:rtype: unicode |
def get_vlan_brief_output_vlan_vlan_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubElement(output, "... | Auto Generated Code |
def _get_ip_address(self, request):
"""Get the remote ip address the request was generated from. """
ipaddr = request.META.get("HTTP_X_FORWARDED_FOR", None)
if ipaddr:
# X_FORWARDED_FOR returns client1, proxy1, proxy2,...
return ipaddr.split(",")[0].strip()
return... | Get the remote ip address the request was generated from. |
def init_logging(config):
"""Initialize base logger named 'wsgidav'.
The base logger is filtered by the `verbose` configuration option.
Log entries will have a time stamp and thread id.
:Parameters:
verbose : int
Verbosity configuration (0..5)
enable_loggers : string list
... | Initialize base logger named 'wsgidav'.
The base logger is filtered by the `verbose` configuration option.
Log entries will have a time stamp and thread id.
:Parameters:
verbose : int
Verbosity configuration (0..5)
enable_loggers : string list
List of module logger ... |
def delete_insight(self, project_key, insight_id):
"""Delete an existing insight.
:params project_key: Project identifier, in the form of
projectOwner/projectId
:type project_key: str
:params insight_id: Insight unique id
:type insight_id: str
:raises RestApiExce... | Delete an existing insight.
:params project_key: Project identifier, in the form of
projectOwner/projectId
:type project_key: str
:params insight_id: Insight unique id
:type insight_id: str
:raises RestApiException: If a server error occurs
Examples
----... |
def reset(self):
"""Clear ConfigObj instance and restore to 'freshly created' state."""
self.clear()
self._initialise()
# FIXME: Should be done by '_initialise', but ConfigObj constructor (and reload)
# requires an empty dictionary
self.configspec = None
# ... | Clear ConfigObj instance and restore to 'freshly created' state. |
def to_bytes(string):
"""Convert a string (bytes, str or unicode) to bytes."""
assert isinstance(string, basestring)
if sys.version_info[0] >= 3:
if isinstance(string, str):
return string.encode('utf-8')
else:
return string
else:
if isinstance(string, unic... | Convert a string (bytes, str or unicode) to bytes. |
def get_list(self, size=100, startIndex=0, searchText="", sortProperty="", sortOrder='ASC', status='Active,Pending'):
"""
Request service locations
Returns
-------
dict
"""
url = urljoin(BASEURL, "sites", "list")
params = {
'api_key': self.t... | Request service locations
Returns
-------
dict |
def on_module(self, node): # ():('body',)
"""Module def."""
out = None
for tnode in node.body:
out = self.run(tnode)
return out | Module def. |
def overlap(self, spectrum):
"""Tests for overlap of this filter with a spectrum
Example of full overlap:
|---------- spectrum ----------|
|------ self ------|
Examples of partial overlap: :
|---------- self ----------|
|------ spectrum -... | Tests for overlap of this filter with a spectrum
Example of full overlap:
|---------- spectrum ----------|
|------ self ------|
Examples of partial overlap: :
|---------- self ----------|
|------ spectrum ------|
|---- spectrum ----|... |
def addTab(self, widget, *args):
"""
Re-implements addTab to connect to the dirty changed signal and setup
some helper attributes.
:param widget: widget to add
:param args: optional addtional arguments (name and/or icon).
"""
widget.dirty_changed.connect(self._on... | Re-implements addTab to connect to the dirty changed signal and setup
some helper attributes.
:param widget: widget to add
:param args: optional addtional arguments (name and/or icon). |
def get_value(self, key):
"""
Fetch the settings value with the highest precedence for the given
key, or raise KeyError.
Precedence:
- IDB scope
- directory scope
- user scope
- system scope
type key: basestring
rtype value: Union... | Fetch the settings value with the highest precedence for the given
key, or raise KeyError.
Precedence:
- IDB scope
- directory scope
- user scope
- system scope
type key: basestring
rtype value: Union[basestring, int, float, List, Dict] |
def pixel_width(self):
"""
Width of the whole TimeLine in pixels
:rtype: int
"""
return self.zoom_factor * ((self._finish - self._start) / self._resolution) | Width of the whole TimeLine in pixels
:rtype: int |
def as_dict(self):
""" Pre-serialisation of the meta data """
drepr = super(PlayMeta, self).as_dict()
drepr["details"] = [meta.as_dict() for meta in self._metas]
return drepr | Pre-serialisation of the meta data |
def list_runner_book(self, market_id, selection_id, handicap=None, price_projection=None, order_projection=None,
match_projection=None, include_overall_position=None, partition_matched_by_strategy_ref=None,
customer_strategy_refs=None, currency_code=None, matched_since=... | Returns a list of dynamic data about a market and a specified runner.
Dynamic data includes prices, the status of the market, the status of selections,
the traded volume, and the status of any orders you have placed in the market
:param unicode market_id: The unique id for the market
... |
def increase_writes_in_units(
current_provisioning, units, max_provisioned_writes,
consumed_write_units_percent, log_tag):
""" Increase the current_provisioning with units units
:type current_provisioning: int
:param current_provisioning: The current provisioning
:type units: int
:p... | Increase the current_provisioning with units units
:type current_provisioning: int
:param current_provisioning: The current provisioning
:type units: int
:param units: How many units should we increase with
:returns: int -- New provisioning value
:type max_provisioned_writes: int
:param max... |
def write(self):
"""Return SAM formatted string
Returns:
str: SAM formatted string containing entire SAM entry
"""
return '{0}\t{1}\t{2}\t{3}\t{4}\t' \
'{5}\t{6}\t{7}\t{8}\t{9}\t' \
'{10}{11}'.format(self.qname,
... | Return SAM formatted string
Returns:
str: SAM formatted string containing entire SAM entry |
def tune(runner, kernel_options, device_options, tuning_options):
""" Find the best performing kernel configuration in the parameter space
:params runner: A runner from kernel_tuner.runners
:type runner: kernel_tuner.runner
:param kernel_options: A dictionary with all options for the kernel.
:type... | Find the best performing kernel configuration in the parameter space
:params runner: A runner from kernel_tuner.runners
:type runner: kernel_tuner.runner
:param kernel_options: A dictionary with all options for the kernel.
:type kernel_options: kernel_tuner.interface.Options
:param device_options... |
def decode_event(self, log_topics, log_data):
""" Return a dictionary representation the log.
Note:
This function won't work with anonymous events.
Args:
log_topics (List[bin]): The log's indexed arguments.
log_data (bin): The encoded non-indexed arguments.
... | Return a dictionary representation the log.
Note:
This function won't work with anonymous events.
Args:
log_topics (List[bin]): The log's indexed arguments.
log_data (bin): The encoded non-indexed arguments. |
def _get_uploaded_file(session, file_info, fragment_count=0):
"""
:param session: locked session (with self._session_resource as >> session <<)
:param file_info: contains file information to save or query
:param fragment_count: amount of fragments associated to the file
:return: ... | :param session: locked session (with self._session_resource as >> session <<)
:param file_info: contains file information to save or query
:param fragment_count: amount of fragments associated to the file
:return: an UploadedFile associated to the file_info |
def entry_line_to_text(self, entry):
"""
Return the textual representation of an :class:`~taxi.timesheet.lines.Entry` instance. This method is a bit
convoluted since we don't want to completely mess up the original formatting of the entry.
"""
line = []
# The entry is ne... | Return the textual representation of an :class:`~taxi.timesheet.lines.Entry` instance. This method is a bit
convoluted since we don't want to completely mess up the original formatting of the entry. |
def from_bytes(cls, bitstream):
'''
Parse the given packet and update properties accordingly
'''
packet = cls()
# Convert to ConstBitStream (if not already provided)
if not isinstance(bitstream, ConstBitStream):
if isinstance(bitstream, Bits):
... | Parse the given packet and update properties accordingly |
def _dens(self,R,z,phi=0.,t=0.):
"""
NAME:
_dens
PURPOSE:
evaluate the density for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
the surfa... | NAME:
_dens
PURPOSE:
evaluate the density for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
the surface density
HISTORY:
2018-08-19 - W... |
def create_async_sns_topic(self, lambda_name, lambda_arn):
"""
Create the SNS-based async topic.
"""
topic_name = get_topic_name(lambda_name)
# Create SNS topic
topic_arn = self.sns_client.create_topic(
Name=topic_name)['TopicArn']
# Create subscriptio... | Create the SNS-based async topic. |
def problem_with_codon(codon_index, codon_list, bad_seqs):
"""
Return true if the given codon overlaps with a bad sequence.
"""
base_1 = 3 * codon_index
base_3 = 3 * codon_index + 2
gene_seq = ''.join(codon_list)
for bad_seq in bad_seqs:
problem = bad_seq.search(gene_seq)
... | Return true if the given codon overlaps with a bad sequence. |
def thin_sum(cachedir, form='sha1'):
'''
Return the checksum of the current thin tarball
'''
thintar = gen_thin(cachedir)
code_checksum_path = os.path.join(cachedir, 'thin', 'code-checksum')
if os.path.isfile(code_checksum_path):
with salt.utils.files.fopen(code_checksum_path, 'r') as fh... | Return the checksum of the current thin tarball |
def rate_limit_status(self):
""" :reference: https://developer.twitter.com/en/docs/developer-utilities/rate-limit-status/api-reference/get-application-rate_limit_status
:allowed_param:'resources'
"""
return bind_api(
api=self,
path='/application/rate_limit_sta... | :reference: https://developer.twitter.com/en/docs/developer-utilities/rate-limit-status/api-reference/get-application-rate_limit_status
:allowed_param:'resources' |
def get_views(self, item=None, key=None, option=None):
"""Return the views object.
If key is None, return all the view for the current plugin
else if option is None return the view for the specific key (all option)
else return the view fo the specific key/option
Specify item if... | Return the views object.
If key is None, return all the view for the current plugin
else if option is None return the view for the specific key (all option)
else return the view fo the specific key/option
Specify item if the stats are stored in a dict of dict (ex: NETWORK, FS...) |
def push(self, cf):
"""
Push the frame cf onto the stack. Return the new stack.
"""
cf.next = self
if self.state is not None:
self.state.register_plugin('callstack', cf)
self.state.history.recent_stack_actions.append(CallStackAction(
hash(c... | Push the frame cf onto the stack. Return the new stack. |
def infer_x(self, y):
"""Infer probable x from input y
@param y the desired output for infered x.
@return a list of probable x
"""
OptimizedInverseModel.infer_x(self, y)
if self.fmodel.size() == 0:
return self._random_x()
x_guesses = [self._guess_x... | Infer probable x from input y
@param y the desired output for infered x.
@return a list of probable x |
def _from_json_array_nested(cls, response_raw):
"""
:type response_raw: client.BunqResponseRaw
:rtype: bunq.sdk.client.BunqResponse[cls]
"""
json = response_raw.body_bytes.decode()
obj = converter.json_to_class(dict, json)
value = converter.deserialize(cls, obj[... | :type response_raw: client.BunqResponseRaw
:rtype: bunq.sdk.client.BunqResponse[cls] |
def do_help(self, arg):
"""
? - show the list of available commands
? * - show help for all commands
? <command> [command...] - show help for the given command(s)
help - show the list of available commands
help * - show help for all commands
help <command> [comman... | ? - show the list of available commands
? * - show help for all commands
? <command> [command...] - show help for the given command(s)
help - show the list of available commands
help * - show help for all commands
help <command> [command...] - show help for the given command(s) |
def add_tracked_motors(self, tracked_motors):
"""Add new motors to the recording"""
new_mockup_motors = map(self.get_mockup_motor, tracked_motors)
self.tracked_motors = list(set(self.tracked_motors + new_mockup_motors)) | Add new motors to the recording |
def state(anon, obj, field, val):
"""
Returns a randomly selected US state code
"""
return anon.faker.state(field=field) | Returns a randomly selected US state code |
def within_n_mads(n, series):
"""Return true if all values in sequence are within n MADs"""
mad_score = (series - series.mean()) / series.mad()
return (mad_score.abs() <= n).all() | Return true if all values in sequence are within n MADs |
def refresh(self, force_cache=False):
"""
Perform a system refresh.
:param force_cache: Force an update of the camera cache
"""
if self.check_if_ok_to_update() or force_cache:
for sync_name, sync_module in self.sync.items():
_LOGGER.debug("Attempting ... | Perform a system refresh.
:param force_cache: Force an update of the camera cache |
def _dataframe_fields(self):
"""
Creates a dictionary of all fields to include with DataFrame.
With the result of the calls to class properties changing based on the
class index value, the dictionary should be regenerated every time the
index is changed when the dataframe proper... | Creates a dictionary of all fields to include with DataFrame.
With the result of the calls to class properties changing based on the
class index value, the dictionary should be regenerated every time the
index is changed when the dataframe property is requested.
Returns
-------... |
def words(content, filter=True, predicate=None):
"""\
Returns an iterable of words from the provided text.
`content`
A text.
`filter`
Indicates if stop words and garbage like "xxxxxx" should be removed from
the word list.
`predicate`
An alternative word filter. I... | \
Returns an iterable of words from the provided text.
`content`
A text.
`filter`
Indicates if stop words and garbage like "xxxxxx" should be removed from
the word list.
`predicate`
An alternative word filter. If it is ``None`` "xxxx", "---",
default stop wor... |
def add_github_hook_options(parser):
"""Add the github jenkins hook command and arguments.
:rtype: argparse.ArgumentParser
"""
cookbook = parser.add_parser('github', help='Install the Jenkins callback '
'hook in a GitHub repository')
cookbook.add_arg... | Add the github jenkins hook command and arguments.
:rtype: argparse.ArgumentParser |
def fit_first_and_second_harmonics(phi, intensities):
"""
Fit the first and second harmonic function values to a set of
(angle, intensity) pairs.
This function is used to compute corrections for ellipse fitting:
.. math::
f(phi) = y0 + a1*\\sin(phi) + b1*\\cos(phi) + a2*\\sin(2*phi) +
... | Fit the first and second harmonic function values to a set of
(angle, intensity) pairs.
This function is used to compute corrections for ellipse fitting:
.. math::
f(phi) = y0 + a1*\\sin(phi) + b1*\\cos(phi) + a2*\\sin(2*phi) +
b2*\\cos(2*phi)
Parameters
----------
p... |
def Update(self, menu=None, tooltip=None,filename=None, data=None, data_base64=None,):
'''
Updates the menu, tooltip or icon
:param menu: menu defintion
:param tooltip: string representing tooltip
:param filename: icon filename
:param data: icon raw image
:param... | Updates the menu, tooltip or icon
:param menu: menu defintion
:param tooltip: string representing tooltip
:param filename: icon filename
:param data: icon raw image
:param data_base64: icon base 64 image
:return: |
def normalize_enum_constant(s):
"""Return enum constant `s` converted to a canonical snake-case."""
if s.islower(): return s
if s.isupper(): return s.lower()
return "".join(ch if ch.islower() else "_" + ch.lower() for ch in s).strip("_") | Return enum constant `s` converted to a canonical snake-case. |
def check_valid_cpc_status(method, uri, cpc):
"""
Check that the CPC is in a valid status, as indicated by its 'status'
property.
If the Cpc object does not have a 'status' property set, this function does
nothing (in order to make the mock support easy to use).
Raises:
ConflictError wit... | Check that the CPC is in a valid status, as indicated by its 'status'
property.
If the Cpc object does not have a 'status' property set, this function does
nothing (in order to make the mock support easy to use).
Raises:
ConflictError with reason 1: The CPC itself has been targeted by the
... |
def pretty_print_json(self, json_string):
"""
Return formatted JSON string _json_string_.\n
Using method json.dumps with settings: _indent=2, ensure_ascii=False_.
*Args:*\n
_json_string_ - JSON string.
*Returns:*\n
Formatted JSON string.
*Example:*\n
... | Return formatted JSON string _json_string_.\n
Using method json.dumps with settings: _indent=2, ensure_ascii=False_.
*Args:*\n
_json_string_ - JSON string.
*Returns:*\n
Formatted JSON string.
*Example:*\n
| *Settings* | *Value* |
| Library | JsonVali... |
def exclude_by_ends(in_file, exclude_file, data, in_params=None):
"""Exclude calls based on overlap of the ends with exclusion regions.
Removes structural variants with either end being in a repeat: a large
source of false positives.
Parameters tuned based on removal of LCR overlapping false positives... | Exclude calls based on overlap of the ends with exclusion regions.
Removes structural variants with either end being in a repeat: a large
source of false positives.
Parameters tuned based on removal of LCR overlapping false positives in DREAM
synthetic 3 data. |
def copy_and_disconnect_tree(root, machine):
"""Copy a RoutingTree (containing nothing but RoutingTrees), disconnecting
nodes which are not connected in the machine.
Note that if a dead chip is part of the input RoutingTree, no corresponding
node will be included in the copy. The assumption behind this... | Copy a RoutingTree (containing nothing but RoutingTrees), disconnecting
nodes which are not connected in the machine.
Note that if a dead chip is part of the input RoutingTree, no corresponding
node will be included in the copy. The assumption behind this is that the
only reason a tree would visit a de... |
def is_binary(path):
'''
Detects if the file is a binary, returns bool. Returns True if the file is
a bin, False if the file is not and None if the file is not available.
'''
if not os.path.isfile(path):
return False
try:
with fopen(path, 'rb') as fp_:
try:
... | Detects if the file is a binary, returns bool. Returns True if the file is
a bin, False if the file is not and None if the file is not available. |
def format_item(x, timedelta_format=None, quote_strings=True):
"""Returns a succinct summary of an object as a string"""
if isinstance(x, (np.datetime64, datetime)):
return format_timestamp(x)
if isinstance(x, (np.timedelta64, timedelta)):
return format_timedelta(x, timedelta_format=timedelt... | Returns a succinct summary of an object as a string |
def close(self):
"""Close the connection to the email server."""
try:
try:
self.connection.quit()
except socket.sslerror:
# This happens when calling quit() on a TLS connection
# sometimes.
self.connection.cl... | Close the connection to the email server. |
def metadata_path(self, m_path):
"""Provide pointers to the paths of the metadata file
Args:
m_path: Path to metadata file
"""
if not m_path:
self.metadata_dir = None
self.metadata_file = None
else:
if not op.exists(m_path):
... | Provide pointers to the paths of the metadata file
Args:
m_path: Path to metadata file |
def structured_partlist(input, timeout=20, showgui=False):
'''export partlist by eagle, then parse it
:param input: .sch or .brd file name
:param timeout: int
:param showgui: Bool, True -> do not hide eagle GUI
:rtype: tuple of header list and dict list: (['part','value',..], [{'part':'C1', 'value'... | export partlist by eagle, then parse it
:param input: .sch or .brd file name
:param timeout: int
:param showgui: Bool, True -> do not hide eagle GUI
:rtype: tuple of header list and dict list: (['part','value',..], [{'part':'C1', 'value':'1n'}, ..]) |
def parse_universe_description(self, description):
''' Semantic
- 'sid1,sid2,sid2,...'
- 'exchange' : every sids of the exchange
- 'exchange,n' : n random sids of the exchange
where exchange is a combination of 'type:index:submarket'
'''
self.raw_descri... | Semantic
- 'sid1,sid2,sid2,...'
- 'exchange' : every sids of the exchange
- 'exchange,n' : n random sids of the exchange
where exchange is a combination of 'type:index:submarket' |
def find_matching_bracket_position(self, start_pos=None, end_pos=None):
"""
Return relative cursor position of matching [, (, { or < bracket.
When `start_pos` or `end_pos` are given. Don't look past the positions.
"""
# Look for a match.
for A, B in '()', '[]', '{}', '<... | Return relative cursor position of matching [, (, { or < bracket.
When `start_pos` or `end_pos` are given. Don't look past the positions. |
def get_data_record(self, brain, field_names):
"""Returns a dict with the column values for the given brain
"""
record = {}
model = None
for field_name in field_names:
# First try to get the value directly from the brain
value = getattr(brain, field_name,... | Returns a dict with the column values for the given brain |
def get_node_label(self, model):
"""
Defines how labels are constructed from models.
Default - uses verbose name, lines breaks where sensible
"""
if model.is_proxy:
label = "(P) %s" % (model.name.title())
else:
label = "%s" % (model.name.title())
... | Defines how labels are constructed from models.
Default - uses verbose name, lines breaks where sensible |
def recreate_article_body(self):
'''
Handles case where article body contained page or image.
Assumes all articles and images have been created.
'''
for foreign_id, body in iteritems(self.record_keeper.article_bodies):
try:
local_page_id = self.record... | Handles case where article body contained page or image.
Assumes all articles and images have been created. |
def get_perceel_by_capakey(self, capakey):
'''
Get a `perceel`.
:param capakey: An capakey for a `perceel`.
:rtype: :class:`Perceel`
'''
def creator():
url = self.base_url + '/parcel/%s' % capakey
h = self.base_headers
p = {
... | Get a `perceel`.
:param capakey: An capakey for a `perceel`.
:rtype: :class:`Perceel` |
def safe_size(source):
"""
READ THE source UP TO SOME LIMIT, THEN COPY TO A FILE IF TOO BIG
RETURN A str() OR A FileString()
"""
if source is None:
return None
total_bytes = 0
bytes = []
b = source.read(MIN_READ_SIZE)
while b:
total_bytes += len(b)
bytes.app... | READ THE source UP TO SOME LIMIT, THEN COPY TO A FILE IF TOO BIG
RETURN A str() OR A FileString() |
def get_config():
'''
Get the status of all the firewall profiles
Returns:
dict: A dictionary of all profiles on the system
Raises:
CommandExecutionError: If the command fails
CLI Example:
.. code-block:: bash
salt '*' firewall.get_config
'''
profiles = {}
... | Get the status of all the firewall profiles
Returns:
dict: A dictionary of all profiles on the system
Raises:
CommandExecutionError: If the command fails
CLI Example:
.. code-block:: bash
salt '*' firewall.get_config |
def get_git_postversion(addon_dir):
""" return the addon version number, with a developmental version increment
if there were git commits in the addon_dir after the last version change.
If the last change to the addon correspond to the version number in the
manifest it is used as is for the python pack... | return the addon version number, with a developmental version increment
if there were git commits in the addon_dir after the last version change.
If the last change to the addon correspond to the version number in the
manifest it is used as is for the python package version. Otherwise a
counter is incr... |
def callback(self, timestamp, event_type, payload):
"""Callback method for processing events in notification queue.
:param timestamp: time the message is received.
:param event_type: event type in the notification queue such as
identity.project.created, identity.proje... | Callback method for processing events in notification queue.
:param timestamp: time the message is received.
:param event_type: event type in the notification queue such as
identity.project.created, identity.project.deleted.
:param payload: Contains information of an ... |
def open_like(a, path, **kwargs):
"""Open a persistent array like `a`."""
_like_args(a, kwargs)
if isinstance(a, Array):
kwargs.setdefault('fill_value', a.fill_value)
return open_array(path, **kwargs) | Open a persistent array like `a`. |
def get_additional_properties(self, _type, *args, **kwargs):
"""Make head and table with additional properties by schema_id
:param str _type:
:rtype: str
"""
if not SchemaObjects.contains(_type):
return _type
schema = SchemaObjects.get(_type)
body = []... | Make head and table with additional properties by schema_id
:param str _type:
:rtype: str |
def detail_search(self, params, standardize=False):
"""Get a detailed list of person objects for the given search params.
:param params:
Dictionary specifying the query parameters
>>> people_detailed = d.detail_search({'first_name': 'tobias', 'last_name': 'funke'})
"""
... | Get a detailed list of person objects for the given search params.
:param params:
Dictionary specifying the query parameters
>>> people_detailed = d.detail_search({'first_name': 'tobias', 'last_name': 'funke'}) |
def dehydrate(self):
"""Return a dict representing this bucket."""
# Only concerned about very specific attributes
result = {}
for attr in self.attrs:
result[attr] = getattr(self, attr)
return result | Return a dict representing this bucket. |
def heartbeat(request):
"""
Runs all the Django checks and returns a JsonResponse with either
a status code of 200 or 500 depending on the results of the checks.
Any check that returns a warning or worse (error, critical) will
return a 500 response.
"""
all_checks = checks.registry.registry... | Runs all the Django checks and returns a JsonResponse with either
a status code of 200 or 500 depending on the results of the checks.
Any check that returns a warning or worse (error, critical) will
return a 500 response. |
def lbol_from_spt_dist_mag (sptnum, dist_pc, jmag, kmag, format='cgs'):
"""Estimate a UCD's bolometric luminosity given some basic parameters.
sptnum: the spectral type as a number; 8 -> M8; 10 -> L0 ; 20 -> T0
Valid values range between 0 and 30, ie M0 to Y0.
dist_pc: distance to the object in parse... | Estimate a UCD's bolometric luminosity given some basic parameters.
sptnum: the spectral type as a number; 8 -> M8; 10 -> L0 ; 20 -> T0
Valid values range between 0 and 30, ie M0 to Y0.
dist_pc: distance to the object in parsecs
jmag: object's J-band magnitude or NaN (*not* None) if unavailable
k... |
def template_from_file(basedir, path, vars):
''' run a file through the templating engine '''
from cirruscluster.ext.ansible import utils
realpath = utils.path_dwim(basedir, path)
loader=jinja2.FileSystemLoader([basedir,os.path.dirname(realpath)])
environment = jinja2.Environment(loader=loader, tri... | run a file through the templating engine |
def join(self, fm_new, minimal_subset=True):
"""
Adds content of a new Datamat to this Datamat.
If a parameter of the Datamats is not equal or does not exist
in one, it is promoted to a field.
If the two Datamats have different fields then the elements for the
Datamats ... | Adds content of a new Datamat to this Datamat.
If a parameter of the Datamats is not equal or does not exist
in one, it is promoted to a field.
If the two Datamats have different fields then the elements for the
Datamats that did not have the field will be NaN, unless
'minimal_... |
def fetch_guilds(self, *, limit=100, before=None, after=None):
"""|coro|
Retrieves an :class:`.AsyncIterator` that enables receiving your guilds.
.. note::
Using this, you will only receive :attr:`.Guild.owner`, :attr:`.Guild.icon`,
:attr:`.Guild.id`, and :attr:`.Guild... | |coro|
Retrieves an :class:`.AsyncIterator` that enables receiving your guilds.
.. note::
Using this, you will only receive :attr:`.Guild.owner`, :attr:`.Guild.icon`,
:attr:`.Guild.id`, and :attr:`.Guild.name` per :class:`.Guild`.
.. note::
This method is... |
def emflx(self, area, wavelengths=None):
"""Calculate
:ref:`equivalent monochromatic flux <synphot-formula-emflx>`.
Parameters
----------
area, wavelengths
See :func:`unit_response`.
Returns
-------
em_flux : `~astropy.units.quantity.Quantity... | Calculate
:ref:`equivalent monochromatic flux <synphot-formula-emflx>`.
Parameters
----------
area, wavelengths
See :func:`unit_response`.
Returns
-------
em_flux : `~astropy.units.quantity.Quantity`
Equivalent monochromatic flux. |
def parse(self, line=None):
"""parses the line provided, if None then uses sys.argv"""
args = self.parser.parse_args(args=line)
return args.func(args) | parses the line provided, if None then uses sys.argv |
def _gatk_extract_reads_cl(data, region, prep_params, tmp_dir):
"""Use GATK to extract reads from full BAM file.
"""
args = ["PrintReads",
"-L", region_to_gatk(region),
"-R", dd.get_ref_file(data),
"-I", data["work_bam"]]
# GATK3 back compatibility, need to specify an... | Use GATK to extract reads from full BAM file. |
def dataset_merge_method(dataset, other, overwrite_vars, compat, join):
"""Guts of the Dataset.merge method."""
# we are locked into supporting overwrite_vars for the Dataset.merge
# method due for backwards compatibility
# TODO: consider deprecating it?
if isinstance(overwrite_vars, str):
... | Guts of the Dataset.merge method. |
def get_section_key_line(self, data, key, opt_extension=':'):
"""Get the next section line for a given key.
:param data: the data to proceed
:param key: the key
:param opt_extension: an optional extension to delimit the opt value
"""
return super(GoogledocTools, self).g... | Get the next section line for a given key.
:param data: the data to proceed
:param key: the key
:param opt_extension: an optional extension to delimit the opt value |
def set_blink_rate(self, b):
"""
Set the user's desired blink rate (0 - 3)
@param b: blink rate
"""
if b > 3:
b = 0 # turn off if not sure
self.firmata.i2c_write(self.board_address,
(self.HT16K33_BLINK_CMD | self.HT16K33_BLINK_D... | Set the user's desired blink rate (0 - 3)
@param b: blink rate |
def git_env(self):
'Set the index file and prevent git from reading global configs.'
env = dict(os.environ)
for var in ["HOME", "XDG_CONFIG_HOME"]:
env.pop(var, None)
env["GIT_CONFIG_NOSYSTEM"] = "true"
# Weirdly, GIT_INDEX_FILE is interpreted relative to the work tre... | Set the index file and prevent git from reading global configs. |
def _ParseAndValidateRecord(self, parser_mediator, text_file_object):
"""Parses and validates an Opera global history record.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
text_file_object (dfvfs.TextFile): t... | Parses and validates an Opera global history record.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
text_file_object (dfvfs.TextFile): text file.
Returns:
bool: True if the record was successfully parse... |
def open(self, callback, instance=None, processor=None):
"""
Begin consuming messages.
:param string instance: (Optional) instance to use in the WebSocket URL
:param string processor: (Optional) processor to use in the WebSocket URL
"""
assert not self._closed
w... | Begin consuming messages.
:param string instance: (Optional) instance to use in the WebSocket URL
:param string processor: (Optional) processor to use in the WebSocket URL |
def get_cache(self, decorated_function, *args, **kwargs):
""" :meth:`WCacheStorage.get_cache` method implementation
"""
self.__check(decorated_function, *args, **kwargs)
if decorated_function in self._storage:
for i in self._storage[decorated_function]:
if i['instance']() == args[0]:
result = i['res... | :meth:`WCacheStorage.get_cache` method implementation |
def _unique_class_name(namespace: Dict[str, Any], uuid: uuid.UUID) -> str:
'''Generate unique to namespace name for a class using uuid.
**Parameters**
:``namespace``: the namespace to verify uniqueness against
:``uuid``: the "unique" portion of the name
**Return Value(s)**
A unique stri... | Generate unique to namespace name for a class using uuid.
**Parameters**
:``namespace``: the namespace to verify uniqueness against
:``uuid``: the "unique" portion of the name
**Return Value(s)**
A unique string (in namespace) using uuid. |
def __get_git_bin():
"""
Get git binary location.
:return: Check git location
"""
git = 'git'
alternatives = [
'/usr/bin/git'
]
for alt in alternatives:
if os.path.exists(alt):
git = alt
break
return git | Get git binary location.
:return: Check git location |
def repr_setup(self, name=None, col_names=None, col_types=None):
"""
This wasn't safe to pass into init because of the inheritance
"""
self._name = name or self._name
self._col_types = col_types or self._col_types | This wasn't safe to pass into init because of the inheritance |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.