positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def all_slots_for(self, cls: ClassDefinition) -> List[SlotDefinitionName]:
""" Return all slots for class cls """
if not cls.is_a:
return cls.slots
else:
return [sn for sn in self.all_slots_for(self.schema.classes[cls.is_a]) if sn not in cls.slot_usage] \
... | Return all slots for class cls |
async def release(self, task_id, *, delay=None):
"""
Release task (return to queue) with delay if specified
:param task_id: Task id
:param delay: Time in seconds before task will become ready again
:return: Task instance
"""
opts = {}
if d... | Release task (return to queue) with delay if specified
:param task_id: Task id
:param delay: Time in seconds before task will become ready again
:return: Task instance |
def days_till_due(self):
"""
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
diff = due - date.today()
... | Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date. |
def check_type_of_param_list_elements(param_list):
"""
Ensures that all elements of param_list are ndarrays or None. Raises a
helpful ValueError if otherwise.
"""
try:
assert isinstance(param_list[0], np.ndarray)
assert all([(x is None or isinstance(x, np.ndarray))
... | Ensures that all elements of param_list are ndarrays or None. Raises a
helpful ValueError if otherwise. |
def walk(self, walk_func):
""" Walks each node of the graph in reverse topological order.
This can be used to perform a set of operations, where the next
operation depends on the previous operation. It's important to note
that walking happens serially, and is not paralellized.
A... | Walks each node of the graph in reverse topological order.
This can be used to perform a set of operations, where the next
operation depends on the previous operation. It's important to note
that walking happens serially, and is not paralellized.
Args:
walk_func (:class:`typ... |
def _format_object(obj, format_type=None):
"""Depending on settings calls either `format_keys` or `format_field_names`"""
if json_api_settings.FORMAT_KEYS is not None:
return format_keys(obj, format_type)
return format_field_names(obj, format_type) | Depending on settings calls either `format_keys` or `format_field_names` |
async def edit(self, *args, **kwargs):
"""
Edits the message iff it's outgoing. Shorthand for
`telethon.client.messages.MessageMethods.edit_message`
with both ``entity`` and ``message`` already set.
Returns ``None`` if the message was incoming,
or the edited `Message` ot... | Edits the message iff it's outgoing. Shorthand for
`telethon.client.messages.MessageMethods.edit_message`
with both ``entity`` and ``message`` already set.
Returns ``None`` if the message was incoming,
or the edited `Message` otherwise.
.. note::
This is different ... |
def reactivate(credit_card_id: str) -> None:
"""
Reactivates a credit card.
"""
logger.info('reactivating-credit-card', credit_card_id=credit_card_id)
with transaction.atomic():
cc = CreditCard.objects.get(pk=credit_card_id)
cc.reactivate()
cc.save() | Reactivates a credit card. |
def fix_surrogates(text):
"""
Replace 16-bit surrogate codepoints with the characters they represent
(when properly paired), or with \ufffd otherwise.
>>> high_surrogate = chr(0xd83d)
>>> low_surrogate = chr(0xdca9)
>>> print(fix_surrogates(high_surrogate + low_surrogate))
�... | Replace 16-bit surrogate codepoints with the characters they represent
(when properly paired), or with \ufffd otherwise.
>>> high_surrogate = chr(0xd83d)
>>> low_surrogate = chr(0xdca9)
>>> print(fix_surrogates(high_surrogate + low_surrogate))
💩
>>> print(fix_surrogates(low... |
def require(self, fieldname, allow_blank=False):
"""fieldname is required"""
if self.request.form and fieldname not in self.request.form.keys():
raise Exception("Required field not found in request: %s" % fieldname)
if self.request.form and (not self.request.form[fieldname] or allow_... | fieldname is required |
def _normalize_and_accrue_digits_and_plus_sign(self, next_char, remember_position):
"""Accrues digits and the plus sign to
_accrued_input_without_formatting for later use. If next_char contains
a digit in non-ASCII format (e.g. the full-width version of digits),
it is first normalized to... | Accrues digits and the plus sign to
_accrued_input_without_formatting for later use. If next_char contains
a digit in non-ASCII format (e.g. the full-width version of digits),
it is first normalized to the ASCII version. The return value is
next_char itself, or its normalized version, if... |
def filter_(data, axis='time', low_cut=None, high_cut=None, order=4,
ftype='butter', Rs=None, notchfreq=50, notchquality=25):
"""Design filter and apply it.
Parameters
----------
ftype : str
'butter', 'cheby1', 'cheby2', 'ellip', 'bessel', 'diff', or 'notch'
axis : str, optional... | Design filter and apply it.
Parameters
----------
ftype : str
'butter', 'cheby1', 'cheby2', 'ellip', 'bessel', 'diff', or 'notch'
axis : str, optional
axis to apply the filter on.
low_cut : float, optional
(not for notch) low cutoff for high-pass filter
high_cut : float,... |
def slice(cls, *args, **kwargs):
"""Take a slice of a DataSetFamily to produce a dataset
indexed by asset and date.
Parameters
----------
*args
**kwargs
The coordinates to fix along each extra dimension.
Returns
-------
dataset : Data... | Take a slice of a DataSetFamily to produce a dataset
indexed by asset and date.
Parameters
----------
*args
**kwargs
The coordinates to fix along each extra dimension.
Returns
-------
dataset : DataSet
A regular pipeline dataset i... |
def assert_invalid_field_list(field_list):
"""raise d1_common.types.exceptions.InvalidRequest() if ``field_list`` contains any
invalid field names. A list of the invalid fields is included in the exception.
- Implicitly called by ``extract_values()``.
"""
if field_list is not None:
invalid... | raise d1_common.types.exceptions.InvalidRequest() if ``field_list`` contains any
invalid field names. A list of the invalid fields is included in the exception.
- Implicitly called by ``extract_values()``. |
def _convert_to_container_dirs(host_paths_to_convert, host_to_container_path_mapping):
"""
Use this method to convert a list of host paths to a list of equivalent paths within the container
where the given host path is mounted. This is necessary when SAM CLI needs to pass path information to
... | Use this method to convert a list of host paths to a list of equivalent paths within the container
where the given host path is mounted. This is necessary when SAM CLI needs to pass path information to
the Lambda Builder running within the container.
If a host path is not mounted within the con... |
def _analyze_states(state: GlobalState) -> List[Issue]:
"""
:param state: the current state
:return: returns the issues for that corresponding state
"""
call = get_call_from_state(state)
if call is None:
return []
issues = [] # type: List[Issue]
if call.type is not "DELEGATECAL... | :param state: the current state
:return: returns the issues for that corresponding state |
def _header(self, pam=False):
"""Return file header as byte string."""
if pam or self.magicnum == b'P7':
header = "\n".join((
"P7",
"HEIGHT %i" % self.height,
"WIDTH %i" % self.width,
"DEPTH %i" % self.depth,
"MA... | Return file header as byte string. |
def processor(ctx, processor_cls, process_time_limit, enable_stdout_capture=True, get_object=False):
"""
Run Processor.
"""
g = ctx.obj
Processor = load_cls(None, None, processor_cls)
processor = Processor(projectdb=g.projectdb,
inqueue=g.fetcher2processor, status_queu... | Run Processor. |
def create_photo(self, blogname, **kwargs):
"""
Create a photo post or photoset on a blog
:param blogname: a string, the url of the blog you want to post to.
:param state: a string, The state of the post.
:param tags: a list of tags that you want applied to the post
:par... | Create a photo post or photoset on a blog
:param blogname: a string, the url of the blog you want to post to.
:param state: a string, The state of the post.
:param tags: a list of tags that you want applied to the post
:param tweet: a string, the customized tweet that you want
:... |
def fit(self, X, C):
"""
Fit a filter tree classifier
Note
----
Shifting the order of the classes within the cost array will produce different
results, as it will build a different binary tree comparing different classes
at each node.
Par... | Fit a filter tree classifier
Note
----
Shifting the order of the classes within the cost array will produce different
results, as it will build a different binary tree comparing different classes
at each node.
Parameters
----------
X : ar... |
def softplus(X):
""" Pass X through a soft-plus function, , in a numerically
stable way (using the log-sum-exp trick).
The softplus transformation is:
.. math::
\log(1 + \exp\{X\})
Parameters
----------
X: ndarray
shape (N,) array or... | Pass X through a soft-plus function, , in a numerically
stable way (using the log-sum-exp trick).
The softplus transformation is:
.. math::
\log(1 + \exp\{X\})
Parameters
----------
X: ndarray
shape (N,) array or shape (N, D) array of da... |
def run(self):
"""
Copy libraries from the bin directory and place them as appropriate
"""
self.announce("Moving library files", level=3)
# We have already built the libraries in the previous build_ext step
self.skip_build = True
bin_dir = self.distribution.bi... | Copy libraries from the bin directory and place them as appropriate |
def find_first_tag(tags, entity_type, after_index=-1):
"""Searches tags for entity type after given index
Args:
tags(list): a list of tags with entity types to be compaired too entity_type
entity_type(str): This is he entity type to be looking for in tags
after_index(int): the start tok... | Searches tags for entity type after given index
Args:
tags(list): a list of tags with entity types to be compaired too entity_type
entity_type(str): This is he entity type to be looking for in tags
after_index(int): the start token must be greaterthan this.
Returns:
( tag, v, c... |
def service_create(name, service_type, description=None, profile=None,
**connection_args):
'''
Add service to Keystone service catalog
CLI Examples:
.. code-block:: bash
salt '*' keystone.service_create nova compute \
'OpenStack Compute Service'
'''
kstone = auth(pr... | Add service to Keystone service catalog
CLI Examples:
.. code-block:: bash
salt '*' keystone.service_create nova compute \
'OpenStack Compute Service' |
def generate_samples(label, num_splits, sampler):
""" Split labels into `num_splits` and
generate candidates based on log-uniform distribution.
"""
def listify(x):
return x if isinstance(x, list) else [x]
label_splits = listify(label.split(num_splits, axis=0))
prob_samples = []
p... | Split labels into `num_splits` and
generate candidates based on log-uniform distribution. |
def getGlobalDeformationEnergy(self, bp, complexDna, freeDnaFrames=None, boundDnaFrames=None, paxis='Z',
which='all', masked=False, outFile=None):
r"""Deformation energy of the input DNA using Global elastic properties
It can be used to calculated deformation energy o... | r"""Deformation energy of the input DNA using Global elastic properties
It can be used to calculated deformation energy of a input DNA with reference to the DNA present in the current
object.
The deformation free energy is calculated using elastic matrix as follows
.. math::
... |
def request(self, msg, timeout=30):
'''request
High-level api: sends message through NetConf session and returns with
a reply. Exception is thrown out either the reply is in wrong
format or timout. Users can modify timeout value (in seconds) by
passing parameter timeout. Users m... | request
High-level api: sends message through NetConf session and returns with
a reply. Exception is thrown out either the reply is in wrong
format or timout. Users can modify timeout value (in seconds) by
passing parameter timeout. Users may want to set a larger timeout when
ma... |
def columns_in_formula(formula):
"""
Returns the names of all the columns used in a patsy formula.
Parameters
----------
formula : str, iterable, or dict
Any formula construction supported by ``str_model_expression``.
Returns
-------
columns : list of str
"""
if formul... | Returns the names of all the columns used in a patsy formula.
Parameters
----------
formula : str, iterable, or dict
Any formula construction supported by ``str_model_expression``.
Returns
-------
columns : list of str |
def _build_meta(text: str, title: str) -> DocstringMeta:
"""Build docstring element.
:param text: docstring element text
:param title: title of section containing element
:return:
"""
meta = _sections[title]
if meta == "returns" and ":" not in text.split()[0]:
return DocstringMeta(... | Build docstring element.
:param text: docstring element text
:param title: title of section containing element
:return: |
def check_aubio():
"Check Aubio availability"
try:
import aubio
except ImportError:
warnings.warn('Aubio librairy is not available', ImportWarning,
stacklevel=2)
_WITH_AUBIO = False
else:
_WITH_AUBIO = True
del aubio
return _WITH_AUBIO | Check Aubio availability |
def derivativeW(self,w,x,y,z):
'''
Evaluates the partial derivative with respect to w (the first argument)
of the interpolated function at the given input.
Parameters
----------
w : np.array or float
Real values to be evaluated in the interpolated function.
... | Evaluates the partial derivative with respect to w (the first argument)
of the interpolated function at the given input.
Parameters
----------
w : np.array or float
Real values to be evaluated in the interpolated function.
x : np.array or float
Real value... |
def location(self, filetype, base_dir=None, **kwargs):
"""Return the location of the relative sas path of a given type of file.
Parameters
----------
filetype : str
File type parameter.
Returns
-------
full : str
The relative sas path to ... | Return the location of the relative sas path of a given type of file.
Parameters
----------
filetype : str
File type parameter.
Returns
-------
full : str
The relative sas path to the file. |
def get_relationship_query_session_for_family(self, family_id=None, proxy=None):
"""Gets the ``OsidSession`` associated with the relationship query service for the given family.
arg: family_id (osid.id.Id): the ``Id`` of the family
arg: proxy (osid.proxy.Proxy): a proxy
return: (o... | Gets the ``OsidSession`` associated with the relationship query service for the given family.
arg: family_id (osid.id.Id): the ``Id`` of the family
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.relationship.RelationshipQuerySession) - a
``RelationshipQuerySession``
... |
def get_id(self):
"""Returns unique id of an alignment. """
return hash(str(self.title) + str(self.best_score()) + str(self.hit_def)) | Returns unique id of an alignment. |
def insertUserStore(siteStore, userStorePath):
"""
Move the SubStore at the indicated location into the given site store's
directory and then hook it up to the site store's authentication database.
@type siteStore: C{Store}
@type userStorePath: C{FilePath}
"""
# The following may, but does ... | Move the SubStore at the indicated location into the given site store's
directory and then hook it up to the site store's authentication database.
@type siteStore: C{Store}
@type userStorePath: C{FilePath} |
def cublasCtpsv(handle, uplo, trans, diag, n, AP, x, incx):
"""
Solve complex triangular-packed system with one right-hand side.
"""
status = _libcublas.cublasCtpsv_v2(handle,
_CUBLAS_FILL_MODE[uplo],
_CUBLAS_OP[tra... | Solve complex triangular-packed system with one right-hand side. |
def run(time: datetime, altkm: float,
glat: Union[float, np.ndarray], glon: Union[float, np.ndarray], *,
f107a: float = None, f107: float = None, Ap: int = None) -> xarray.Dataset:
"""
loops the rungtd1d function below. Figure it's easier to troubleshoot in Python than Fortran.
"""
glat ... | loops the rungtd1d function below. Figure it's easier to troubleshoot in Python than Fortran. |
def set_analog_latch(self, pin, threshold_type, threshold_value,
cb=None, cb_type=None):
"""
This method "arms" an analog pin for its data to be latched and
saved in the latching table.
If a callback method is provided, when latching criteria is achieved,
... | This method "arms" an analog pin for its data to be latched and
saved in the latching table.
If a callback method is provided, when latching criteria is achieved,
the callback function is called with latching data notification.
:param pin: Analog pin number (value following an 'A' desig... |
def drop_layer(self, layer):
"""Removes the named layer and the value associated with it from the node.
Parameters
----------
layer : str
Name of the layer to drop.
Raises
------
TypeError
If the node is frozen
KeyError
... | Removes the named layer and the value associated with it from the node.
Parameters
----------
layer : str
Name of the layer to drop.
Raises
------
TypeError
If the node is frozen
KeyError
If the named layer does not exist |
def on_connect(self, connection):
"""
Called when the socket connects
"""
self._sock = connection._sock
self._buffer = SocketBuffer(self._sock, self.socket_read_size)
if connection.decode_responses:
self.encoding = connection.encoding | Called when the socket connects |
def switch(self, device_id, obj_slot_id):
"""Switching of device-context"""
payload = {
"device-context": self._build_payload(device_id, obj_slot_id)
}
return self._post(self.url_prefix, payload) | Switching of device-context |
def evaluate_policy(model,
mdr,
tol=1e-8,
maxit=2000,
grid={},
verbose=True,
initial_guess=None,
hook=None,
integration_orders=None,
details... | Compute value function corresponding to policy ``dr``
Parameters:
-----------
model:
"dtcscc" model. Must contain a 'value' function.
mdr:
decision rule to evaluate
Returns:
--------
decision rule:
value function (a function of the space similar to a decision rul... |
def async_call(self, fn, *args, **kwargs):
"""Schedule `fn` to be called by the event loop soon.
This function is thread-safe, and is the only way code not
on the main thread could interact with nvim api objects.
This function can also be called in a synchronous
event handler, ... | Schedule `fn` to be called by the event loop soon.
This function is thread-safe, and is the only way code not
on the main thread could interact with nvim api objects.
This function can also be called in a synchronous
event handler, just before it returns, to defer execution
tha... |
def create(cls, domain, tlp_level=0, tags=[]):
"""
Create a new :class:`DomainSample` on the server.
:param domain: The domain as a string.
:param tlp_level: The TLP-Level
:param tags: Tags to add to the sample.
:return: The created sample.
"""
return cls... | Create a new :class:`DomainSample` on the server.
:param domain: The domain as a string.
:param tlp_level: The TLP-Level
:param tags: Tags to add to the sample.
:return: The created sample. |
def unfinished(finished_status,
update_interval,
status_key,
edit_at_key):
"""
Create dict query for pymongo that getting all unfinished task.
:param finished_status: int, status code that less than this
will be considered as unfinished.
:param updat... | Create dict query for pymongo that getting all unfinished task.
:param finished_status: int, status code that less than this
will be considered as unfinished.
:param update_interval: int, the record will be updated every x seconds.
:param status_key: status code field key, support dot notation.
... |
def insert_runner(fun, args=None, kwargs=None, queue=None, backend=None):
'''
Insert a reference to a runner into the queue so that it can be run later.
fun
The runner function that is going to be run
args
list or comma-seperated string of args to send to fun
kwargs
dictio... | Insert a reference to a runner into the queue so that it can be run later.
fun
The runner function that is going to be run
args
list or comma-seperated string of args to send to fun
kwargs
dictionary of keyword arguments to send to fun
queue
queue to insert the runner... |
def silhouette_score(X, labels, metric='euclidean', sample_size=None,
random_state=None, **kwds):
"""Compute the mean Silhouette Coefficient of all samples.
The Silhouette Coefficient is calculated using the mean intra-cluster
distance (``a``) and the mean nearest-cluster distance (``b... | Compute the mean Silhouette Coefficient of all samples.
The Silhouette Coefficient is calculated using the mean intra-cluster
distance (``a``) and the mean nearest-cluster distance (``b``) for each
sample. The Silhouette Coefficient for a sample is ``(b - a) / max(a,
b)``. To clarify, ``b`` is the di... |
def _gerritCmd(self, *args):
'''Construct a command as a list of strings suitable for
:func:`subprocess.call`.
'''
if self.gerrit_identity_file is not None:
options = ['-i', self.gerrit_identity_file]
else:
options = []
return ['ssh'] + options + [... | Construct a command as a list of strings suitable for
:func:`subprocess.call`. |
def cross(self, other):
'''
:other: Point or point equivalent
:return: float
Vector cross product of points U (self) and V (other), computed:
U x V = (u1*i + u2*j + u3*k) x (v1*i + v2*j + v3*k)
s1 = u2v3 - u3v2
s2 = u3v1 - u1v3
s3 = u1v2 - u2v1
... | :other: Point or point equivalent
:return: float
Vector cross product of points U (self) and V (other), computed:
U x V = (u1*i + u2*j + u3*k) x (v1*i + v2*j + v3*k)
s1 = u2v3 - u3v2
s2 = u3v1 - u1v3
s3 = u1v2 - u2v1
U x V = s1 + s2 + s3
Returns a floa... |
def quoted(arg):
""" Given a string, return a quoted string as per RFC 3501, section 9.
Implementation copied from https://github.com/mjs/imapclient
(imapclient/imapclient.py), 3-clause BSD license
"""
if isinstance(arg, str):
arg = arg.replace('\\', '\\\\')
arg = arg.replac... | Given a string, return a quoted string as per RFC 3501, section 9.
Implementation copied from https://github.com/mjs/imapclient
(imapclient/imapclient.py), 3-clause BSD license |
def new_conv(self, name: str, kernel_size: tuple, channels_output: int,
stride_size: tuple, padding: str='SAME',
group: int=1, biased: bool=True, relu: bool=True, input_layer_name: str=None):
"""
Creates a convolution layer for the network.
:param name: name for... | Creates a convolution layer for the network.
:param name: name for the layer
:param kernel_size: tuple containing the size of the kernel (Width, Height)
:param channels_output: ¿? Perhaps number of channels in the output? it is used as the bias size.
:param stride_size: tuple containing ... |
def get_segment(neuron, section_id, segment_id):
'''Get a segment given a section and segment id
Returns:
array of two [x, y, z, r] points defining segment
'''
sec = neuron.sections[section_id]
return sec.points[segment_id:segment_id + 2][:, COLS.XYZR] | Get a segment given a section and segment id
Returns:
array of two [x, y, z, r] points defining segment |
def add_flags(self, flag_name, flags, target_name=None, configuration_name=None):
"""
Adds the given flags to the flag_name section of the target on the configurations
:param flag_name: name of the flag to be added the values to
:param flags: A string or array of strings
:param t... | Adds the given flags to the flag_name section of the target on the configurations
:param flag_name: name of the flag to be added the values to
:param flags: A string or array of strings
:param target_name: Target name or list of target names to add the flag to or None for every target
:p... |
def from_nodes(cls, nodes, new_nodes, max_slaves_limit=None):
'''When this is used only for peeking reuslt
`new_nodes` can be any type with `host` and `port` attributes
'''
param = gen_distribution(nodes, new_nodes)
param['max_slaves_limit'] = max_slaves_limit
return c... | When this is used only for peeking reuslt
`new_nodes` can be any type with `host` and `port` attributes |
def close(self):
"""
Closes the connection and any tunnels created for it.
"""
try:
super(DockerFabricClient, self).close()
finally:
if self._tunnel is not None:
self._tunnel.close() | Closes the connection and any tunnels created for it. |
def handleNotification(self, req):
"""handles a notification request by calling the appropriete method the service exposes"""
name = req["method"]
params = req["params"]
try: #to get a callable obj
obj = getMethodByName(self.service, name)
rslt = obj(*params)
... | handles a notification request by calling the appropriete method the service exposes |
def histogram(
arg, nbins=None, binwidth=None, base=None, closed='left', aux_hash=None
):
"""
Compute a histogram with fixed width bins
Parameters
----------
arg : numeric array expression
nbins : int, default None
If supplied, will be used to compute the binwidth
binwidth : numbe... | Compute a histogram with fixed width bins
Parameters
----------
arg : numeric array expression
nbins : int, default None
If supplied, will be used to compute the binwidth
binwidth : number, default None
If not supplied, computed from the data (actual max and min values)
base : numbe... |
def fallback_render(template, context, at_paths=None,
at_encoding=anytemplate.compat.ENCODING,
**kwargs):
"""
Render from given template and context.
This is a basic implementation actually does nothing and just returns
the content of given template file `templat... | Render from given template and context.
This is a basic implementation actually does nothing and just returns
the content of given template file `template`.
:param template: Template file path
:param context: A dict or dict-like object to instantiate given
template file
:param at_paths: Te... |
def _assertIndex(self, index):
"""Raise TypeError or IndexError if index is not an integer or out of
range for the number of elements in this array, respectively.
"""
if type(index) is not int:
raise TypeError('list indices must be integers')
if index < 0 or index >= ... | Raise TypeError or IndexError if index is not an integer or out of
range for the number of elements in this array, respectively. |
def distance_to(self, other_catchment):
"""
Returns the distance between the centroids of two catchments in kilometers.
:param other_catchment: Catchment to calculate distance to
:type other_catchment: :class:`.Catchment`
:return: Distance between the catchments in km.
:... | Returns the distance between the centroids of two catchments in kilometers.
:param other_catchment: Catchment to calculate distance to
:type other_catchment: :class:`.Catchment`
:return: Distance between the catchments in km.
:rtype: float |
def expand_tarball(tarball_fname,cwd=None):
"expand a tarball"
if tarball_fname.endswith('.gz'): opts = 'xzf'
elif tarball_fname.endswith('.bz2'): opts = 'xjf'
else: opts = 'xf'
args = ['/bin/tar',opts,tarball_fname]
process_command(args, cwd=cwd) | expand a tarball |
def read(self):
"""Reads the data stored in the files we have been initialized with. It will
ignore files that cannot be read, possibly leaving an empty configuration
:return: Nothing
:raise IOError: if a file cannot be handled"""
if self._is_initialized:
return
... | Reads the data stored in the files we have been initialized with. It will
ignore files that cannot be read, possibly leaving an empty configuration
:return: Nothing
:raise IOError: if a file cannot be handled |
def is_public_member(self, login):
"""Check if the user with login ``login`` is a public member.
:returns: bool
"""
url = self._build_url('public_members', login, base_url=self._api)
return self._boolean(self._get(url), 204, 404) | Check if the user with login ``login`` is a public member.
:returns: bool |
def to_unicode(path, errors="replace"):
"""Given a bytestring/unicode path, return it as unicode."""
if isinstance(path, UNICODE):
return path
return path.decode(sys.getfilesystemencoding(), errors) | Given a bytestring/unicode path, return it as unicode. |
def commit(self, index_update=True, label_guesser_update=True):
"""
Apply the changes to the index
"""
logger.info("Index: Commiting changes")
self.docsearch.index.commit(index_update=index_update,
label_guesser_update=label_guesser_update) | Apply the changes to the index |
def path_trace(map_projection, pts, closed=False, meta_data=None):
'''
path_trace(proj, points) yields a path-trace object that represents the given path of points on
the given map projection proj.
The following options may be given:
* closed (default: False) specifies whether the points fo... | path_trace(proj, points) yields a path-trace object that represents the given path of points on
the given map projection proj.
The following options may be given:
* closed (default: False) specifies whether the points form a closed loop. If they do form
such a loop, the points should be giv... |
def hook(self, id_num):
"""Get a single hook.
:param int id_num: (required), id of the hook
:returns: :class:`Hook <github3.repos.hook.Hook>` if successful,
otherwise None
"""
json = None
if int(id_num) > 0:
url = self._build_url('hooks', str(id_n... | Get a single hook.
:param int id_num: (required), id of the hook
:returns: :class:`Hook <github3.repos.hook.Hook>` if successful,
otherwise None |
def add_new_next_method(obj):
"""
TODO
"""
def new_next(self):
field_values = [next(g) for g in self.field_gens.values()]
return self.item_cls(*field_values)
obj.__next__ = new_next | TODO |
def functions(self):
""" Return a sorted list of the function names available on the object.
"""
names = []
for i, k in enumerate(self.obj):
if _(self.obj[k]).isCallable():
names.append(k)
return self._wrap(sorted(names)) | Return a sorted list of the function names available on the object. |
def download_article(id_val, id_type='doi', on_retry=False):
"""Low level function to get an XML article for a particular id.
Parameters
----------
id_val : str
The value of the id.
id_type : str
The type of id, such as pmid (a.k.a. pubmed_id), doi, or eid.
on_retry : bool
... | Low level function to get an XML article for a particular id.
Parameters
----------
id_val : str
The value of the id.
id_type : str
The type of id, such as pmid (a.k.a. pubmed_id), doi, or eid.
on_retry : bool
This function has a recursive retry feature, and this is the only... |
def find_vmrun(self):
"""
Searches for vmrun.
:returns: path to vmrun
"""
# look for vmrun
vmrun_path = self.config.get_section_config("VMware").get("vmrun_path")
if not vmrun_path:
if sys.platform.startswith("win"):
vmrun_path = shut... | Searches for vmrun.
:returns: path to vmrun |
def unparse_color(r, g, b, a, type):
"""
Take the r, g, b, a color values and give back
a type css color string. This is the inverse function of parse_color
"""
if type == '#rgb':
# Don't lose precision on rgb shortcut
if r % 17 == 0 and g % 17 == 0 and b % 17 == 0:
retur... | Take the r, g, b, a color values and give back
a type css color string. This is the inverse function of parse_color |
def parse_specification(spec):
"""
Parse a requirement from a python distribution metadata and return a
tuple with name, extras, constraints, marker and url components.
This method does not enforce strict specifications but extracts the
information which is assumed to be *correct*. As such no error... | Parse a requirement from a python distribution metadata and return a
tuple with name, extras, constraints, marker and url components.
This method does not enforce strict specifications but extracts the
information which is assumed to be *correct*. As such no errors are raised.
Example
-------
... |
def same_page(c):
"""Return true if all the components of c are on the same page of the document.
Page numbers are based on the PDF rendering of the document. If a PDF file is
provided, it is used. Otherwise, if only a HTML/XML document is provided, a
PDF is created and then used to determine the page ... | Return true if all the components of c are on the same page of the document.
Page numbers are based on the PDF rendering of the document. If a PDF file is
provided, it is used. Otherwise, if only a HTML/XML document is provided, a
PDF is created and then used to determine the page number of a Mention.
... |
def colRowIsOnSciencePixel(self, col, row, padding=DEFAULT_PADDING):
"""Is col row on a science pixel?
Ranges taken from Fig 25 or Instrument Handbook (p50)
Padding allows for the fact that distortion means the
results from getColRowWithinChannel can be off by a bit.
Setting pa... | Is col row on a science pixel?
Ranges taken from Fig 25 or Instrument Handbook (p50)
Padding allows for the fact that distortion means the
results from getColRowWithinChannel can be off by a bit.
Setting padding > 0 means that objects that are computed
to lie a small amount off... |
def _query_view(self, model, **kwargs):
"""
:param model:
:return: (query, condition)
Default use QueryForm
"""
QueryForm = functions.get_form('QueryForm')
if 'form_cls' not in kwargs:
kwargs['form_cls'] = QueryForm
query = functions.QueryVie... | :param model:
:return: (query, condition)
Default use QueryForm |
def singleton_init_by(init_fn=None):
"""
>>> from Redy.Magic.Classic import singleton
>>> @singleton
>>> class S:
>>> pass
>>> assert isinstance(S, S)
"""
if not init_fn:
def wrap_init(origin_init):
return origin_init
else:
def wrap_init(origin_init):... | >>> from Redy.Magic.Classic import singleton
>>> @singleton
>>> class S:
>>> pass
>>> assert isinstance(S, S) |
def _checkIfCode(self, inCodeBlockObj):
"""Checks whether or not a given line appears to be Python code."""
while True:
line, lines, lineNum = (yield)
testLineNum = 1
currentLineNum = 0
testLine = line.strip()
lineOfCode = None
whil... | Checks whether or not a given line appears to be Python code. |
def _update_redundancy_routers(self, context, updated_router,
update_specification, requested_ha_settings,
updated_router_db, gateway_changed):
"""To be called in update_router() AFTER router has been
updated in DB.
"""
... | To be called in update_router() AFTER router has been
updated in DB. |
def get_associated_uplink_groups(self):
"""
Gets the uplink sets which are using an Ethernet network.
Returns:
list: URIs of the associated uplink sets.
"""
uri = "{}/associatedUplinkGroups".format(self.data['uri'])
return self._helper.do_get(uri) | Gets the uplink sets which are using an Ethernet network.
Returns:
list: URIs of the associated uplink sets. |
def get_first_non_label_instruction(self):
""" Returns the memcell of the given block, which is
not a LABEL.
"""
for i in range(len(self)):
if not self.mem[i].is_label:
return self.mem[i]
return None | Returns the memcell of the given block, which is
not a LABEL. |
def _EntriesGenerator(self):
"""Retrieves directory entries.
Since a directory can contain a vast number of entries using
a generator is more memory efficient.
Yields:
OSPathSpec: a path specification.
Raises:
AccessError: if the access to list the directory was denied.
BackEndE... | Retrieves directory entries.
Since a directory can contain a vast number of entries using
a generator is more memory efficient.
Yields:
OSPathSpec: a path specification.
Raises:
AccessError: if the access to list the directory was denied.
BackEndError: if the directory could not be ... |
def execute(self, input_data):
''' This worker computes meta data for any file type. '''
raw_bytes = input_data['sample']['raw_bytes']
self.meta['md5'] = hashlib.md5(raw_bytes).hexdigest()
self.meta['tags'] = input_data['tags']['tags']
self.meta['type_tag'] = input_data['sample']... | This worker computes meta data for any file type. |
def plot(self, filename, title=None, reciprocal=None, limits=None,
dtype='rho', return_fig=False, **kwargs):
"""Standard plot of spectrum
Parameters
----------
filename: string
Output filename. Include the ending to specify the filetype
(usually .pdf... | Standard plot of spectrum
Parameters
----------
filename: string
Output filename. Include the ending to specify the filetype
(usually .pdf or .png)
title: string, optional
Title for the plot
reciprocal: :class:`reda.eis.plots.sip_response`, op... |
def _gen_keys_from_multicol_key(key_multicol, n_keys):
"""Generates single-column keys from multicolumn key."""
keys = [('{}{:03}of{:03}')
.format(key_multicol, i+1, n_keys) for i in range(n_keys)]
return keys | Generates single-column keys from multicolumn key. |
def execute(self,
image = None,
command = None,
app = None,
writable = False,
contain = False,
bind = None,
stream = False,
nv = False,
return_result=False):
''' execute: send a command to a container
... | execute: send a command to a container
Parameters
==========
image: full path to singularity image
command: command to send to container
app: if not None, execute a command in context of an app
writable: This option makes the file system accessible as read/write
... |
def matrix(self, coordinates, profile='mapbox/driving',
sources=None, destinations=None, annotations=None):
"""Request a directions matrix for trips between coordinates
In the default case, the matrix returns a symmetric matrix,
using all input coordinates as sources and destina... | Request a directions matrix for trips between coordinates
In the default case, the matrix returns a symmetric matrix,
using all input coordinates as sources and destinations. You may
also generate an asymmetric matrix, with only some coordinates
as sources or destinations:
Para... |
def build_bot(config_file=None):
"""Parse a config and return a SeshetBot instance. After, the bot can be run
simply by calling .connect() and then .start()
Optional arguments:
config_file - valid file path or ConfigParser instance
If config_file is None, will read default conf... | Parse a config and return a SeshetBot instance. After, the bot can be run
simply by calling .connect() and then .start()
Optional arguments:
config_file - valid file path or ConfigParser instance
If config_file is None, will read default config defined in this module. |
def scalar_input_map(func, input_):
"""
Map like function
Args:
func: function to apply
input_ : either an iterable or scalar value
Returns:
If ``input_`` is iterable this function behaves like map
otherwise applies func to ``input_``
"""
if util_iter.isiterable... | Map like function
Args:
func: function to apply
input_ : either an iterable or scalar value
Returns:
If ``input_`` is iterable this function behaves like map
otherwise applies func to ``input_`` |
def _check_port(host, port, socket_type):
"""
Check if an a port is available and raise an OSError if port is not available
:returns: boolean
"""
if socket_type == "UDP":
socket_type = socket.SOCK_DGRAM
else:
socket_type = socket.SOCK_STREAM
... | Check if an a port is available and raise an OSError if port is not available
:returns: boolean |
def get_oauth_params(self, request):
"""Get the basic OAuth parameters to be used in generating a signature.
"""
nonce = (generate_nonce()
if self.nonce is None else self.nonce)
timestamp = (generate_timestamp()
if self.timestamp is None else self.ti... | Get the basic OAuth parameters to be used in generating a signature. |
def position_half_h(pslit, cpix, backw=4):
"""Find the position where the value is half of the peak"""
# Find the first peak to the right of cpix
next_peak = simple_prot(pslit, cpix)
if next_peak is None:
raise ValueError
dis_peak = next_peak - cpix
wpos2 = cpix - dis_peak
wpos1 ... | Find the position where the value is half of the peak |
def convert_timestamp(obj):
"""Make an ARF timestamp from an object.
Argument can be a datetime.datetime object, a time.struct_time, an integer,
a float, or a tuple of integers. The returned value is a numpy array with
the integer number of seconds since the Epoch and any additional
microseconds.
... | Make an ARF timestamp from an object.
Argument can be a datetime.datetime object, a time.struct_time, an integer,
a float, or a tuple of integers. The returned value is a numpy array with
the integer number of seconds since the Epoch and any additional
microseconds.
Note that because floating poin... |
def token(self, value):
""" Setter to convert any token dict into Token instance """
if value and not isinstance(value, Token):
value = Token(value)
self._token = value | Setter to convert any token dict into Token instance |
def db_temp_from_wb_rh(wet_bulb, rel_humid, b_press=101325):
"""Dry Bulb Temperature (C) and humidity_ratio at at wet_bulb (C),
rel_humid (%) and Pressure b_press (Pa).
Formula is only valid for rel_humid == 0 or rel_humid == 100.
"""
assert rel_humid == 0 or rel_humid == 100, 'formula is only vali... | Dry Bulb Temperature (C) and humidity_ratio at at wet_bulb (C),
rel_humid (%) and Pressure b_press (Pa).
Formula is only valid for rel_humid == 0 or rel_humid == 100. |
def client(cls, config):
"""
Cache statsd client so it doesn't do a DNS lookup
over and over
"""
if not hasattr(cls, "_client"):
cls._client = statsd.StatsClient(config.STATSD_HOST, config.STATSD_PORT, config.STATSD_PREFIX)
return cls._client | Cache statsd client so it doesn't do a DNS lookup
over and over |
def _simsearch_to_simresult(self, sim_resp: Dict, method: SimAlgorithm) -> SimResult:
"""
Convert owlsim json to SimResult object
:param sim_resp: owlsim response from search_by_attribute_set()
:param method: SimAlgorithm
:return: SimResult object
"""
sim_ids = ... | Convert owlsim json to SimResult object
:param sim_resp: owlsim response from search_by_attribute_set()
:param method: SimAlgorithm
:return: SimResult object |
def load_collided_alias(self):
"""
Load (create, if not exist) the collided alias file.
"""
# w+ creates the alias config file if it does not exist
open_mode = 'r+' if os.path.exists(GLOBAL_COLLIDED_ALIAS_PATH) else 'w+'
with open(GLOBAL_COLLIDED_ALIAS_PATH, open_mode) as... | Load (create, if not exist) the collided alias file. |
def _action_set_subsumption(self, action_set):
"""Perform action set subsumption."""
# Select a condition with maximum bit count among those having
# sufficient experience and sufficiently low error.
selected_rule = None
selected_bit_count = None
for rule in action_set:
... | Perform action set subsumption. |
def subdivide(self, N=1, method=0):
"""Increase the number of vertices of a surface mesh.
:param int N: number of subdivisions.
:param int method: Loop(0), Linear(1), Adaptive(2), Butterfly(3)
.. hint:: |tutorial_subdivide| |tutorial.py|_
"""
triangles = vtk.vtkTriangle... | Increase the number of vertices of a surface mesh.
:param int N: number of subdivisions.
:param int method: Loop(0), Linear(1), Adaptive(2), Butterfly(3)
.. hint:: |tutorial_subdivide| |tutorial.py|_ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.