code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def remove_neighbours(self):
"""
Removes from the MOC instance the HEALPix cells located at its border.
The depth of the HEALPix cells removed is equal to the maximum depth of the MOC instance.
Returns
-------
moc : `~mocpy.moc.MOC`
self minus its HEALPix ce... | Removes from the MOC instance the HEALPix cells located at its border.
The depth of the HEALPix cells removed is equal to the maximum depth of the MOC instance.
Returns
-------
moc : `~mocpy.moc.MOC`
self minus its HEALPix cells located at its border. |
def sync_deps(self, path):
"""
Creates or updates a directory structure that can be used to avoid
doing a full rebuild whenever the configuration is changed, mirroring
include/config/ in the kernel.
This function is intended to be called during each build, before
compili... | Creates or updates a directory structure that can be used to avoid
doing a full rebuild whenever the configuration is changed, mirroring
include/config/ in the kernel.
This function is intended to be called during each build, before
compiling source files that depend on configuration sy... |
def get_session(session, baseurl, config):
"""
Try to get a valid session for this baseurl, using login found in config.
This function invoques Firefox if necessary
"""
# Read proxy for firefox
if environ.get("HTTP_PROXY"):
myProxy = environ.get("HTTP_PROXY")
proxy = Proxy({
... | Try to get a valid session for this baseurl, using login found in config.
This function invoques Firefox if necessary |
def exact(self, *args, **kwargs):
"""Compare attributes of pairs exactly.
Shortcut of :class:`recordlinkage.compare.Exact`::
from recordlinkage.compare import Exact
indexer = recordlinkage.Compare()
indexer.add(Exact())
"""
compare = Exact(*args, *... | Compare attributes of pairs exactly.
Shortcut of :class:`recordlinkage.compare.Exact`::
from recordlinkage.compare import Exact
indexer = recordlinkage.Compare()
indexer.add(Exact()) |
def switch_to_plugin(self):
"""Switch to plugin."""
# Unmaxizime currently maximized plugin
if (self.main.last_plugin is not None and
self.main.last_plugin.ismaximized and
self.main.last_plugin is not self):
self.main.maximize_dockwidget()
... | Switch to plugin. |
def propagate(cls, date):
"""Compute the Moon position at a given date
Args:
date (~beyond.utils.date.Date)
Return:
~beyond.orbits.orbit.Orbit: Position of the Moon in EME2000 frame
Example:
.. code-block:: python
from beyond.utils.d... | Compute the Moon position at a given date
Args:
date (~beyond.utils.date.Date)
Return:
~beyond.orbits.orbit.Orbit: Position of the Moon in EME2000 frame
Example:
.. code-block:: python
from beyond.utils.date import Date
MoonP... |
def _get_coordinates_for_dataset_key(self, dsid):
"""Get the coordinate dataset keys for *dsid*."""
ds_info = self.ids[dsid]
cids = []
for cinfo in ds_info.get('coordinates', []):
if not isinstance(cinfo, dict):
cinfo = {'name': cinfo}
cinfo['res... | Get the coordinate dataset keys for *dsid*. |
def play(self):
"""
Starts game and returns one of 3 results .
Iterates between methods ``white_move()`` and
``black_move()`` until game ends. Each
method calls the respective player's ``generate_move()``
method.
:rtype: int
"""
colors = [lambda:... | Starts game and returns one of 3 results .
Iterates between methods ``white_move()`` and
``black_move()`` until game ends. Each
method calls the respective player's ``generate_move()``
method.
:rtype: int |
def getFlag(self, flagName):
"""
Creates a flag having path <variables dir path><os.sep><flagName>
"""
assert (len(flagName) > 0)
return Flag(os.path.join(self._variablesDirPath, flagName)) | Creates a flag having path <variables dir path><os.sep><flagName> |
def convert2dbus(value, signature):
"""Converts `value` type from python to dbus according signature.
:param value: value to convert to dbus object
:param str signature: dbus type signature.
:returns: value in dbus type.
"""
if len(signature) == 2 and signature.startswith('a'):
return d... | Converts `value` type from python to dbus according signature.
:param value: value to convert to dbus object
:param str signature: dbus type signature.
:returns: value in dbus type. |
def _compat_name(new_name, compat_name=None):
"""Returns old API ("slave") name for new name ("worker").
>>> assert _compat_name("Worker") == "Slave"
>>> assert _compat_name("SomeWorkerStuff") == "SomeSlaveStuff"
>>> assert _compat_name("SomeWorker", compat_name="SomeBuildSlave") == \
"SomeBuil... | Returns old API ("slave") name for new name ("worker").
>>> assert _compat_name("Worker") == "Slave"
>>> assert _compat_name("SomeWorkerStuff") == "SomeSlaveStuff"
>>> assert _compat_name("SomeWorker", compat_name="SomeBuildSlave") == \
"SomeBuildSlave"
If `compat_name` is not specified old na... |
def update(self, task_name, task_json):
"""Updates a GBDX task.
Args:
task_name (str): Task name.
task_json (dict): Dictionary representing updated task definition.
Returns:
Dictionary representing the updated task definition.
"""
r = self.gb... | Updates a GBDX task.
Args:
task_name (str): Task name.
task_json (dict): Dictionary representing updated task definition.
Returns:
Dictionary representing the updated task definition. |
def build(self, builder):
"""Build XML by appending to builder"""
builder.start("mdsol:ReviewGroup", {})
builder.data(self.name)
builder.end("mdsol:ReviewGroup") | Build XML by appending to builder |
def _decode_step(self,
prev_word: mx.nd.NDArray,
step: int,
source_length: int,
states: List[ModelState],
models_output_layer_w: List[mx.nd.NDArray],
models_output_layer_b: List[mx.nd.NDArray]) ... | Returns decoder predictions (combined from all models), attention scores, and updated states.
:param prev_word: Previous words of hypotheses. Shape: (batch_size * beam_size,).
:param step: Beam search iteration.
:param source_length: Length of the input sequence.
:param states: List of ... |
def spendables_for_address(self, address):
"""
Return a list of Spendable objects for the
given bitcoin address.
"""
URL = self.api_domain + "/unspent?active=%s" % address
r = json.loads(urlopen(URL).read().decode("utf8"))
spendables = []
for u in r["unspe... | Return a list of Spendable objects for the
given bitcoin address. |
def full_newton(s, nodes1, t, nodes2):
r"""Perform a Newton iteration until convergence to a solution.
This assumes :math:`s` and :math:`t` are sufficiently close to an
intersection. It **does not** govern the maximum distance away
that the solution can lie, though the subdivided intervals that contain... | r"""Perform a Newton iteration until convergence to a solution.
This assumes :math:`s` and :math:`t` are sufficiently close to an
intersection. It **does not** govern the maximum distance away
that the solution can lie, though the subdivided intervals that contain
:math:`s` and :math:`t` could be used.... |
def _count_async(self, limit=None, **q_options):
"""Internal version of count_async()."""
# TODO: Support offset by incorporating it to the limit.
if 'offset' in q_options:
raise NotImplementedError('.count() and .count_async() do not support '
'offsets at present.')
... | Internal version of count_async(). |
def expose(url="/", methods=("GET",)):
"""
Use this decorator to expose API endpoints on your API classes.
:param url:
Relative URL for the endpoint
:param methods:
Allowed HTTP methods. By default only GET is allowed.
"""
def wrap(f):
if not hasattr... | Use this decorator to expose API endpoints on your API classes.
:param url:
Relative URL for the endpoint
:param methods:
Allowed HTTP methods. By default only GET is allowed. |
def create_audit_student_enrollment(self, course_id):
"""
Creates an audit enrollment for the user in a given course
Args:
course_id (str): an edX course id
Returns:
Enrollment: object representing the student enrollment in the provided course
"""
... | Creates an audit enrollment for the user in a given course
Args:
course_id (str): an edX course id
Returns:
Enrollment: object representing the student enrollment in the provided course |
def _replace_fields(self, json_dict):
"""
Delete this object's attributes, and replace with
those in json_dict.
"""
for key in self._json_dict.keys():
if not key.startswith("_"):
delattr(self, key)
self._json_dict = json_dict
self._set_... | Delete this object's attributes, and replace with
those in json_dict. |
def _assignSignature(self, chip):
"""Assign a unique signature for the image based
on the instrument, detector, chip, and size
this will be used to uniquely identify the appropriate
static mask for the image.
This also records the filename for the static mask to the... | Assign a unique signature for the image based
on the instrument, detector, chip, and size
this will be used to uniquely identify the appropriate
static mask for the image.
This also records the filename for the static mask to the outputNames dictionary. |
def distance(self, other=None):
"""Return the geometric distance to the other location.
If no object is provided, this will calculate the distance to the origin.
::
>>> l = Location(pop=100)
>>> m = Location(pop=200)
>>> l.distance(m)
100.0
... | Return the geometric distance to the other location.
If no object is provided, this will calculate the distance to the origin.
::
>>> l = Location(pop=100)
>>> m = Location(pop=200)
>>> l.distance(m)
100.0
>>> l = Location()
>>> m... |
def reset_interface(self):
"""
Reset the interface by removing all assigned addresses and VLANs.
This will not delete the interface itself, only the sub interfaces that
may have addresses assigned. This will not affect inline or capture
interfaces.
Note that if this inter... | Reset the interface by removing all assigned addresses and VLANs.
This will not delete the interface itself, only the sub interfaces that
may have addresses assigned. This will not affect inline or capture
interfaces.
Note that if this interface is used as a primary control, auth request... |
def sum_combined_sp_values(self, other):
"""
sum(sp_values * sp_values)
"""
if self.values is None:
ret = IdValues()
else:
ret = IdValues({'0': sum(int(x) for x in
{k: int(v) * int(other.values[k]) for k, v
... | sum(sp_values * sp_values) |
def _create_initial_state(self, initial_ids, initial_cache):
"""Return initial state dictionary and its shape invariants.
Args:
initial_ids: initial ids to pass into the symbols_to_logits_fn.
int tensor with shape [batch_size, 1]
initial_cache: dictionary storing values to be passed into th... | Return initial state dictionary and its shape invariants.
Args:
initial_ids: initial ids to pass into the symbols_to_logits_fn.
int tensor with shape [batch_size, 1]
initial_cache: dictionary storing values to be passed into the
symbols_to_logits_fn.
Returns:
state and shap... |
def handle(self, path, method='GET'):
""" (deprecated) Execute the first matching route callback and return
the result. :exc:`HTTPResponse` exceptions are catched and returned.
If :attr:`Bottle.catchall` is true, other exceptions are catched as
well and returned as :exc:`HTTP... | (deprecated) Execute the first matching route callback and return
the result. :exc:`HTTPResponse` exceptions are catched and returned.
If :attr:`Bottle.catchall` is true, other exceptions are catched as
well and returned as :exc:`HTTPError` instances (500). |
def _args_checks_gen(self, decorated_function, function_spec, arg_specs):
""" Generate checks for positional argument testing
:param decorated_function: function decorator
:param function_spec: function inspect information
:param arg_specs: argument specification (same as arg_specs in :meth:`.Verifier.decorate... | Generate checks for positional argument testing
:param decorated_function: function decorator
:param function_spec: function inspect information
:param arg_specs: argument specification (same as arg_specs in :meth:`.Verifier.decorate`)
:return: internal structure, that is used by :meth:`.Verifier._args_checks... |
def get_cds_time(days, msecs):
"""Get the datetime object of the time since epoch given in days and
milliseconds of day
"""
return datetime(1958, 1, 1) + timedelta(days=float(days),
milliseconds=float(msecs)) | Get the datetime object of the time since epoch given in days and
milliseconds of day |
def get_fields(catalog, filter_in=None, filter_out=None, meta_field=None,
only_time_series=False, distribution_identifier=None):
"""Devuelve lista de campos del catálogo o de uno de sus metadatos.
Args:
catalog (dict, str or DataJson): Representación externa/interna de un
cat... | Devuelve lista de campos del catálogo o de uno de sus metadatos.
Args:
catalog (dict, str or DataJson): Representación externa/interna de un
catálogo. Una representación _externa_ es un path local o una
URL remota a un archivo con la metadata de un catálogo, en
formato J... |
def copy(self, pk=None, new_name=None, **kwargs):
"""Copy an object.
Only the ID is used for the lookup. All provided fields are used to override the old data from the
copied resource.
=====API DOCS=====
Copy an object.
:param pk: Primary key of the resource object to ... | Copy an object.
Only the ID is used for the lookup. All provided fields are used to override the old data from the
copied resource.
=====API DOCS=====
Copy an object.
:param pk: Primary key of the resource object to be copied
:param new_name: The new name to give the r... |
def _ser_script_to_sh_address(script_bytes, witness=False, cashaddr=True):
'''
makes an p2sh address from a serialized script
'''
if witness:
script_hash = utils.sha256(script_bytes)
else:
script_hash = utils.hash160(script_bytes)
return _hash_to_sh_address(
script_hash=s... | makes an p2sh address from a serialized script |
def make_case2(context):
"""This is a helper method for testing.
When run with the current context, it will create a case 2 entries
in the database. See top of file for what case 2 is.
"""
query = context.session.query(models.IPAddress)
period_start, period_end = billing.calc_periods()
ip_l... | This is a helper method for testing.
When run with the current context, it will create a case 2 entries
in the database. See top of file for what case 2 is. |
def is_prefix(pre_path, path):
"""Return True if pre_path is a path-prefix of path."""
pre_path = pre_path.strip('.')
path = path.strip('.')
return not pre_path or path.startswith(pre_path + '.') | Return True if pre_path is a path-prefix of path. |
def findInvariant(self, symclasses):
"""(symclasses) -> converge the disambiguity function
until we have an invariant"""
get = primes.primes.get
disambiguate = self.disambiguate
breakRankTies = self.breakRankTies
while 1:
newSyms = map(get, symclasses)
... | (symclasses) -> converge the disambiguity function
until we have an invariant |
def _get_cpu_info_from_cat_var_run_dmesg_boot():
'''
Returns the CPU info gathered from /var/run/dmesg.boot.
Returns {} if dmesg is not found or does not have the desired info.
'''
# Just return {} if there is no /var/run/dmesg.boot
if not DataSource.has_var_run_dmesg_boot():
return {}
# If dmesg.boot fails r... | Returns the CPU info gathered from /var/run/dmesg.boot.
Returns {} if dmesg is not found or does not have the desired info. |
def explode(self):
"""
Get services and put them in members container
:return: None
"""
# We do not want a same service group to be exploded again and again
# so we tag it
for tmp_sg in list(self.items.values()):
tmp_sg.already_exploded = False
... | Get services and put them in members container
:return: None |
def _make_valid_if_necessary(shape):
"""
attempt to correct invalid shapes if necessary
After simplification, even when preserving topology, invalid
shapes can be returned. This appears to only occur with polygon
types. As an optimization, we only check if the polygon types are
valid.
"""
... | attempt to correct invalid shapes if necessary
After simplification, even when preserving topology, invalid
shapes can be returned. This appears to only occur with polygon
types. As an optimization, we only check if the polygon types are
valid. |
def list_courses(self):
"""
List enrolled courses.
@return: List of enrolled courses.
@rtype: [str]
"""
course = CourseraOnDemand(session=self._session,
course_id=None,
course_name=None)
return c... | List enrolled courses.
@return: List of enrolled courses.
@rtype: [str] |
def process_file(self):
""" download: download a web+graphie file
Args: None
Returns: None
"""
try:
self.filename = self.generate_graphie_file()
config.LOGGER.info("\t--- Generated graphie {}".format(self.filename))
return self.filename... | download: download a web+graphie file
Args: None
Returns: None |
def save_wrapper(cls, save, new_class):
"""
Wrap the save method to call pre and post enable signals and update
module status
"""
def _wrapped(self, *args, **kwargs):
if not self.installed:
raise AssertionError('Module %s is not installed' %
... | Wrap the save method to call pre and post enable signals and update
module status |
def elements(self):
'''Iterator over elements repeating each as many times as its count.
>>> c = Counter('ABCABC')
>>> sorted(c.elements())
['A', 'A', 'B', 'B', 'C', 'C']
If an element's count has been set to zero or is a negative number,
elements() will ignore it.
'''
try:
... | Iterator over elements repeating each as many times as its count.
>>> c = Counter('ABCABC')
>>> sorted(c.elements())
['A', 'A', 'B', 'B', 'C', 'C']
If an element's count has been set to zero or is a negative number,
elements() will ignore it. |
def remove_outlier(self, data, sd_val):
""" Remove outliers from dataframe.
Note
----
1. This function excludes all lines with NA in all columns.
Parameters
----------
data : pd.DataFrame()
Dataframe to remove outliers from.
sd_val : int
... | Remove outliers from dataframe.
Note
----
1. This function excludes all lines with NA in all columns.
Parameters
----------
data : pd.DataFrame()
Dataframe to remove outliers from.
sd_val : int
Standard Deviation Value (specifices how... |
def get_ip4():
"""
return all ip v4 address of current computer
:return:
"""
addresses = []
shell_cmd = "ifconfig | awk '/inet addr/{print substr($2,6)}'"
proc = subprocess.Popen([shell_cmd], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
ip_addresses = out.spli... | return all ip v4 address of current computer
:return: |
def intervals_to_bed(intervals):
"""
Convert list of intervals of format chr1:100-200 or chr1:100-200:+ to
BedTool object.
Parameters
----------
intervals : array-like
List of intervals.
Returns
-------
bt : pybedtools.BedTool
BedTool with one line for each interva... | Convert list of intervals of format chr1:100-200 or chr1:100-200:+ to
BedTool object.
Parameters
----------
intervals : array-like
List of intervals.
Returns
-------
bt : pybedtools.BedTool
BedTool with one line for each interval. |
def get(self, document=None, plugin=None):
"""
Get one or more documents.
:param document: Name of the document
:type document: str
:param plugin: Plugin object, under which the document was registered
:type plugin: GwBasePattern
"""
if plugin is not None... | Get one or more documents.
:param document: Name of the document
:type document: str
:param plugin: Plugin object, under which the document was registered
:type plugin: GwBasePattern |
def quantile_1D(data, weights, quantile):
"""
Compute the weighted quantile of a 1D numpy array.
Parameters
----------
data : ndarray
Input array (one dimension).
weights : ndarray
Array with the weights of the same size of `data`.
quantile : float
Quantile to comput... | Compute the weighted quantile of a 1D numpy array.
Parameters
----------
data : ndarray
Input array (one dimension).
weights : ndarray
Array with the weights of the same size of `data`.
quantile : float
Quantile to compute. It must have a value between 0 and 1.
Returns
... |
def decompress_array(str_list):
"""
Decompress a list of strings
"""
global _compress_thread_pool
if not str_list:
return str_list
if not ENABLE_PARALLEL or len(str_list) <= LZ4_N_PARALLEL:
return [lz4_decompress(chunk) for chunk in str_list]
if _compress_thread_pool is No... | Decompress a list of strings |
def lowest_common_hypernyms(self,target_synset):
"""Returns the common hypernyms of the synset and the target synset, which are furthest from the closest roots.
Parameters
----------
target_synset : Synset
Synset with which the common hypernyms are sought.
... | Returns the common hypernyms of the synset and the target synset, which are furthest from the closest roots.
Parameters
----------
target_synset : Synset
Synset with which the common hypernyms are sought.
Returns
-------
list of Synsets
... |
def cookie(self, k, v, expires=None, domain=None, path='/', secure=False):
""" Sets cookie value.
:param k: Name for cookie value
:param v: Cookie value
:param expires: Cookie expiration date
:param domain: Cookie domain
:param path: Cookie path
:param secure: Fl... | Sets cookie value.
:param k: Name for cookie value
:param v: Cookie value
:param expires: Cookie expiration date
:param domain: Cookie domain
:param path: Cookie path
:param secure: Flag for `https only`
:type k: str
:type v: str
:type expires: da... |
def get(self, patch, default=None):
"""
Returns given patch value.
:param patch: Patch name.
:type patch: unicode
:param default: Default value if patch is not found.
:type default: object
:return: Action.
:rtype: QAction
"""
try:
... | Returns given patch value.
:param patch: Patch name.
:type patch: unicode
:param default: Default value if patch is not found.
:type default: object
:return: Action.
:rtype: QAction |
def _basic_login(self):
"""Obtain a new access token from the vendor.
First, try using the refresh_token, if one is available, otherwise
authenticate using the user credentials.
"""
_LOGGER.debug("No/Expired/Invalid access_token, re-authenticating...")
self.access_token ... | Obtain a new access token from the vendor.
First, try using the refresh_token, if one is available, otherwise
authenticate using the user credentials. |
def transform_33_32(inst, new_inst, i, n, offset,
instructions, new_asm):
"""MAKE_FUNCTION, and MAKE_CLOSURE have an additional LOAD_CONST of a name
that are not in Python 3.2. Remove these.
"""
add_size = xdis.op_size(new_inst.opcode, opcode_33)
if inst.opname in ('MAKE_FUNCTION... | MAKE_FUNCTION, and MAKE_CLOSURE have an additional LOAD_CONST of a name
that are not in Python 3.2. Remove these. |
def has_frames(self, destination):
"""
Whether specified queue has any frames.
@param destination: The queue name (destinationination).
@type destination: C{str}
@return: Whether there are any frames in the specified queue.
@rtype: C{bool}
"""
return (de... | Whether specified queue has any frames.
@param destination: The queue name (destinationination).
@type destination: C{str}
@return: Whether there are any frames in the specified queue.
@rtype: C{bool} |
def GetSecurityToken(self, username, password):
"""
Grabs a security Token to authenticate to Office 365 services
"""
url = 'https://login.microsoftonline.com/extSTS.srf'
body = """
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
xm... | Grabs a security Token to authenticate to Office 365 services |
def get(self, name):
"""
Gets an image.
Args:
name (str): The name of the image.
Returns:
(:py:class:`Image`): The image.
Raises:
:py:class:`docker.errors.ImageNotFound`
If the image does not exist.
:py:class:`doc... | Gets an image.
Args:
name (str): The name of the image.
Returns:
(:py:class:`Image`): The image.
Raises:
:py:class:`docker.errors.ImageNotFound`
If the image does not exist.
:py:class:`docker.errors.APIError`
If t... |
def handle_fobj(backend, f, **kwargs):
"""
Handle a file-like object.
Called by `get()` when provided a file-like. This function will prefer the
backend's `handle_fobj()` if one is provided. Otherwise, it will write the
data to a temporary file and call `handle_path()`.
"""
if not is_binary... | Handle a file-like object.
Called by `get()` when provided a file-like. This function will prefer the
backend's `handle_fobj()` if one is provided. Otherwise, it will write the
data to a temporary file and call `handle_path()`. |
def dispatch(self, request, *args, **kwargs):
"""Dispatch all HTTP methods to the proxy."""
self.request = DownstreamRequest(request)
self.args = args
self.kwargs = kwargs
self._verify_config()
self.middleware = MiddlewareSet(self.proxy_middleware)
return self.... | Dispatch all HTTP methods to the proxy. |
def _update_meta(self,directory,filename):
"""Opens up filename.title and
filename.description, updates on flickr"""
if not self._connectToFlickr():
print("%s - Couldn't connect to flickr"%(directory))
return False
db = self._loadDB(directory)
# Look up... | Opens up filename.title and
filename.description, updates on flickr |
def get_build_template():
'''get default build template.
'''
base = get_installdir()
name = "%s/main/templates/build/singularity-cloudbuild.json" % base
if os.path.exists(name):
bot.debug("Found template %s" %name)
return read_json(name)
bot.warning("Template %s not found." % n... | get default build template. |
def build_preauth_str(preauth_key, account_name, timestamp, expires,
admin=False):
""" Builds the preauth string and hmac it, following the zimbra spec.
Spec and examples are here http://wiki.zimbra.com/wiki/Preauth
"""
if admin:
s = '{0}|1|name|{1}|{2}'.format(account_nam... | Builds the preauth string and hmac it, following the zimbra spec.
Spec and examples are here http://wiki.zimbra.com/wiki/Preauth |
def in_hull_volume(self):
r"""
Work out the voxels inside the convex hull of the voronoi vertices of
each pore
"""
i = self.network['pore.internal']
s = self.network['pore.surface']
d = self.network['pore.delaunay']
Ps = self.network.pores()[np.logical_and... | r"""
Work out the voxels inside the convex hull of the voronoi vertices of
each pore |
def _request_activity_data(self, athlete, filename):
"""Actually do the request for activity filename
This call is slow and therefore this method is memory cached.
Keyword arguments:
athlete -- Full name of athlete
filename -- filename of request activity (e.g. \'2015_04_29_09_0... | Actually do the request for activity filename
This call is slow and therefore this method is memory cached.
Keyword arguments:
athlete -- Full name of athlete
filename -- filename of request activity (e.g. \'2015_04_29_09_03_16.json\') |
def _fit_tfa(self, data, R, template_prior=None):
"""TFA main algorithm
Parameters
----------
data: 2D array, in shape [n_voxel, n_tr]
The fMRI data from one subject.
R : 2D array, in shape [n_voxel, n_dim]
The voxel coordinate matrix of fMRI data
... | TFA main algorithm
Parameters
----------
data: 2D array, in shape [n_voxel, n_tr]
The fMRI data from one subject.
R : 2D array, in shape [n_voxel, n_dim]
The voxel coordinate matrix of fMRI data
template_prior : 1D array,
The template prior... |
def _set_master_vlan(self, v, load=False):
"""
Setter method for master_vlan, mapped from YANG variable /topology_group_state/topology_group_data/master_vlan (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_master_vlan is considered as a private
method. Ba... | Setter method for master_vlan, mapped from YANG variable /topology_group_state/topology_group_data/master_vlan (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_master_vlan is considered as a private
method. Backends looking to populate this variable should
do ... |
def reorder_dag(sequence,
depends_getter=lambda x: x.depends_on,
name_getter=lambda x: x.app_name,
impatience_max=100):
"""
DAG = Directed Acyclic Graph
If we have something like:
C depends on B
B depends on A
A doesn't depend on any
... | DAG = Directed Acyclic Graph
If we have something like:
C depends on B
B depends on A
A doesn't depend on any
Given the order of [C, B, A] expect it to return [A, B, C]
parameters:
:sequence: some sort of iterable list
:depends_getter: a callable that extracts the... |
def upload(ctx, check, sdist, dry_run):
"""Release a specific check to PyPI as it is on the repo HEAD."""
if check in get_valid_checks():
check_dir = os.path.join(get_root(), check)
else:
check_dir = resolve_path(check)
if not dir_exists(check_dir):
abort('`{}` is not an ... | Release a specific check to PyPI as it is on the repo HEAD. |
def main():
"""
Main method.
"""
run_config = _parse_args(sys.argv[1:])
if run_config.debug:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
gitlab_config = GitLabConfig(run_config.url, run_config.token)
project_updater_builder = FileBasedProjectVariab... | Main method. |
def push(self, *args, **kwargs):
''' Push commits to remote '''
stdout = six.b('')
# Execute command
cmd = self.git.push(as_process=True, *args, **kwargs)
# Capture output
while True:
output = cmd.stdout.read(1)
sys.stdout.write(outpu... | Push commits to remote |
def action(name, factory, label=None, desc=None):
"""
Annotate a model's action.
@param name: the name of the model's action.
@type name: str or unicode
@param factory: a factory to create actions.
@type factory: IActionFactory
@param label: the action label if specified.
@type label: st... | Annotate a model's action.
@param name: the name of the model's action.
@type name: str or unicode
@param factory: a factory to create actions.
@type factory: IActionFactory
@param label: the action label if specified.
@type label: str or unicode or None
@param desc: the action description i... |
def fromstring(cls, ptb_string, namespace='ptb', precedence=False,
ignore_traces=True):
"""create a PTBDocumentGraph from a string containing PTB parses."""
temp = tempfile.NamedTemporaryFile(delete=False)
temp.write(ptb_string)
temp.close()
ptb_docgraph = cls(p... | create a PTBDocumentGraph from a string containing PTB parses. |
def array_of_vstr(lst):
"""
:param lst: a list of strings or bytes
:returns: an array of variable length ASCII strings
"""
ls = []
for el in lst:
try:
ls.append(el.encode('utf-8'))
except AttributeError:
ls.append(el)
return numpy.array(ls, vstr) | :param lst: a list of strings or bytes
:returns: an array of variable length ASCII strings |
def get_remote_file_size(self, url):
""" Gets the filesize of a remote file.
:param url:
The url that has to be checked.
:type url:
String
:returns:
int
"""
headers = requests.head(url).headers
return int(headers['content-leng... | Gets the filesize of a remote file.
:param url:
The url that has to be checked.
:type url:
String
:returns:
int |
def _sigmainf(N, h, m, dW, Km0, Pm0):
"""Asymptotic covariance matrix \Sigma_\infty Wiktorsson2001 eqn (4.5)"""
M = m*(m-1)//2
Im = broadcast_to(np.eye(m), (N, m, m))
IM = broadcast_to(np.eye(M), (N, M, M))
Ims0 = np.eye(m**2)
factor1 = broadcast_to((2.0/h)*np.dot(Km0, Ims0 - Pm0), (N, M, m**2)... | Asymptotic covariance matrix \Sigma_\infty Wiktorsson2001 eqn (4.5) |
def collect(self, attrs):
"""Collect the implementations from a given attributes dict."""
for name, value in attrs.items():
if self.should_collect(value):
transition = self.workflow.transitions[value.trname]
if (
value.trname in self.... | Collect the implementations from a given attributes dict. |
def calcphot(log, wavelengthArray, fluxArray, obsmode, extrapolate=False):
"""
*Run calcphot on single spectrum and filter.*
**Key Arguments:**
- ``log`` -- logger
- ``wavelengthArray`` -- the array containing the wavelength range of the spectrum
- ``fluxArray`` -- the array contain... | *Run calcphot on single spectrum and filter.*
**Key Arguments:**
- ``log`` -- logger
- ``wavelengthArray`` -- the array containing the wavelength range of the spectrum
- ``fluxArray`` -- the array contain the respective spectrum flux (as function of wavelength)
- ``obsmode`` -- the ... |
def send_message_and_wait(self, message, response_emsg, body_params=None, timeout=None, raises=False):
""".. versionchanged:: 0.8.4
Send a message to CM and wait for a defined answer.
:param message: a message instance
:type message: :class:`.Msg`, :class:`.MsgProto`
:param resp... | .. versionchanged:: 0.8.4
Send a message to CM and wait for a defined answer.
:param message: a message instance
:type message: :class:`.Msg`, :class:`.MsgProto`
:param response_emsg: emsg to wait for
:type response_emsg: :class:`.EMsg`,:class:`int`
:param body_params: a... |
def build_pipeline_string(self, forks):
"""Parses, filters and merge all possible pipeline forks into the
final pipeline string
This method checks for shared start and end sections between forks
and merges them according to the shared processes::
[[spades, ...], [skesa, ...... | Parses, filters and merge all possible pipeline forks into the
final pipeline string
This method checks for shared start and end sections between forks
and merges them according to the shared processes::
[[spades, ...], [skesa, ...], [...,[spades, skesa]]]
-> [..., ... |
def drop_user(self, name):
"""
Drop an MapD user
Parameters
----------
name : string
Database name
"""
statement = ddl.DropUser(name)
self._execute(statement) | Drop an MapD user
Parameters
----------
name : string
Database name |
async def copy_to_table(self, table_name, *, source,
columns=None, schema_name=None, timeout=None,
format=None, oids=None, freeze=None,
delimiter=None, null=None, header=None,
quote=None, escape=None, force_q... | Copy data to the specified table.
:param str table_name:
The name of the table to copy data to.
:param source:
A :term:`path-like object <python:path-like object>`,
or a :term:`file-like object <python:file-like object>`, or
an :term:`asynchronous iterab... |
def secure_channel(target, credentials, options=None, *, loop=None, executor=None,
standalone_pool_for_streaming=False):
"""Creates a secure Channel to a server.
Args:
target: The server address.
credentials: A ChannelCredentials instance.
options: An optional list of key-value pai... | Creates a secure Channel to a server.
Args:
target: The server address.
credentials: A ChannelCredentials instance.
options: An optional list of key-value pairs (channel args in gRPC runtime)
to configure the channel.
Returns:
A Channel object. |
def _retrieve_result(endpoints, token_header):
"""Prepare the request list and execute them concurrently."""
request_list = [
(url, token_header)
for (task_id, url) in endpoints
]
responses = concurrent_get(request_list)
# Quick sanity check
asse... | Prepare the request list and execute them concurrently. |
def watch(self, resource, namespace=None, name=None, label_selector=None, field_selector=None, resource_version=None, timeout=None):
"""
Stream events for a resource from the Kubernetes API
:param resource: The API resource object that will be used to query the API
:param namespace: The... | Stream events for a resource from the Kubernetes API
:param resource: The API resource object that will be used to query the API
:param namespace: The namespace to query
:param name: The name of the resource instance to query
:param label_selector: The label selector with which to filte... |
def search_users(self, user):
"""Search for LDAP users.
Args:
user: User to search for. It is not entirely clear how the
JSS determines the results- are regexes allowed, or
globbing?
Returns:
LDAPUsersResult object.
Raises:
... | Search for LDAP users.
Args:
user: User to search for. It is not entirely clear how the
JSS determines the results- are regexes allowed, or
globbing?
Returns:
LDAPUsersResult object.
Raises:
Will raise a JSSGetError if no res... |
def get_parser():
''' Return the command-line parser '''
parser = argparse.ArgumentParser(
description="Reverse, undo, and calculate CRC32 checksums")
subparsers = parser.add_subparsers(metavar='action')
poly_flip_parser = argparse.ArgumentParser(add_help=False)
subparser_group = poly_flip_... | Return the command-line parser |
def _is_uuid(uuid):
'''
Check if uuid is a valid smartos uuid
Example: e69a0918-055d-11e5-8912-e3ceb6df4cf8
'''
if uuid and list((len(x) for x in uuid.split('-'))) == [8, 4, 4, 4, 12]:
return True
return False | Check if uuid is a valid smartos uuid
Example: e69a0918-055d-11e5-8912-e3ceb6df4cf8 |
def ChunkedAttentionSelector(x, params, selector=None, **kwargs):
"""Select which chunks to attend to in chunked attention.
Args:
x: inputs, a list of elements of the form (q, k, v), mask for each chunk.
params: parameters (unused).
selector: a function from chunk_number -> list of chunk numbers that s... | Select which chunks to attend to in chunked attention.
Args:
x: inputs, a list of elements of the form (q, k, v), mask for each chunk.
params: parameters (unused).
selector: a function from chunk_number -> list of chunk numbers that says
which other chunks should be appended to the given one (previ... |
def plot(self, plot_grouped=False, dates=None, min_dets=1, rate=False,
**kwargs):
"""
Plot the cumulative detections in time.
:type plot_grouped: bool
:param plot_grouped:
Whether to plot all families together (plot_grouped=True), or each
as a separa... | Plot the cumulative detections in time.
:type plot_grouped: bool
:param plot_grouped:
Whether to plot all families together (plot_grouped=True), or each
as a separate line.
:type dates: list
:param dates: list of obspy.core.UTCDateTime objects bounding the
... |
def in_file(self, fn: str) -> Iterator[Statement]:
"""
Returns an iterator over all of the statements belonging to a file.
"""
yield from self.__file_to_statements.get(fn, []) | Returns an iterator over all of the statements belonging to a file. |
def _NormalizeDiscoveryUrls(discovery_url):
"""Expands a few abbreviations into full discovery urls."""
if discovery_url.startswith('http'):
return [discovery_url]
elif '.' not in discovery_url:
raise ValueError('Unrecognized value "%s" for discovery url')
api_name, _, api_version = disc... | Expands a few abbreviations into full discovery urls. |
def add_child(self, widget):
"""
Append a widget to the list.
:param widget: Object inheriting :class:`~.widgets.base.BaseElement`
"""
li_itm = _li(id=self.id + str(self._count))
li_itm.add_child(widget)
super(List, self).add_child(li_itm)
self._items.ap... | Append a widget to the list.
:param widget: Object inheriting :class:`~.widgets.base.BaseElement` |
def rise(self, crd, ev='5deg'):
"""This method will give the rise/set hour-angles of a source. It
needs the position in the frame, and a time. If the latter is not
set, the current time will be used.
:param crd: a direction measure
:param ev: the elevation limit as a quantity or... | This method will give the rise/set hour-angles of a source. It
needs the position in the frame, and a time. If the latter is not
set, the current time will be used.
:param crd: a direction measure
:param ev: the elevation limit as a quantity or string
:returns: `dict` with rise ... |
def get_historic_prices(self, **params):
"""https://developers.coinbase.com/api/v2#get-historic-prices"""
if 'currency_pair' in params:
currency_pair = params['currency_pair']
else:
currency_pair = 'BTC-USD'
response = self._get('v2', 'prices', currency_pair, 'his... | https://developers.coinbase.com/api/v2#get-historic-prices |
def benchmark_process_and_backend(exe, backend):
"""Returns BenchmarkResults for a given executable and backend."""
env = dict(os.environ)
env['GOLESS_BACKEND'] = backend
args = [exe, '-m', 'benchmark']
return get_benchproc_results(args, env=env) | Returns BenchmarkResults for a given executable and backend. |
def add_section(self, section):
"""Create a new section in the configuration. Extends
RawConfigParser.add_section by validating if the section name is
a string."""
section, _, _ = self._validate_value_types(section=section)
super(ConfigParser, self).add_section(section) | Create a new section in the configuration. Extends
RawConfigParser.add_section by validating if the section name is
a string. |
def format_value(value, error, plus_error=None, use_scientific_notation=3,
include_error=True, use_relative_error=False, ndecs=None):
"""Given a numerical value and some bound on it, formats the number into a
string such that the value is rounded to the nearest significant figure,
which is determine... | Given a numerical value and some bound on it, formats the number into a
string such that the value is rounded to the nearest significant figure,
which is determined by the error = abs(value-bound).
Note: if either use_scientific_notation or include_error are True, the
returned string will include LaTeX... |
def get_context(self):
"""Add mails to the context
"""
context = super(MailListView, self).get_context()
mail_list = registered_mails_names()
context['mail_map'] = mail_list
return context | Add mails to the context |
def draw(self, X, y, **kwargs):
"""
Called from the fit method, this method creates the radviz canvas and
draws each instance as a class or target colored point, whose location
is determined by the feature data set.
"""
# Convert from dataframe
if is_dataframe(X):... | Called from the fit method, this method creates the radviz canvas and
draws each instance as a class or target colored point, whose location
is determined by the feature data set. |
def _provision_network(self, port_id, net_uuid, network_type,
physical_network, segmentation_id):
"""Provision the network with the received information."""
LOG.info("Provisioning network %s", net_uuid)
vswitch_name = self._get_vswitch_name(network_type, physical_netw... | Provision the network with the received information. |
def spanstring2text(docgraph, span_string):
"""
converts a span of tokens (str, e.g. 'word_88..word_91') into a string
that contains the tokens itself.
"""
token_node_ids = spanstring2tokens(docgraph, span_string)
return u' '.join(docgraph.node[tok_node_id][docgraph.ns+':token']
... | converts a span of tokens (str, e.g. 'word_88..word_91') into a string
that contains the tokens itself. |
def smoothed(mesh, angle):
"""
Return a non- watertight version of the mesh which will
render nicely with smooth shading by disconnecting faces
at sharp angles to each other.
Parameters
---------
mesh : trimesh.Trimesh
Source geometry
angle : float
Angle in radians, adjacent... | Return a non- watertight version of the mesh which will
render nicely with smooth shading by disconnecting faces
at sharp angles to each other.
Parameters
---------
mesh : trimesh.Trimesh
Source geometry
angle : float
Angle in radians, adjacent faces which have normals
below t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.