code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _set_link_oam(self, v, load=False):
"""
Setter method for link_oam, mapped from YANG variable /protocol/link_oam (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_link_oam is considered as a private
method. Backends looking to populate this variable sho... | Setter method for link_oam, mapped from YANG variable /protocol/link_oam (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_link_oam is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_link_oam() di... |
def counts(args):
"""
%prog counts vcffile
Collect allele counts from RO and AO fields.
"""
p = OptionParser(counts.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
vcffile, = args
vcf_reader = vcf.Reader(open(vcffile))
for r in ... | %prog counts vcffile
Collect allele counts from RO and AO fields. |
def parseHolidays(holidaysStr, holidayMap=None):
"""
Takes a string like NZ[WTL,Nelson],AU[*],Northern Ireland and builds a HolidaySum from it
"""
if holidayMap is None:
holidayMap = _HOLIDAY_MAP
retval = holidays.HolidayBase()
retval.country = None
holidaysStr = holidaysStr.strip()
... | Takes a string like NZ[WTL,Nelson],AU[*],Northern Ireland and builds a HolidaySum from it |
def decode_param(data):
"""Decode any parameter to a byte sequence.
:param data: byte sequence representing an LLRP parameter.
:returns dict, bytes: where dict is {'Type': <decoded type>, 'Data':
<decoded data>} and bytes is the remaining bytes trailing the bytes we
could decode.
"""
... | Decode any parameter to a byte sequence.
:param data: byte sequence representing an LLRP parameter.
:returns dict, bytes: where dict is {'Type': <decoded type>, 'Data':
<decoded data>} and bytes is the remaining bytes trailing the bytes we
could decode. |
def varintSize(value):
"""Compute the size of a varint value."""
if value <= 0x7f: return 1
if value <= 0x3fff: return 2
if value <= 0x1fffff: return 3
if value <= 0xfffffff: return 4
if value <= 0x7ffffffff: return 5
if value <= 0x3ffffffffff: return 6
if value <= 0x1ffffffffffff: return 7
if value <... | Compute the size of a varint value. |
def dbmax50years(self, value=None):
""" Corresponds to IDD Field `dbmax50years`
50-year return period values for maximum extreme dry-bulb temperature
Args:
value (float): value for IDD Field `dbmax50years`
Unit: C
if `value` is None it will not be ch... | Corresponds to IDD Field `dbmax50years`
50-year return period values for maximum extreme dry-bulb temperature
Args:
value (float): value for IDD Field `dbmax50years`
Unit: C
if `value` is None it will not be checked against the
specification a... |
async def stop(self):
"""
Stop recording.
"""
if self.__container:
for track, context in self.__tracks.items():
if context.task is not None:
context.task.cancel()
context.task = None
for packet in con... | Stop recording. |
def serve(self, host='127.0.0.1', port=5000):
"""Serve predictions as an API endpoint."""
from meinheld import server, middleware
# self.app.run(host=host, port=port)
server.listen((host, port))
server.run(middleware.WebSocketMiddleware(self.app)) | Serve predictions as an API endpoint. |
def p_bexpr_func(p):
""" bexpr : ID bexpr
"""
args = make_arg_list(make_argument(p[2], p.lineno(2)))
p[0] = make_call(p[1], p.lineno(1), args)
if p[0] is None:
return
if p[0].token in ('STRSLICE', 'VAR', 'STRING'):
entry = SYMBOL_TABLE.access_call(p[1], p.lineno(1))
entr... | bexpr : ID bexpr |
def list_user_logins_users(self, user_id):
"""
List user logins.
Given a user ID, return that user's logins for the given account.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - user_id
"""ID"""
path["user_id"] = user... | List user logins.
Given a user ID, return that user's logins for the given account. |
def single(self, predicate=None):
'''The only element (which satisfies a condition).
If the predicate is omitted or is None this query returns the only
element in the sequence; otherwise, it returns the only element in
the sequence for which the predicate evaluates to True. Exceptions a... | The only element (which satisfies a condition).
If the predicate is omitted or is None this query returns the only
element in the sequence; otherwise, it returns the only element in
the sequence for which the predicate evaluates to True. Exceptions are
raised if there is either no such ... |
def _embedding_classical_mds(matrix, dimensions=3, additive_correct=False):
"""
Private method to calculate CMDS embedding
:param dimensions: (int)
:return: coordinate matrix (np.array)
"""
if additive_correct:
dbc = double_centre(_additive_correct(matrix))
else:
dbc = double... | Private method to calculate CMDS embedding
:param dimensions: (int)
:return: coordinate matrix (np.array) |
def create_or_update_tags(self, tags):
"""
Creates new tags or updates existing tags for an Auto Scaling group.
:type tags: List of :class:`boto.ec2.autoscale.tag.Tag`
:param tags: The new or updated tags.
"""
params = {}
for i, tag in enumerate(tags):
... | Creates new tags or updates existing tags for an Auto Scaling group.
:type tags: List of :class:`boto.ec2.autoscale.tag.Tag`
:param tags: The new or updated tags. |
def GetLinkedFileEntry(self):
"""Retrieves the linked file entry, e.g. for a symbolic link.
Returns:
APFSFileEntry: linked file entry or None if not available.
"""
link = self._GetLink()
if not link:
return None
# TODO: is there a way to determine the identifier here?
link_iden... | Retrieves the linked file entry, e.g. for a symbolic link.
Returns:
APFSFileEntry: linked file entry or None if not available. |
def group(self):
"""returns the community.Group class for the current group"""
split_count = self._url.lower().find("/content/")
len_count = len('/content/')
gURL = self._url[:self._url.lower().find("/content/")] + \
"/community/" + self._url[split_count+ len_count:]#self.__a... | returns the community.Group class for the current group |
def _handle_force_timeout(self) -> None:
"""Called by IOLoop periodically to ask libcurl to process any
events it may have forgotten about.
"""
while True:
try:
ret, num_handles = self._multi.socket_all()
except pycurl.error as e:
r... | Called by IOLoop periodically to ask libcurl to process any
events it may have forgotten about. |
def add_new(self, command):
"""Add a new entry to the queue."""
self.queue[self.next_key] = command
self.queue[self.next_key]['status'] = 'queued'
self.queue[self.next_key]['returncode'] = ''
self.queue[self.next_key]['stdout'] = ''
self.queue[self.next_key]['stderr'] = '... | Add a new entry to the queue. |
def calc_requiredrelease_v2(self):
"""Calculate the water release (immediately downstream) required for
reducing drought events.
Required control parameter:
|NearDischargeMinimumThreshold|
Required derived parameter:
|dam_derived.TOY|
Calculated flux sequence:
|RequiredRelease|
... | Calculate the water release (immediately downstream) required for
reducing drought events.
Required control parameter:
|NearDischargeMinimumThreshold|
Required derived parameter:
|dam_derived.TOY|
Calculated flux sequence:
|RequiredRelease|
Basic equation:
:math:`Required... |
def register_options(cls, register):
"""Register an option to make capturing snapshots optional.
This class is intended to be extended by Jvm resolvers (coursier and ivy), and the option name should reflect that.
"""
super(JvmResolverBase, cls).register_options(register)
# TODO This flag should be d... | Register an option to make capturing snapshots optional.
This class is intended to be extended by Jvm resolvers (coursier and ivy), and the option name should reflect that. |
def remove_link_type_vlan(enode, name, shell=None):
"""
Delete a virtual link.
Deletes a vlan device with the name {name}.
Will raise an expection if the port is not already present.
:param enode: Engine node to communicate with.
:type enode: topology.platforms.base.BaseNode
:param str nam... | Delete a virtual link.
Deletes a vlan device with the name {name}.
Will raise an expection if the port is not already present.
:param enode: Engine node to communicate with.
:type enode: topology.platforms.base.BaseNode
:param str name: specifies the name of the new
virtual device.
:param... |
def aggregate_cap_val(self, conn, **kwargs):
'''
Returns the normalised feedin profile and installed capacity for
a given region.
Parameters
----------
region : Region instance
region.geom : shapely.geometry object
Geo-spatial data with information fo... | Returns the normalised feedin profile and installed capacity for
a given region.
Parameters
----------
region : Region instance
region.geom : shapely.geometry object
Geo-spatial data with information for location/region-shape. The
geometry can be a polygo... |
def add_child(self, node, as_last=True):
"""
Add the given child to the current list of children.
The new child is appended as the last child if ``as_last``
is ``True``, or as the first child if ``as_last`` is ``False``.
This call updates the ``__parent`` and ``__level`` fields... | Add the given child to the current list of children.
The new child is appended as the last child if ``as_last``
is ``True``, or as the first child if ``as_last`` is ``False``.
This call updates the ``__parent`` and ``__level`` fields of ``node``.
:param node: the child node to be adde... |
def create_data_and_metadata_io_handler(self, io_handler_delegate):
"""Create an I/O handler that reads and writes a single data_and_metadata.
:param io_handler_delegate: A delegate object :py:class:`DataAndMetadataIOHandlerInterface`
.. versionadded:: 1.0
Scriptable: No
"""
... | Create an I/O handler that reads and writes a single data_and_metadata.
:param io_handler_delegate: A delegate object :py:class:`DataAndMetadataIOHandlerInterface`
.. versionadded:: 1.0
Scriptable: No |
def process_refs_for_node(cls, manifest, current_project, node):
"""Given a manifest and a node in that manifest, process its refs"""
target_model = None
target_model_name = None
target_model_package = None
for ref in node.refs:
if len(ref) == 1:
targ... | Given a manifest and a node in that manifest, process its refs |
def neg_loglik(self,beta):
""" Creates the negative log-likelihood of the model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
The negative logliklihood of the model
""" ... | Creates the negative log-likelihood of the model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
The negative logliklihood of the model |
def mkFilter(parts):
"""Convert a filter-convertable thing into a filter
@param parts: a filter, an endpoint, a callable, or a list of any of these.
"""
# Convert the parts into a list, and pass to mkCompoundFilter
if parts is None:
parts = [BasicServiceEndpoint]
try:
parts = l... | Convert a filter-convertable thing into a filter
@param parts: a filter, an endpoint, a callable, or a list of any of these. |
def forward(self, observations):
""" Model forward pass """
input_data = self.input_block(observations)
advantage_features, value_features = self.backbone(input_data)
log_histogram = self.q_head(advantage_features, value_features)
return log_histogram | Model forward pass |
def unsign(self, signed_value):
"""Unsigns the given string."""
signed_value = want_bytes(signed_value)
sep = want_bytes(self.sep)
if sep not in signed_value:
raise BadSignature('No %r found in value' % self.sep)
value, sig = signed_value.rsplit(sep, 1)
if sel... | Unsigns the given string. |
def chain(request):
"""shows how the XmlQuerySetChain can be used instead of @toxml decorator"""
bars = foobar_models.Bar.objects.all()
bazs = foobar_models.Baz.objects.all()
qsc = XmlQuerySetChain(bars, bazs)
return HttpResponse(tree.xml(qsc), mimetype='text/xml') | shows how the XmlQuerySetChain can be used instead of @toxml decorator |
def _is_known_signed_by_dtype(dt):
"""Helper returning True if dtype is known to be signed."""
return {
tf.float16: True,
tf.float32: True,
tf.float64: True,
tf.int8: True,
tf.int16: True,
tf.int32: True,
tf.int64: True,
}.get(dt.base_dtype, False) | Helper returning True if dtype is known to be signed. |
def start_output (self):
"""
Start log output.
"""
# map with spaces between part name and value
if self.logparts is None:
parts = Fields.keys()
else:
parts = self.logparts
values = (self.part(x) for x in parts)
# maximum indent for... | Start log output. |
def reverse_cyk_transforms(root):
# type: (Nonterminal) -> Nonterminal
"""
Reverse transformation made to grammar before CYK.
Performs following steps:
- transform from chomsky normal form
- restore unit rules
- restore epsilon rules
:param root: Root node... | Reverse transformation made to grammar before CYK.
Performs following steps:
- transform from chomsky normal form
- restore unit rules
- restore epsilon rules
:param root: Root node of the parsed tree.
:return: Restored parsed tree. |
def filter_users_by_email(email):
"""Return list of users by email address
Typically one, at most just a few in length. First we look through
EmailAddress table, than customisable User model table. Add results
together avoiding SQL joins and deduplicate.
"""
from .models import EmailAddress
... | Return list of users by email address
Typically one, at most just a few in length. First we look through
EmailAddress table, than customisable User model table. Add results
together avoiding SQL joins and deduplicate. |
def make_example_scripts_docs(spth, npth, rpth):
"""
Generate rst docs from example scripts. Arguments `spth`, `npth`,
and `rpth` are the top-level scripts directory, the top-level
notebooks directory, and the top-level output directory within the
docs respectively.
"""
# Ensure that outpu... | Generate rst docs from example scripts. Arguments `spth`, `npth`,
and `rpth` are the top-level scripts directory, the top-level
notebooks directory, and the top-level output directory within the
docs respectively. |
def copy(self, name=None):
"""
Creates a copy of this attribute.
:param name: the new name, uses the old one if None
:type name: str
:return: the copy of the attribute
:rtype: Attribute
"""
if name is None:
return Attribute(
ja... | Creates a copy of this attribute.
:param name: the new name, uses the old one if None
:type name: str
:return: the copy of the attribute
:rtype: Attribute |
def generate_gallery_rst(app):
"""Generate the Main examples gallery reStructuredText
Start the sphinx-gallery configuration and recursively scan the examples
directories in order to populate the examples gallery
"""
try:
plot_gallery = eval(app.builder.config.plot_gallery)
except TypeE... | Generate the Main examples gallery reStructuredText
Start the sphinx-gallery configuration and recursively scan the examples
directories in order to populate the examples gallery |
def _normalize_tags_type(self, tags, device_name=None, metric_name=None):
"""
Normalize tags contents and type:
- append `device_name` as `device:` tag
- normalize tags type
- doesn't mutate the passed list, returns a new list
"""
normalized_tags = []
if ... | Normalize tags contents and type:
- append `device_name` as `device:` tag
- normalize tags type
- doesn't mutate the passed list, returns a new list |
def qsub(command, queue=None, cwd=True, name=None, deps=[], stdout='',
stderr='', env=[], array=None, context='grid', hostname=None,
memfree=None, hvmem=None, gpumem=None, pe_opt=None, io_big=False):
"""Submits a shell job to a given grid queue
Keyword parameters:
command
The command to be submitted... | Submits a shell job to a given grid queue
Keyword parameters:
command
The command to be submitted to the grid
queue
A valid queue name or None, to use the default queue
cwd
If the job should change to the current working directory before starting
name
An optional name to set for the job. ... |
def instance_cache(cls, func):
""" Save the cache to `self`
This decorator take it for granted that the decorated function
is a method. The first argument of the function is `self`.
:param func: function to decorate
:return: the decorator
"""
@functools.wraps(... | Save the cache to `self`
This decorator take it for granted that the decorated function
is a method. The first argument of the function is `self`.
:param func: function to decorate
:return: the decorator |
def __draw_leaf_density(self):
"""!
@brief Display densities by filling blocks by appropriate colors.
"""
leafs = self.__directory.get_leafs()
density_scale = leafs[-1].get_density()
if density_scale == 0.0: density_scale = 1.0
for block in leafs:
... | !
@brief Display densities by filling blocks by appropriate colors. |
def smooth(y, radius, mode='two_sided', valid_only=False):
'''
Smooth signal y, where radius is determines the size of the window
mode='twosided':
average over the window [max(index - radius, 0), min(index + radius, len(y)-1)]
mode='causal':
average over the window [max(index - radius, ... | Smooth signal y, where radius is determines the size of the window
mode='twosided':
average over the window [max(index - radius, 0), min(index + radius, len(y)-1)]
mode='causal':
average over the window [max(index - radius, 0), index]
valid_only: put nan in entries where the full-sized win... |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'expansions') and self.expansions is not None:
_dict['expansions'] = [x._to_dict() for x in self.expansions]
return _dict | Return a json dictionary representing this model. |
def url_as_file(url, ext=None):
"""
Context manager that GETs a given `url` and provides it as a local file.
The file is in a closed state upon entering the context,
and removed when leaving it, if still there.
To give the file name a specific extension, use `ext`;
the exte... | Context manager that GETs a given `url` and provides it as a local file.
The file is in a closed state upon entering the context,
and removed when leaving it, if still there.
To give the file name a specific extension, use `ext`;
the extension can optionally include a separating dot,
... |
def add_style(self, name, fg=None, bg=None, options=None):
"""
Adds a new style
"""
style = Style(name)
if fg is not None:
style.fg(fg)
if bg is not None:
style.bg(bg)
if options is not None:
if "bold" in options:
... | Adds a new style |
def get_series(self, key):
"""Get a series object from TempoDB given its key.
:param string key: a string name for the series
:rtype: :class:`tempodb.response.Response` with a
:class:`tempodb.protocol.objects.Series` data payload"""
url = make_series_url(key)
re... | Get a series object from TempoDB given its key.
:param string key: a string name for the series
:rtype: :class:`tempodb.response.Response` with a
:class:`tempodb.protocol.objects.Series` data payload |
def filter_nremoved(self, filt=True, quiet=False):
"""
Report how many data are removed by the active filters.
"""
rminfo = {}
for n in self.subsets['All_Samples']:
s = self.data[n]
rminfo[n] = s.filt_nremoved(filt)
if not quiet:
maxL =... | Report how many data are removed by the active filters. |
def get_vertices(self, indexed=None):
"""Get the vertices
Parameters
----------
indexed : str | None
If Note, return an array (N,3) of the positions of vertices in
the mesh. By default, each unique vertex appears only once.
If indexed is 'faces', then... | Get the vertices
Parameters
----------
indexed : str | None
If Note, return an array (N,3) of the positions of vertices in
the mesh. By default, each unique vertex appears only once.
If indexed is 'faces', then the array will instead contain three
... |
def parse_ACCT(chunk, encryption_key):
"""
Parses an account chunk, decrypts and creates an Account object.
May return nil when the chunk does not represent an account.
All secure notes are ACCTs but not all of them strore account
information.
"""
# TODO: Make a test case that covers secure ... | Parses an account chunk, decrypts and creates an Account object.
May return nil when the chunk does not represent an account.
All secure notes are ACCTs but not all of them strore account
information. |
def p_localparamdecl_integer(self, p):
'localparamdecl : LOCALPARAM INTEGER param_substitution_list SEMICOLON'
paramlist = [Localparam(rname, rvalue, lineno=p.lineno(3))
for rname, rvalue in p[3]]
p[0] = Decl(tuple(paramlist), lineno=p.lineno(1))
p.set_lineno(0, p.li... | localparamdecl : LOCALPARAM INTEGER param_substitution_list SEMICOLON |
def _lexsorted_specs(self, order):
"""
A lexsort is specified using normal key string prefixed by '+'
(for ascending) or '-' for (for descending).
Note that in Python 2, if a key is missing, None is returned
(smallest Python value). In Python 3, an Exception will be
rais... | A lexsort is specified using normal key string prefixed by '+'
(for ascending) or '-' for (for descending).
Note that in Python 2, if a key is missing, None is returned
(smallest Python value). In Python 3, an Exception will be
raised regarding comparison of heterogenous types. |
def human_or_01(X, y, model_generator, method_name):
""" OR (false/true)
This tests how well a feature attribution method agrees with human intuition
for an OR operation combined with linear effects. This metric deals
specifically with the question of credit allocation for the following function
wh... | OR (false/true)
This tests how well a feature attribution method agrees with human intuition
for an OR operation combined with linear effects. This metric deals
specifically with the question of credit allocation for the following function
when all three inputs are true:
if fever: +2 points
if ... |
def _k_prototypes_iter(Xnum, Xcat, centroids, cl_attr_sum, cl_memb_sum, cl_attr_freq,
membship, num_dissim, cat_dissim, gamma, random_state):
"""Single iteration of the k-prototypes algorithm"""
moves = 0
for ipoint in range(Xnum.shape[0]):
clust = np.argmin(
num_d... | Single iteration of the k-prototypes algorithm |
def load_files(filenames,multiproc=False,**kwargs):
""" Load a set of FITS files with kwargs. """
filenames = np.atleast_1d(filenames)
logger.debug("Loading %s files..."%len(filenames))
kwargs = [dict(filename=f,**kwargs) for f in filenames]
if multiproc:
from multiprocessing import Pool
... | Load a set of FITS files with kwargs. |
def _image_data(self, normalize=False,
min_depth=MIN_DEPTH,
max_depth=MAX_DEPTH,
twobyte=False):
"""Returns the data in image format, with scaling and conversion to uint8 types.
Parameters
----------
normalize : bool
... | Returns the data in image format, with scaling and conversion to uint8 types.
Parameters
----------
normalize : bool
whether or not to normalize by the min and max depth of the image
min_depth : float
minimum depth value for the normalization
max_depth : ... |
def validate(node, source):
"""Call this function to validate an AST."""
# TODO: leaving strict checking off to support insert_grad_of
lf = LanguageFence(source, strict=False)
lf.visit(node)
return node | Call this function to validate an AST. |
def create_new_version(
self,
name,
subject,
text='',
template_id=None,
html=None,
locale=None,
timeout=None
):
""" API call to create a new version of a template """
if(html):
payload = {
'name': name,
... | API call to create a new version of a template |
def get_options_from_file(self, file_path):
"""
Return the options parsed from a JSON file.
"""
# read options JSON file
with open(file_path) as options_file:
options_dict = json.load(options_file)
options = []
for opt_name in options_dict:
... | Return the options parsed from a JSON file. |
def main(*kw):
"""Command line entry point; arguments must match those defined in
in :meth:`create_parser()`; returns 0 for success, else 1.
Example::
command.main("-i", "**/*.py", "--no-default-excludes")
Runs formic printing out all .py files in the current working directory
and its child... | Command line entry point; arguments must match those defined in
in :meth:`create_parser()`; returns 0 for success, else 1.
Example::
command.main("-i", "**/*.py", "--no-default-excludes")
Runs formic printing out all .py files in the current working directory
and its children to ``sys.stdout``.... |
def canonicalize_half_turns(
half_turns: Union[sympy.Basic, float]
) -> Union[sympy.Basic, float]:
"""Wraps the input into the range (-1, +1]."""
if isinstance(half_turns, sympy.Basic):
return half_turns
half_turns %= 2
if half_turns > 1:
half_turns -= 2
return half_turns | Wraps the input into the range (-1, +1]. |
def _compute_acq(self,x):
"""
Integrated GP-Lower Confidence Bound
"""
means, stds = self.model.predict(x)
f_acqu = 0
for m,s in zip(means, stds):
f_acqu += -m + self.exploration_weight * s
return f_acqu/(len(means)) | Integrated GP-Lower Confidence Bound |
def plot_sources(topo, mixmaps, unmixmaps, global_scale=None, fig=None):
"""Plot all scalp projections of mixing- and unmixing-maps.
.. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_map`.
Parameters
----------
topo : :class:`~eegtopo.topoplot.... | Plot all scalp projections of mixing- and unmixing-maps.
.. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_map`.
Parameters
----------
topo : :class:`~eegtopo.topoplot.Topoplot`
This object draws the topo plot
mixmaps : array, shape = [... |
def gb(args):
"""
%prog gb gffile fastafile
Convert GFF3 to Genbank format. Recipe taken from:
<http://www.biostars.org/p/2492/>
"""
from Bio.Alphabet import generic_dna
try:
from BCBio import GFF
except ImportError:
print("You need to install dep first: $ easy_install b... | %prog gb gffile fastafile
Convert GFF3 to Genbank format. Recipe taken from:
<http://www.biostars.org/p/2492/> |
def to_string(self):
"""
Return the current DEVICE_CONFIG as a string (always 4 bytes).
"""
fmt = '<BBH'
first = struct.pack(
fmt,
self._mode,
self._cr_timeout,
self._auto_eject_time
)
#crc = 0xffff - yubico_util.cr... | Return the current DEVICE_CONFIG as a string (always 4 bytes). |
def pip_uninstall(package, **options):
"""Uninstall a python package"""
command = ["uninstall", "-q", "-y"]
available_options = ('proxy', 'log', )
for option in parse_options(options, available_options):
command.append(option)
if isinstance(package, list):
command.extend(package)
... | Uninstall a python package |
def update_system(version='', ruby=None, runas=None, gem_bin=None):
'''
Update rubygems.
:param version: string : (newest)
The version of rubygems to install.
:param gem_bin: string : None
Full path to ``gem`` binary to use.
:param ruby: string : None
If RVM or rbenv are ins... | Update rubygems.
:param version: string : (newest)
The version of rubygems to install.
:param gem_bin: string : None
Full path to ``gem`` binary to use.
:param ruby: string : None
If RVM or rbenv are installed, the ruby version and gemset to use.
Ignored if ``gem_bin`` is sp... |
def inq_convolution(inp, outmaps, kernel,
pad=None, stride=None, dilation=None, group=1,
num_bits=4, inq_iterations=(), selection_algorithm='random',
seed=-1, w_init=None, i_init=None, b_init=None,
base_axis=1, fix_parameters=False, rng=Non... | Incremental Network Quantization Convolution Layer
During training, the weights are sequentially quantized to power-of-two
values, which allows the training of a multiplierless network.
Using `inq_iterations`, one can specify after how many forward passes
half of the learnable weights are fixed and qu... |
def blog_authors(*args):
"""
Put a list of authors (users) for blog posts into the template context.
"""
blog_posts = BlogPost.objects.published()
authors = User.objects.filter(blogposts__in=blog_posts)
return list(authors.annotate(post_count=Count("blogposts"))) | Put a list of authors (users) for blog posts into the template context. |
def remove(ctx, client, sources):
"""Remove files and check repository for potential problems."""
from renku.api._git import _expand_directories
def fmt_path(path):
"""Format path as relative to the client path."""
return str(Path(path).absolute().relative_to(client.path))
files = {
... | Remove files and check repository for potential problems. |
def imshow(self, *args, show_crosshair=True, show_mask=True,
show_qscale=True, axes=None, invalid_color='black',
mask_opacity=0.8, show_colorbar=True, **kwargs):
"""Plot the matrix (imshow)
Keyword arguments [and their default values]:
show_crosshair [True]: if a ... | Plot the matrix (imshow)
Keyword arguments [and their default values]:
show_crosshair [True]: if a cross-hair marking the beam position is
to be plotted.
show_mask [True]: if the mask is to be plotted.
show_qscale [True]: if the horizontal and vertical axes are to be
... |
def set_global_defaults(**kwargs):
"""Set global defaults for the options passed to the icon painter."""
valid_options = [
'active', 'selected', 'disabled', 'on', 'off',
'on_active', 'on_selected', 'on_disabled',
'off_active', 'off_selected', 'off_disabled',
'color', 'color_on',... | Set global defaults for the options passed to the icon painter. |
def _parse_udevadm_info(udev_info):
'''
Parse the info returned by udevadm command.
'''
devices = []
dev = {}
for line in (line.strip() for line in udev_info.splitlines()):
if line:
line = line.split(':', 1)
if len(line) != 2:
continue
... | Parse the info returned by udevadm command. |
def info_hash(self):
"""Hash of torrent file info section. Also known as torrent hash."""
info = self._struct.get('info')
if not info:
return None
return sha1(Bencode.encode(info)).hexdigest() | Hash of torrent file info section. Also known as torrent hash. |
def parse_cluster(self, global_params, region, cluster):
"""
Parse a single Redshift cluster
:param global_params: Parameters shared for all regions
:param region: Name of the AWS region
:param cluster: Cluster
"""
vpc_i... | Parse a single Redshift cluster
:param global_params: Parameters shared for all regions
:param region: Name of the AWS region
:param cluster: Cluster |
def clean_csvs(dialogpath=None):
""" Translate non-ASCII characters to spaces or equivalent ASCII characters """
dialogdir = os.dirname(dialogpath) if os.path.isfile(dialogpath) else dialogpath
filenames = [dialogpath.split(os.path.sep)[-1]] if os.path.isfile(dialogpath) else os.listdir(dialogpath)
for ... | Translate non-ASCII characters to spaces or equivalent ASCII characters |
def group_files_by_size(fileslist, multi): # pragma: no cover
''' Cluster files into the specified number of groups, where each groups total size is as close as possible to each other.
Pseudo-code (O(n^g) time complexity):
Input: number of groups G per cluster, list of files F with respective sizes
- ... | Cluster files into the specified number of groups, where each groups total size is as close as possible to each other.
Pseudo-code (O(n^g) time complexity):
Input: number of groups G per cluster, list of files F with respective sizes
- Order F by descending size
- Until F is empty:
- Create a c... |
def construct_from(cls, group_info):
"""Constructs ``FileGroup`` instance from group information."""
group = cls(group_info['id'])
group._info_cache = group_info
return group | Constructs ``FileGroup`` instance from group information. |
def setup_Jupyter():
"""
Set up a Jupyter notebook with a few defaults.
"""
sns.set(context = "paper", font = "monospace")
warnings.filterwarnings("ignore")
pd.set_option("display.max_rows", 500)
pd.set_option("display.max_columns", 500)
plt.rcParams["figure.figsize"] = (17, 10) | Set up a Jupyter notebook with a few defaults. |
def pprint_out(dct: Dict):
"""
Utility methods to pretty-print a dictionary that is typically outputted by parsyfiles (an ordered dict)
:param dct:
:return:
"""
for name, val in dct.items():
print(name + ':')
pprint(val, indent=4) | Utility methods to pretty-print a dictionary that is typically outputted by parsyfiles (an ordered dict)
:param dct:
:return: |
def save(self, *args, **kwargs):
"""
Custom save method does the following:
* automatically inherit node coordinates and elevation
* save shortcuts if HSTORE is enabled
"""
custom_checks = kwargs.pop('custom_checks', True)
super(Device, self).save(*args, ... | Custom save method does the following:
* automatically inherit node coordinates and elevation
* save shortcuts if HSTORE is enabled |
def raw_corpus_rouge2(hypotheses: Iterable[str], references: Iterable[str]) -> float:
"""
Simple wrapper around ROUGE-2 implementation.
:param hypotheses: Hypotheses stream.
:param references: Reference stream.
:return: ROUGE-2 score as float between 0 and 1.
"""
return rouge.rouge_2(hypoth... | Simple wrapper around ROUGE-2 implementation.
:param hypotheses: Hypotheses stream.
:param references: Reference stream.
:return: ROUGE-2 score as float between 0 and 1. |
def delta(self, mapping, prefix):
"""
return a delta containing values that have changed.
"""
previous = self.getrange(prefix, strip=True)
if not previous:
pk = set()
else:
pk = set(previous.keys())
ck = set(mapping.keys())
delta = ... | return a delta containing values that have changed. |
def visit_subscript(self, node):
""" Look for indexing exceptions. """
try:
for inferred in node.value.infer():
if not isinstance(inferred, astroid.Instance):
continue
if utils.inherit_from_std_ex(inferred):
self.add_mes... | Look for indexing exceptions. |
def store_initial_arguments(request, initial_arguments=None):
'Store initial arguments, if any, and return a cache identifier'
if initial_arguments is None:
return None
# Generate a cache id
cache_id = "dpd-initial-args-%s" % str(uuid.uuid4()).replace('-', '')
# Store args in json form in... | Store initial arguments, if any, and return a cache identifier |
def fcoe_get_interface_input_fcoe_intf_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_interface = ET.Element("fcoe_get_interface")
config = fcoe_get_interface
input = ET.SubElement(fcoe_get_interface, "input")
fcoe_intf_nam... | Auto Generated Code |
def circ_permutation(items):
"""Calculate the circular permutation for a given list of items."""
permutations = []
for i in range(len(items)):
permutations.append(items[i:] + items[:i])
return permutations | Calculate the circular permutation for a given list of items. |
def list_all_orders(cls, **kwargs):
"""List Orders
Return a list of Orders
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_orders(async=True)
>>> result = thread.get()
... | List Orders
Return a list of Orders
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_orders(async=True)
>>> result = thread.get()
:param async bool
:param int page: pa... |
def data():
"""Data providing function:
Make sure to have every relevant import statement included here and return data as
used in model function below. This function is separated from model() so that hyperopt
won't reload data for each evaluation run.
"""
from keras.datasets import mnist
f... | Data providing function:
Make sure to have every relevant import statement included here and return data as
used in model function below. This function is separated from model() so that hyperopt
won't reload data for each evaluation run. |
def __expand_subfeatures_aux (property_, dont_validate = False):
""" Helper for expand_subfeatures.
Given a feature and value, or just a value corresponding to an
implicit feature, returns a property set consisting of all component
subfeatures and their values. For example:
expand... | Helper for expand_subfeatures.
Given a feature and value, or just a value corresponding to an
implicit feature, returns a property set consisting of all component
subfeatures and their values. For example:
expand_subfeatures <toolset>gcc-2.95.2-linux-x86
-> <toolset>gcc ... |
def menu(items, heading):
'''Takes list of dictionaries and prints a menu.
items parameter should be in the form of a list, containing
dictionaries with the keys: {"key", "text", "function"}.
Typing the key for a menuitem, followed by return, will run
"function".
'''
headin... | Takes list of dictionaries and prints a menu.
items parameter should be in the form of a list, containing
dictionaries with the keys: {"key", "text", "function"}.
Typing the key for a menuitem, followed by return, will run
"function". |
def _get_read_query(self, table_columns, limit=None):
"""Create the read (COPY TO) query"""
query_columns = [column.name for column in table_columns]
query_columns.remove('the_geom_webmercator')
query = 'SELECT {columns} FROM "{schema}"."{table_name}"'.format(
table_name=sel... | Create the read (COPY TO) query |
def syzygyJD(jd):
""" Finds the latest new or full moon and
returns the julian date of that event.
"""
sun = swe.sweObjectLon(const.SUN, jd)
moon = swe.sweObjectLon(const.MOON, jd)
dist = angle.distance(sun, moon)
# Offset represents the Syzygy type.
# Zero is conjunction and... | Finds the latest new or full moon and
returns the julian date of that event. |
def screenshot(self, save_path, element=None, delay=0):
"""
This can be used no matter what driver that is being used
* ^ Soon requests support will be added
Save screenshot to local dir with uuid as filename
then move the file to `filename` (path must be part of the file name)
... | This can be used no matter what driver that is being used
* ^ Soon requests support will be added
Save screenshot to local dir with uuid as filename
then move the file to `filename` (path must be part of the file name)
Return the filepath of the image |
def drop_table(self, table):
"""
Drop a table from the MyDB context.
## Arguments
* `table` (str): The name of the table to drop.
"""
job_id = self.submit("DROP TABLE %s"%table, context="MYDB")
status = self.monitor(job_id)
if status[0] != 5:
... | Drop a table from the MyDB context.
## Arguments
* `table` (str): The name of the table to drop. |
def change_settings(self, bio=None, public_images=None,
messaging_enabled=None, album_privacy=None,
accepted_gallery_terms=None):
"""
Update the settings for the user.
:param bio: A basic description filled out by the user, is displayed in
... | Update the settings for the user.
:param bio: A basic description filled out by the user, is displayed in
the gallery profile page.
:param public_images: Set the default privacy setting of the users
images. If True images are public, if False private.
:param messaging_en... |
def get_contents(self):
"""The contents of an alias is the concatenation
of the content signatures of all its sources."""
childsigs = [n.get_csig() for n in self.children()]
return ''.join(childsigs) | The contents of an alias is the concatenation
of the content signatures of all its sources. |
def handle_read(self):
"""
Handle the 'channel readable' state. E.g. read from a socket.
"""
with self.lock:
logger.debug("handle_read()")
if self._eof or self._socket is None:
return
if self._state == "tls-handshake":
w... | Handle the 'channel readable' state. E.g. read from a socket. |
def gmdaArray(arry, dtype, mask=None, numGhosts=1):
"""
ghosted distributed array constructor
@param arry numpy-like array
@param numGhosts the number of ghosts (>= 0)
"""
a = numpy.array(arry, dtype)
res = GhostedMaskedDistArray(a.shape, a.dtype)
res.mask = mask
res.setNumberOfGhost... | ghosted distributed array constructor
@param arry numpy-like array
@param numGhosts the number of ghosts (>= 0) |
def _get_features(self, eopatch=None):
"""A generator of parsed features.
:param eopatch: A given EOPatch
:type eopatch: EOPatch or None
:return: One by one feature
:rtype: tuple(FeatureType, str) or tuple(FeatureType, str, str)
"""
for feature_type, feat... | A generator of parsed features.
:param eopatch: A given EOPatch
:type eopatch: EOPatch or None
:return: One by one feature
:rtype: tuple(FeatureType, str) or tuple(FeatureType, str, str) |
def format_in_original_format(numobj, region_calling_from):
"""Format a number using the original format that the number was parsed from.
The original format is embedded in the country_code_source field of the
PhoneNumber object passed in. If such information is missing, the number
will be formatted in... | Format a number using the original format that the number was parsed from.
The original format is embedded in the country_code_source field of the
PhoneNumber object passed in. If such information is missing, the number
will be formatted into the NATIONAL format by default.
When we don't have a forma... |
def parse_list(cls, data):
"""Parse a list of JSON objects into a result set of model instances."""
results = ResultSet()
data = data or []
for obj in data:
if obj:
results.append(cls.parse(obj))
return results | Parse a list of JSON objects into a result set of model instances. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.