code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def require_template_debug(f):
"""Decorated function is a no-op if TEMPLATE_DEBUG is False"""
def _(*args, **kwargs):
TEMPLATE_DEBUG = getattr(settings, 'TEMPLATE_DEBUG', False)
return f(*args, **kwargs) if TEMPLATE_DEBUG else ''
return _ | Decorated function is a no-op if TEMPLATE_DEBUG is False |
def CopyToDateTimeString(cls, time_elements_tuple, fraction_of_second):
"""Copies the time elements and fraction of second to a string.
Args:
time_elements_tuple (tuple[int, int, int, int, int, int]):
time elements, contains year, month, day of month, hours, minutes and
seconds.
... | Copies the time elements and fraction of second to a string.
Args:
time_elements_tuple (tuple[int, int, int, int, int, int]):
time elements, contains year, month, day of month, hours, minutes and
seconds.
fraction_of_second (decimal.Decimal): fraction of second, which must be a
... |
def do_db(self, arg):
"""
Usage:
db get_config
db use_local_file [<filename>]
db use_aws_instance [<instance_id>]
db aws_list_regions
db aws_get_region
db aws_set_region [<region_name>]
db aws_list_instances
db aws_create_in... | Usage:
db get_config
db use_local_file [<filename>]
db use_aws_instance [<instance_id>]
db aws_list_regions
db aws_get_region
db aws_set_region [<region_name>]
db aws_list_instances
db aws_create_instance [<instance_id> <size> <username> <p... |
def get_POST_data(self):
"""
Returns:
dict: POST data, which can be sent to webform using \
:py:mod:`urllib` or similar library
"""
self._postprocess()
# some fields need to be remapped (depends on type of media)
self._apply_mapping(
... | Returns:
dict: POST data, which can be sent to webform using \
:py:mod:`urllib` or similar library |
def until(self, regex):
"""Wait until the regex encountered
"""
logger.debug('waiting for %s', regex)
r = re.compile(regex, re.M)
self.tn.expect([r]) | Wait until the regex encountered |
def create_app(app_name, config={}, db=None, celery=None):
"""
App Factory 工具
策略是:
- 初始化app
- 根据app_name,装载指定的模块
- 尝试装载app.run_app
- 如果指定了`FANTASY_PRIMARY_NODE`,则尝试进行migrate操作
- 装载error handler
:return:
"""
track_mode = os.environ['FANTASY_TRACK_MODE'] ... | App Factory 工具
策略是:
- 初始化app
- 根据app_name,装载指定的模块
- 尝试装载app.run_app
- 如果指定了`FANTASY_PRIMARY_NODE`,则尝试进行migrate操作
- 装载error handler
:return: |
def start_with(self, x):
"""Returns all arguments beginning with given string
(or list thereof).
"""
_args = []
for arg in self.all:
if _is_collection(x):
for _x in x:
if arg.startswith(x):
_args.append(... | Returns all arguments beginning with given string
(or list thereof). |
def read_uint16(self):
"""Read 2 bytes."""
if self.pos + 2 > self.remaining_length:
return NC.ERR_PROTOCOL
msb = self.payload[self.pos]
self.pos += 1
lsb = self.payload[self.pos]
self.pos += 1
word = (msb << 8) + lsb
return NC... | Read 2 bytes. |
def find_matching_endpoints(self, discovery_ns):
"""
Compute current matching endpoints.
Evaluated as a property to defer evaluation.
"""
def match_func(operation, ns, rule):
return operation in self.matching_operations
return list(iter_endpoints(self.graph... | Compute current matching endpoints.
Evaluated as a property to defer evaluation. |
def run_analysis(self, argv):
"""Run this analysis"""
args = self._parser.parse_args(argv)
if not HAVE_ST:
raise RuntimeError(
"Trying to run fermipy analysis, but don't have ST")
gta = GTAnalysis(args.config, logging={'verbosity': 3},
... | Run this analysis |
def train_cv(self, num_folds, fold, random=None):
"""
Generates a training fold for cross-validation.
:param num_folds: the number of folds of cross-validation, eg 10
:type num_folds: int
:param fold: the current fold (0-based)
:type fold: int
:param random: the ... | Generates a training fold for cross-validation.
:param num_folds: the number of folds of cross-validation, eg 10
:type num_folds: int
:param fold: the current fold (0-based)
:type fold: int
:param random: the random number generator
:type random: Random
:return: ... |
def _antenna_uvw(uvw, antenna1, antenna2, chunks, nr_of_antenna):
""" numba implementation of antenna_uvw """
if antenna1.ndim != 1:
raise ValueError("antenna1 shape should be (row,)")
if antenna2.ndim != 1:
raise ValueError("antenna2 shape should be (row,)")
if uvw.ndim != 2 or uvw.s... | numba implementation of antenna_uvw |
def _fileobj_to_fd(fileobj):
""" Return a file descriptor from a file object. If
given an integer will simply return that integer back. """
if isinstance(fileobj, int):
fd = fileobj
else:
try:
fd = int(fileobj.fileno())
except (AttributeError, TypeError, ValueError):
... | Return a file descriptor from a file object. If
given an integer will simply return that integer back. |
def mget(self, ids, index=None, doc_type=None, **query_params):
"""
Get multi JSON documents.
ids can be:
list of tuple: (index, type, id)
list of ids: index and doc_type are required
"""
if not ids:
return []
body = []
for va... | Get multi JSON documents.
ids can be:
list of tuple: (index, type, id)
list of ids: index and doc_type are required |
def mpl_get_cb_bound_below_plot(ax):
"""
Return the coordinates for a colorbar axes below the provided axes object.
Take into account the changes of the axes due to aspect ratio settings.
Parts of this code are taken from the transforms.py file from matplotlib
Important: Use only AFTER fig.subplot... | Return the coordinates for a colorbar axes below the provided axes object.
Take into account the changes of the axes due to aspect ratio settings.
Parts of this code are taken from the transforms.py file from matplotlib
Important: Use only AFTER fig.subplots_adjust(...)
Use as:
======= |
def check_labels_file_header(filename):
"""Validate that filename corresponds to labels for the MNIST dataset."""
with tf.gfile.Open(filename, 'rb') as f:
magic = read32(f)
read32(f) # num_items, unused
if magic != 2049:
raise ValueError('Invalid magic number %d in MNIST file %s' % (magic,
... | Validate that filename corresponds to labels for the MNIST dataset. |
def _check_embedded_object(embedded_object, type, value, element_kind,
element_name):
# pylint: disable=redefined-builtin
"""
Check whether embedded-object-related parameters are ok.
"""
if embedded_object not in ('instance', 'object'):
raise ValueError(
... | Check whether embedded-object-related parameters are ok. |
def imap(requests, stream=False, size=2, exception_handler=None):
"""Concurrently converts a generator object of Requests to
a generator of Responses.
:param requests: a generator of Request objects.
:param stream: If True, the content will not be downloaded immediately.
:param size: Specifies the ... | Concurrently converts a generator object of Requests to
a generator of Responses.
:param requests: a generator of Request objects.
:param stream: If True, the content will not be downloaded immediately.
:param size: Specifies the number of requests to make at a time. default is 2
:param exception_h... |
def update_lazyevals(self):
"""Update all LazyEvals in self
self.lzy_evals must be set to LazyEval object(s) enough to
update all owned LazyEval objects.
"""
if self.lazy_evals is None:
return
elif isinstance(self.lazy_evals, LazyEval):
self.lazy_... | Update all LazyEvals in self
self.lzy_evals must be set to LazyEval object(s) enough to
update all owned LazyEval objects. |
def _prune_maps_to_sequences(self):
''' When we merge the SIFTS maps, we can extend the sequence maps such that they have elements in their domain that we removed
from the sequence e.g. 1A2P, residue 'B 3 ' is removed because Rosetta barfs on it. Here, we prune the maps so that their
d... | When we merge the SIFTS maps, we can extend the sequence maps such that they have elements in their domain that we removed
from the sequence e.g. 1A2P, residue 'B 3 ' is removed because Rosetta barfs on it. Here, we prune the maps so that their
domains do not have elements that were removed fr... |
def add(self, child):
"""
Adds a typed child object to the behavioral object.
@param child: Child object to be added.
"""
if isinstance(child, StateVariable):
self.add_state_variable(child)
elif isinstance(child, DerivedVariable):
self.add_derive... | Adds a typed child object to the behavioral object.
@param child: Child object to be added. |
def copy(self, empty=False):
"""returns an independent copy of the current object."""
# Create an empty object
newobject = self.__new__(self.__class__)
if empty:
return
# And fill it !
for prop in ["_properties","_side_properties",
... | returns an independent copy of the current object. |
def scp(args):
"""
Transfer files to or from EC2 instance.
Use "--" to separate scp args from aegea args:
aegea scp -- -r local_dir instance_name:~/remote_dir
"""
if args.scp_args[0] == "--":
del args.scp_args[0]
user_or_hostname_chars = string.ascii_letters + string.digits
... | Transfer files to or from EC2 instance.
Use "--" to separate scp args from aegea args:
aegea scp -- -r local_dir instance_name:~/remote_dir |
def setCommonInput(configObj, createOutwcs=True):
"""
The common interface interpreter for MultiDrizzle tasks which not only runs
'process_input()' but 'createImageObject()' and 'defineOutput()' as well to
fully setup all inputs for use with the rest of the MultiDrizzle steps either
as stand-alone t... | The common interface interpreter for MultiDrizzle tasks which not only runs
'process_input()' but 'createImageObject()' and 'defineOutput()' as well to
fully setup all inputs for use with the rest of the MultiDrizzle steps either
as stand-alone tasks or internally to MultiDrizzle itself.
Parameters
... |
def next_frame_savp_gan():
"""SAVP - GAN only model."""
hparams = next_frame_savp()
hparams.use_gan = True
hparams.use_vae = False
hparams.gan_loss_multiplier = 0.001
hparams.optimizer_adam_beta1 = 0.5
hparams.learning_rate_constant = 2e-4
hparams.gan_loss = "cross_entropy"
hparams.learning_rate_decay... | SAVP - GAN only model. |
def set_iscsi_info(self, target_name, lun, ip_address,
port='3260', auth_method=None, username=None,
password=None):
"""Set iscsi details of the system in uefi boot mode.
The initiator system is set with the target details like
IQN, LUN, IP, Port et... | Set iscsi details of the system in uefi boot mode.
The initiator system is set with the target details like
IQN, LUN, IP, Port etc.
:param target_name: Target Name for iscsi.
:param lun: logical unit number.
:param ip_address: IP address of the target.
:param port: port ... |
def import_parameters_from_file(parameters_file):
"""
Try importing a parameter dictionary from file.
We expect values in parameters_file to be defined as follows:
param1: value1
param2: [value2, value3]
"""
params = {}
with open(parameters_file, 'r') as f:
matches = re... | Try importing a parameter dictionary from file.
We expect values in parameters_file to be defined as follows:
param1: value1
param2: [value2, value3] |
def shapeRef_to_iriref(self, ref: ShExDocParser.ShapeRefContext) -> ShExJ.IRIREF:
""" shapeRef: ATPNAME_NS | ATPNAME_LN | '@' shapeExprLabel """
if ref.ATPNAME_NS():
return ShExJ.IRIREF(self._lookup_prefix(ref.ATPNAME_NS().getText()[1:]))
elif ref.ATPNAME_LN():
prefix, lo... | shapeRef: ATPNAME_NS | ATPNAME_LN | '@' shapeExprLabel |
def list_sensors(parent_class, sensor_items, filter, strategy, status,
use_python_identifiers, tuple, refresh):
"""Helper for implementing :meth:`katcp.resource.KATCPResource.list_sensors`
Parameters
----------
sensor_items : tuple of sensor-item tuples
As would be returned th... | Helper for implementing :meth:`katcp.resource.KATCPResource.list_sensors`
Parameters
----------
sensor_items : tuple of sensor-item tuples
As would be returned the items() method of a dict containing KATCPSensor objects
keyed by Python-identifiers.
parent_class: KATCPClientResource or ... |
def create_process(cmd, root_helper=None, addl_env=None, log_output=True):
"""Create a process object for the given command.
The return value will be a tuple of the process object and the
list of command arguments used to create it.
"""
if root_helper:
cmd = shlex.split(root_helper) + cmd
... | Create a process object for the given command.
The return value will be a tuple of the process object and the
list of command arguments used to create it. |
def _setup_no_fallback(parser):
"""Add the option, --tox-pyenv-no-fallback.
If this option is set, do not allow fallback to tox's built-in
strategy for looking up python executables if the call to `pyenv which`
by this plugin fails. This will allow the error to raise instead
of falling back to tox'... | Add the option, --tox-pyenv-no-fallback.
If this option is set, do not allow fallback to tox's built-in
strategy for looking up python executables if the call to `pyenv which`
by this plugin fails. This will allow the error to raise instead
of falling back to tox's default behavior. |
def _mark_lines(lines, sender):
"""Mark message lines with markers to distinguish signature lines.
Markers:
* e - empty line
* s - line identified as signature
* t - other i.e. ordinary text line
>>> mark_message_lines(['Some text', '', 'Bob'], 'Bob')
'tes'
"""
global EXTRACTOR
... | Mark message lines with markers to distinguish signature lines.
Markers:
* e - empty line
* s - line identified as signature
* t - other i.e. ordinary text line
>>> mark_message_lines(['Some text', '', 'Bob'], 'Bob')
'tes' |
def bam2fastq(self, input_bam, output_fastq,
output_fastq2=None, unpaired_fastq=None):
"""
Create command to convert BAM(s) to FASTQ(s).
:param str input_bam: Path to sequencing reads file to convert
:param output_fastq: Path to FASTQ to write
:param output_fas... | Create command to convert BAM(s) to FASTQ(s).
:param str input_bam: Path to sequencing reads file to convert
:param output_fastq: Path to FASTQ to write
:param output_fastq2: Path to (R2) FASTQ to write
:param unpaired_fastq: Path to unpaired FASTQ to write
:return str: Command ... |
def slip_reader(port, trace_function):
"""Generator to read SLIP packets from a serial port.
Yields one full SLIP packet at a time, raises exception on timeout or invalid data.
Designed to avoid too many calls to serial.read(1), which can bog
down on slow systems.
"""
partial_packet = None
... | Generator to read SLIP packets from a serial port.
Yields one full SLIP packet at a time, raises exception on timeout or invalid data.
Designed to avoid too many calls to serial.read(1), which can bog
down on slow systems. |
def generate(self):
"""Generate a new string and return it."""
key = self._propose_new_key()
while self.key_exists(key):
_logger.warning('Previous candidate was used.'
' Regenerating another...')
key = self._propose_new_key()
return key | Generate a new string and return it. |
def set_auto_reply(self, message, status=AutoReplyStatus.ALWAYS_ENABLED, start=None, end=None,
external_message=None, audience=AutoReplyAudience.ALL):
# type: (str, OutlookAccount.AutoReplyStatus, datetime, datetime, str, OutlookAccount.AutoReplyAudience) -> None
""" Set an automa... | Set an automatic reply for the account.
Args:
message (str): The message to be sent in replies. If external_message is provided this is the message sent
to internal recipients
status (OutlookAccount.AutoReplyStatus): Whether the auto-reply should be always enabled, scheduled,... |
def get_player_id(player):
"""
Returns the player ID(s) associated with the player name that is passed in.
There are instances where players have the same name so there are multiple
player IDs associated with it.
Parameters
----------
player : str
The desired player's name in 'Last... | Returns the player ID(s) associated with the player name that is passed in.
There are instances where players have the same name so there are multiple
player IDs associated with it.
Parameters
----------
player : str
The desired player's name in 'Last Name, First Name' format. Passing in
... |
def _headers(self, **kwargs):
""" Returns dict containing base headers for all requests to the server. """
headers = BASE_HEADERS.copy()
if self._token:
headers['X-Plex-Token'] = self._token
headers.update(kwargs)
return headers | Returns dict containing base headers for all requests to the server. |
def save(self, filename, content):
"""
default is to save a file from list of lines
"""
with open(filename, "w") as f:
if hasattr(content, '__iter__'):
f.write('\n'.join([row for row in content]))
else:
print('WRINGI CONTWETESWREWR'... | default is to save a file from list of lines |
def update(self, data):
"""Updates the object information based on live data, if there were any changes made. Any changes will be
automatically applied to the object, but will not be automatically persisted. You must manually call
`db.session.add(ami)` on the object.
Args:
d... | Updates the object information based on live data, if there were any changes made. Any changes will be
automatically applied to the object, but will not be automatically persisted. You must manually call
`db.session.add(ami)` on the object.
Args:
data (bunch): Data fetched from AWS ... |
def ontologyShapeTree(self):
"""
Returns a dict representing the ontology tree
Top level = {0:[top properties]}
Multi inheritance is represented explicitly
"""
treedict = {}
if self.all_shapes:
treedict[0] = self.toplayer_shapes
for element... | Returns a dict representing the ontology tree
Top level = {0:[top properties]}
Multi inheritance is represented explicitly |
def group_experiments(experiments: TomographyExperiment,
method: str = 'greedy') -> TomographyExperiment:
"""
Group experiments that are diagonal in a shared tensor product basis (TPB) to minimize number
of QPU runs.
Background
----------
Given some PauliTerm operator, th... | Group experiments that are diagonal in a shared tensor product basis (TPB) to minimize number
of QPU runs.
Background
----------
Given some PauliTerm operator, the 'natural' tensor product basis to
diagonalize this term is the one which diagonalizes each Pauli operator in the
product term-by-t... |
def _neg32(ins):
""" Negates top of the stack (32 bits in DEHL)
"""
output = _32bit_oper(ins.quad[2])
output.append('call __NEG32')
output.append('push de')
output.append('push hl')
REQUIRES.add('neg32.asm')
return output | Negates top of the stack (32 bits in DEHL) |
def _process_model_dict(self, d):
"""
Remove redundant items from a model's configuration dict.
Parameters
----------
d : dict
Modified in place.
Returns
-------
dict
Modified `d`.
"""
del d['model_type']
... | Remove redundant items from a model's configuration dict.
Parameters
----------
d : dict
Modified in place.
Returns
-------
dict
Modified `d`. |
def _is_valid_integer(self, inpt, metadata):
"""Checks if input is a valid integer value"""
if not isinstance(inpt, int):
return False
if metadata.get_minimum_integer() and inpt < metadata.get_maximum_integer():
return False
if metadata.get_maximum_integer() and i... | Checks if input is a valid integer value |
def received_message(self, message):
'''
Checks if the client has sent a ready message.
A ready message causes ``send()`` to be called on the
``parent end`` of the pipe.
Clients need to ensure that the pipe assigned to ``self.pipe`` is
the ``parent end`` of a pipe.
... | Checks if the client has sent a ready message.
A ready message causes ``send()`` to be called on the
``parent end`` of the pipe.
Clients need to ensure that the pipe assigned to ``self.pipe`` is
the ``parent end`` of a pipe.
This ensures completion of the underlying websocket c... |
def _append_path(new_path): # type: (str) -> None
""" Given a path string, append it to sys.path """
for path in sys.path:
path = os.path.abspath(path)
if new_path == path:
return
sys.path.append(new_path) | Given a path string, append it to sys.path |
def avail_images(call=None):
'''
Return a dict of all available VM images on the cloud provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
ret = ... | Return a dict of all available VM images on the cloud provider. |
def unlink(self):
"""
Unregisters the Link
"""
links = self.registry.get(self.source)
if self in links:
links.pop(links.index(self)) | Unregisters the Link |
def level(self):
"""Returns the current output level by querying the remote controller."""
ev = self._query_waiters.request(self.__do_query_level)
ev.wait(1.0)
return self._level | Returns the current output level by querying the remote controller. |
def _log_likelihood_per_sample(X, means, covars):
"""
Theta = (theta_1, theta_2, ... theta_M)
Likelihood of mixture parameters given data: L(Theta | X) = product_i P(x_i | Theta)
log likelihood: log L(Theta | X) = sum_i log(P(x_i | Theta))
and note that p(x_i | Theta) = sum_j prior_j * p(x_... | Theta = (theta_1, theta_2, ... theta_M)
Likelihood of mixture parameters given data: L(Theta | X) = product_i P(x_i | Theta)
log likelihood: log L(Theta | X) = sum_i log(P(x_i | Theta))
and note that p(x_i | Theta) = sum_j prior_j * p(x_i | theta_j)
Probability of sample x being generated fro... |
def normalize_ident(ident):
'''Splits a generic identifier.
If ``ident`` is a tuple, then ``(ident[0], ident[1])`` is returned.
Otherwise, ``(ident[0], None)`` is returned.
'''
if isinstance(ident, tuple) and len(ident) == 2:
return ident[0], ident[1] # content_id, subtopic_id
else:
... | Splits a generic identifier.
If ``ident`` is a tuple, then ``(ident[0], ident[1])`` is returned.
Otherwise, ``(ident[0], None)`` is returned. |
def _getColumnNeighborhood(self, centerColumn):
"""
Gets a neighborhood of columns.
Simply calls topology.neighborhood or topology.wrappingNeighborhood
A subclass can insert different topology behavior by overriding this method.
:param centerColumn (int)
The center of the neighborhood.
@... | Gets a neighborhood of columns.
Simply calls topology.neighborhood or topology.wrappingNeighborhood
A subclass can insert different topology behavior by overriding this method.
:param centerColumn (int)
The center of the neighborhood.
@returns (1D numpy array of integers)
The columns in the ... |
def _build_resolver(cls, session: AppSession):
'''Build resolver.'''
args = session.args
dns_timeout = args.dns_timeout
if args.timeout:
dns_timeout = args.timeout
if args.inet_family == 'IPv4':
family = IPFamilyPreference.ipv4_only
elif args.ine... | Build resolver. |
def multi_pop(d, *args):
""" pops multiple keys off a dict like object """
retval = {}
for key in args:
if key in d:
retval[key] = d.pop(key)
return retval | pops multiple keys off a dict like object |
def read_unsigned_var_int(file_obj):
"""Read a value using the unsigned, variable int encoding."""
result = 0
shift = 0
while True:
byte = struct.unpack(b"<B", file_obj.read(1))[0]
result |= ((byte & 0x7F) << shift)
if (byte & 0x80) == 0:
break
shift += 7
... | Read a value using the unsigned, variable int encoding. |
def isEnabled( self ):
"""
Returns whether or not this node is enabled.
"""
if ( self._disableWithLayer and self._layer ):
lenabled = self._layer.isEnabled()
else:
lenabled = True
return self._enabled and lenabled | Returns whether or not this node is enabled. |
def robust_topological_sort(graph: Graph) -> list:
"""Identify strongly connected components then perform a topological sort of those components."""
assert check_argument_types()
components = strongly_connected_components(graph)
node_component = {}
for component in components:
for node in component:
nod... | Identify strongly connected components then perform a topological sort of those components. |
def subscribe(self, stream, callback, transform=""):
"""Given a stream, a callback and an optional transform, sets up the subscription"""
if self.status == "disconnected" or self.status == "disconnecting" or self.status == "connecting":
self.connect()
if self.status is not "connected... | Given a stream, a callback and an optional transform, sets up the subscription |
def do(self, arg):
".example - This is an example plugin for the command line debugger"
print "This is an example command."
print "%s.do(%r, %r):" % (__name__, self, arg)
print " last event", self.lastEvent
print " prefix", self.cmdprefix
print " arguments", self.split_tokens(arg) | .example - This is an example plugin for the command line debugger |
def get_code(self):
"""Opens the link and returns the response's content."""
if self.code is None:
self.code = urlopen(self.url).read()
return self.code | Opens the link and returns the response's content. |
def tparse(instring, lenout=_default_len_out):
"""
Parse a time string and return seconds past the J2000
epoch on a formal calendar.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tparse_c.html
:param instring: Input time string, UTC.
:type instring: str
:param lenout: Available s... | Parse a time string and return seconds past the J2000
epoch on a formal calendar.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tparse_c.html
:param instring: Input time string, UTC.
:type instring: str
:param lenout: Available space in output error message string.
:type lenout: int
... |
def start(self, max):
"""
Displays the progress bar for a given maximum value.
:param float max: Maximum value of the progress bar.
"""
try:
self.widget.max = max
display(self.widget)
except:
pass | Displays the progress bar for a given maximum value.
:param float max: Maximum value of the progress bar. |
def get_metrics(self, name=None):
"""Get metrics for this operator.
Args:
name(str, optional): Only return metrics matching `name`, where `name` can be a regular expression. If
`name` is not supplied, then all metrics for this operator are returned.
Returns:
... | Get metrics for this operator.
Args:
name(str, optional): Only return metrics matching `name`, where `name` can be a regular expression. If
`name` is not supplied, then all metrics for this operator are returned.
Returns:
list(Metric): List of matching metrics... |
def load_json(filename):
"""Load a json file as a dictionary"""
try:
if PY2:
args = 'rb'
else:
args = 'r'
with open(filename, args) as fid:
data = json.load(fid)
return data, None
except Exception as err:
return None, str(err) | Load a json file as a dictionary |
def register_user(self, data):
""" Parses input and register user """
error = False
msg = ""
email_re = re.compile(
r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\0... | Parses input and register user |
def mutation_jwt_refresh_token_required(fn):
"""
A decorator to protect a mutation.
If you decorate anmutation with this, it will ensure that the requester
has a valid refresh token before allowing the mutation to be called.
"""
@wraps(fn)
def wrapper(cls, *args, **kwargs):
token = ... | A decorator to protect a mutation.
If you decorate anmutation with this, it will ensure that the requester
has a valid refresh token before allowing the mutation to be called. |
def get_one(cls, db, *args, **kwargs):
"""
Returns an object that corresponds to given query or ``None``.
Example::
item = Item.get_one(db, {'title': u'Hello'})
"""
data = db[cls.collection].find_one(*args, **kwargs)
if data:
return cls.wrap_inc... | Returns an object that corresponds to given query or ``None``.
Example::
item = Item.get_one(db, {'title': u'Hello'}) |
def get_handler(self, request):
"""
Get callable from JSON RPC request
:param RPCRequest request: JSON RPC request
:return: Method
:rtype: callable
"""
try:
f = self._json_rpc_methods[request.method]
except (AttributeError, KeyError): # prag... | Get callable from JSON RPC request
:param RPCRequest request: JSON RPC request
:return: Method
:rtype: callable |
def set_data_matrix_chunk_size(df_shape, max_chunk_kb, elem_per_kb):
"""
Sets chunk size to use for writing data matrix.
Note. Calculation used here is for compatibility with cmapM and cmapR.
Input:
- df_shape (tuple): shape of input data_df.
- max_chunk_kb (int, default=1024): The m... | Sets chunk size to use for writing data matrix.
Note. Calculation used here is for compatibility with cmapM and cmapR.
Input:
- df_shape (tuple): shape of input data_df.
- max_chunk_kb (int, default=1024): The maximum number of KB a given chunk will occupy
- elem_per_kb (int): Number... |
def autobuild_arm_program(elfname, test_dir=os.path.join('firmware', 'test'), patch=True):
"""
Build the an ARM module for all targets and build all unit tests. If pcb files are given, also build those.
"""
try:
#Build for all targets
family = utilities.get_family('module_settings.json'... | Build the an ARM module for all targets and build all unit tests. If pcb files are given, also build those. |
def mirrored(setup):
"""Convience decorator for setUp in testcases::
@mirrored
def setUp(self, mirror, mock):
...
is the same as::
def setUp(self):
self.mirror, self.mock = mirror()
mirror, mock = self.mirror, self.mock
...
"""
@... | Convience decorator for setUp in testcases::
@mirrored
def setUp(self, mirror, mock):
...
is the same as::
def setUp(self):
self.mirror, self.mock = mirror()
mirror, mock = self.mirror, self.mock
... |
def permission_denied(request, template_name=None, extra_context=None):
"""
Default 403 handler.
Templates: `403.html`
Context:
request_path
The path of the requested URL (e.g., '/app/pages/bad_page/')
"""
if template_name is None:
template_name = ('403.html', 'autho... | Default 403 handler.
Templates: `403.html`
Context:
request_path
The path of the requested URL (e.g., '/app/pages/bad_page/') |
def _merge_sections(sec_a, sec_b):
'''Merge two sections
Merges sec_a into sec_b and sets sec_a attributes to default
'''
sec_b.ids = list(sec_a.ids) + list(sec_b.ids[1:])
sec_b.ntype = sec_a.ntype
sec_b.pid = sec_a.pid
sec_a.ids = []
sec_a.pid = -1
sec_a.ntype = 0 | Merge two sections
Merges sec_a into sec_b and sets sec_a attributes to default |
def bulk_create_posts(self, posts, post_categories, post_tags, post_media_attachments):
"""
Actually do a db bulk creation of posts, and link up the many-to-many fields
:param posts: the list of Post objects to bulk create
:param post_categories: a mapping of Categories to add to newly ... | Actually do a db bulk creation of posts, and link up the many-to-many fields
:param posts: the list of Post objects to bulk create
:param post_categories: a mapping of Categories to add to newly created Posts
:param post_tags: a mapping of Tags to add to newly created Posts
:param post_... |
def _do_exit(self, cmd, args):
"""\
Exit shell.
exit | C-D Exit to the parent shell.
exit root | end Exit to the root shell.
exit all Exit to the command line.
"""
if cmd == 'end':
if not args:
return... | \
Exit shell.
exit | C-D Exit to the parent shell.
exit root | end Exit to the root shell.
exit all Exit to the command line. |
def evolved_transformer_decoder(decoder_input,
encoder_output,
decoder_self_attention_bias,
encoder_decoder_attention_bias,
hparams,
cache=None,
... | Evolved Transformer decoder. See arxiv.org/abs/1901.11117 for more details.
Args:
decoder_input: a Tensor.
encoder_output: a Tensor.
decoder_self_attention_bias: bias Tensor for self-attention (see
common_attention.attention_bias()).
encoder_decoder_attention_bias: bias Tensor for encoder-decod... |
def _validate_name(name):
"""Pre-flight ``Bucket`` name validation.
:type name: str or :data:`NoneType`
:param name: Proposed bucket name.
:rtype: str or :data:`NoneType`
:returns: ``name`` if valid.
"""
if name is None:
return
# The first and las characters must be alphanumer... | Pre-flight ``Bucket`` name validation.
:type name: str or :data:`NoneType`
:param name: Proposed bucket name.
:rtype: str or :data:`NoneType`
:returns: ``name`` if valid. |
def compute_panel(cls, data, scales, params):
"""
Positions must override this function
Notes
-----
Make necessary adjustments to the columns in the dataframe.
Create the position transformation functions and
use self.transform_position() do the rest.
S... | Positions must override this function
Notes
-----
Make necessary adjustments to the columns in the dataframe.
Create the position transformation functions and
use self.transform_position() do the rest.
See Also
--------
position_jitter.compute_panel |
def _run_evolve(ssm_file, cnv_file, work_dir, data):
"""Run evolve.py to infer subclonal composition.
"""
exe = os.path.join(os.path.dirname(sys.executable), "evolve.py")
assert os.path.exists(exe), "Could not find evolve script for PhyloWGS runs."
out_dir = os.path.join(work_dir, "evolve")
out_... | Run evolve.py to infer subclonal composition. |
def invoke(self):
"""
Run it, return whether to end training.
"""
self._iter += 1
if self._iter - max(self._trainer.best_iter, self._annealed_iter) >= self._patience:
if self._annealed_times >= self._anneal_times:
logging.info("ending")
... | Run it, return whether to end training. |
def process_next_message(self, timeout):
"""Processes the next message coming from the workers."""
message = self.worker_manager.receive(timeout)
if isinstance(message, Acknowledgement):
self.task_manager.task_start(message.task, message.worker)
elif isinstance(message, Resu... | Processes the next message coming from the workers. |
def get_handlers(self, kind=None):
"""
Retrieves the handlers of the given kind. If kind is None, all handlers
are returned.
:param kind: The kind of the handlers to return
:return: A list of handlers, or an empty list
"""
with self._lock:
if kind is ... | Retrieves the handlers of the given kind. If kind is None, all handlers
are returned.
:param kind: The kind of the handlers to return
:return: A list of handlers, or an empty list |
def close(self):
"""
Stop analyzing the current document and come up with a final
prediction.
:returns: The ``result`` attribute, a ``dict`` with the keys
`encoding`, `confidence`, and `language`.
"""
# Don't bother with checks if we're already done
... | Stop analyzing the current document and come up with a final
prediction.
:returns: The ``result`` attribute, a ``dict`` with the keys
`encoding`, `confidence`, and `language`. |
def _value_and_gradients(fn, fn_arg_list, result=None, grads=None, name=None):
"""Helper to `maybe_call_fn_and_grads`."""
with tf.compat.v1.name_scope(name, 'value_and_gradients',
[fn_arg_list, result, grads]):
def _convert_to_tensor(x, name):
ctt = lambda x_: x_ if x_ is N... | Helper to `maybe_call_fn_and_grads`. |
def _add_field_column(self, field): # pragma: no cover
"""Add a column for a given label field."""
@self.add_column(name=field)
def get_my_label(cluster_id):
return self.cluster_meta.get(field, cluster_id) | Add a column for a given label field. |
def getVariable(self, name):
"""
Get the variable with the corresponding name.
Args:
name: Name of the variable to be found.
Raises:
TypeError: if the specified variable does not exist.
"""
return lock_and_call(
lambda: Variable(self.... | Get the variable with the corresponding name.
Args:
name: Name of the variable to be found.
Raises:
TypeError: if the specified variable does not exist. |
def get_owned_games(self, steamID, include_appinfo=1,
include_played_free_games=0, appids_filter=None, format=None):
"""Request a list of games owned by a given steam id.
steamID: The users id
include_appinfo: boolean.
include_played_free_games: boolean.
appids_filte... | Request a list of games owned by a given steam id.
steamID: The users id
include_appinfo: boolean.
include_played_free_games: boolean.
appids_filter: a json encoded list of app ids.
format: Return format. None defaults to json. (json, xml, vdf) |
def dAbr_dV(dSf_dVa, dSf_dVm, dSt_dVa, dSt_dVm, Sf, St):
""" Partial derivatives of squared flow magnitudes w.r.t voltage.
Computes partial derivatives of apparent power w.r.t active and
reactive power flows. Partial derivative must equal 1 for lines
with zero flow to avoid division by zer... | Partial derivatives of squared flow magnitudes w.r.t voltage.
Computes partial derivatives of apparent power w.r.t active and
reactive power flows. Partial derivative must equal 1 for lines
with zero flow to avoid division by zero errors (1 comes from
L'Hopital). |
def build_error_handler(*tasks):
"""
Provides a generic error function that packages a flask_buzz exception
so that it can be handled nicely by the flask error handler::
app.register_error_handler(
FlaskBuzz, FlaskBuzz.build_error_handler(),
)
Ad... | Provides a generic error function that packages a flask_buzz exception
so that it can be handled nicely by the flask error handler::
app.register_error_handler(
FlaskBuzz, FlaskBuzz.build_error_handler(),
)
Additionally, extra tasks may be applied to the error p... |
def find_multiline_pattern(self, regexp, cursor, findflag):
"""Reimplement QTextDocument's find method
Add support for *multiline* regular expressions"""
pattern = to_text_string(regexp.pattern())
text = to_text_string(self.toPlainText())
try:
regobj = re.comp... | Reimplement QTextDocument's find method
Add support for *multiline* regular expressions |
def version_history(soup, html_flag=True):
"extract the article version history details"
convert = lambda xml_string: xml_to_html(html_flag, xml_string)
version_history = []
related_object_tags = raw_parser.related_object(raw_parser.article_meta(soup))
for tag in related_object_tags:
article... | extract the article version history details |
def print_variables_info(self, output_file=sys.stdout):
"""Print variables information in human readble format."""
table = (' name | type size \n' +
'---------+-------------------------\n')
for name, var_info in list(self.variables.items()):
table +=... | Print variables information in human readble format. |
def locate_file(filename, env_var='', directory=''):
"""
Locates a file given an environment variable or directory
:param filename: filename to search for
:param env_var: environment variable to look under
:param directory: directory to look in
:return: (string) absolute path to filename or None... | Locates a file given an environment variable or directory
:param filename: filename to search for
:param env_var: environment variable to look under
:param directory: directory to look in
:return: (string) absolute path to filename or None if not found |
def has_perm(self, perm):
"""
Checks if key has the given django's auth Permission
"""
if '.' in perm:
app_label, codename = perm.split('.')
permissions = self.permissions.filter(
content_type__app_label = app_label,
codename = cod... | Checks if key has the given django's auth Permission |
def add_filter_rule(
self, name, condition, filters, actions, active=1, way='in'):
"""
:param: name filter name
:param: condition allof or anyof
:param: filters dict of filters
:param: actions dict of actions
:param: way string discribing if filter is for 'in'... | :param: name filter name
:param: condition allof or anyof
:param: filters dict of filters
:param: actions dict of actions
:param: way string discribing if filter is for 'in' or 'out' messages
:returns: list of user's zobjects.FilterRule |
def _flatten(self, element):
"""Recursively enter and extract text from all child
elements."""
result = [(element.text or '')]
if element.attrib.get('alt'):
result.append(Symbol(element.attrib.get('alt')).textbox)
for sel in element:
result.append(self._fl... | Recursively enter and extract text from all child
elements. |
def check_ok_button(self):
"""Helper to enable or not the OK button."""
login = self.login.text()
password = self.password.text()
url = self.url.text()
if self.layers.count() >= 1 and login and password and url:
self.ok_button.setEnabled(True)
else:
... | Helper to enable or not the OK button. |
def limit_spec(self, spec):
"""
Whenever we do a Pseudo ID lookup from the database, we need to limit
based on the memberships -> organization -> jurisdiction, so we scope
the resolution.
"""
if list(spec.keys()) == ['name']:
# if we're just resolving on name,... | Whenever we do a Pseudo ID lookup from the database, we need to limit
based on the memberships -> organization -> jurisdiction, so we scope
the resolution. |
def return_self_updater(func):
'''
Run func, but still return v. Useful for using knowledge.update with operates like append, extend, etc.
e.g. return_self(lambda k,v: v.append('newobj'))
'''
@functools.wraps(func)
def decorator(k,v):
func(k,v)
return v
return decorator | Run func, but still return v. Useful for using knowledge.update with operates like append, extend, etc.
e.g. return_self(lambda k,v: v.append('newobj')) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.