code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _build_action_bound_constraints_table(self):
'''Builds the lower and upper action bound constraint expressions.'''
self.action_lower_bound_constraints = {}
self.action_upper_bound_constraints = {}
for name, preconds in self.local_action_preconditions.items():
for precon... | Builds the lower and upper action bound constraint expressions. |
def insert(self, key, value, ttl=0, format=None, persist_to=0, replicate_to=0):
"""Store an object in Couchbase unless it already exists.
Follows the same conventions as :meth:`upsert` but the value is
stored only if it does not exist already. Conversely, the value
is not stored if the ... | Store an object in Couchbase unless it already exists.
Follows the same conventions as :meth:`upsert` but the value is
stored only if it does not exist already. Conversely, the value
is not stored if the key already exists.
Notably missing from this method is the `cas` parameter, this ... |
def cluster(self, method, **kwargs):
"""
Cluster the tribe.
Cluster templates within a tribe: returns multiple tribes each of
which could be stacked.
:type method: str
:param method:
Method of stacking, see :mod:`eqcorrscan.utils.clustering`
:return... | Cluster the tribe.
Cluster templates within a tribe: returns multiple tribes each of
which could be stacked.
:type method: str
:param method:
Method of stacking, see :mod:`eqcorrscan.utils.clustering`
:return: List of tribes.
.. rubric:: Example |
def get_box_files(self, box_key):
'''Gets to file infos in a single box.
Args:
box_key key for the file
return (status code, list of file info dicts)
'''
uri = '/'.join([self.api_uri,
self.boxes_suffix,
box_key,
self.files_suffix
])
return self._req('get', uri) | Gets to file infos in a single box.
Args:
box_key key for the file
return (status code, list of file info dicts) |
def get_reply_visibility(self, status_dict):
"""Given a status dict, return the visibility that should be used.
This behaves like Mastodon does by default.
"""
# Visibility rankings (higher is more limited)
visibility = ("public", "unlisted", "private", "direct")
default... | Given a status dict, return the visibility that should be used.
This behaves like Mastodon does by default. |
def has_args():
''' returns true if the decorator invocation
had arguments passed to it before being
sent a function to decorate '''
no_args_syntax = '@overload'
args_syntax = no_args_syntax + '('
args, no_args = [(-1,-1)], [(-1,-1)]
for i, line in enumera... | returns true if the decorator invocation
had arguments passed to it before being
sent a function to decorate |
def getoptS(X, Y, M_E, E):
''' Find Sopt given X, Y
'''
n, r = X.shape
C = np.dot(np.dot(X.T, M_E), Y)
C = C.flatten()
A = np.zeros((r * r, r * r))
for i in range(r):
for j in range(r):
ind = j * r + i
temp = np.dot(
np.dot(X.T, np... | Find Sopt given X, Y |
def clear_plot(self):
"""Clear plot display."""
self.tab_plot.clear()
self.tab_plot.draw()
self.save_plot.set_enabled(False) | Clear plot display. |
def get_score(self, fmap='', importance_type='weight'):
"""Get feature importance of each feature.
Importance type can be defined as:
* 'weight': the number of times a feature is used to split the data across all trees.
* 'gain': the average gain across all splits the feature is used in... | Get feature importance of each feature.
Importance type can be defined as:
* 'weight': the number of times a feature is used to split the data across all trees.
* 'gain': the average gain across all splits the feature is used in.
* 'cover': the average coverage across all splits the fea... |
def power_down(self):
"""
turn off the HX711
:return: always True
:rtype bool
"""
GPIO.output(self._pd_sck, False)
GPIO.output(self._pd_sck, True)
time.sleep(0.01)
return True | turn off the HX711
:return: always True
:rtype bool |
def qop(self):
"""Indicates what "quality of protection" the client has applied to
the message for HTTP digest auth."""
def on_update(header_set):
if not header_set and 'qop' in self:
del self['qop']
elif header_set:
self['qop'] = header_se... | Indicates what "quality of protection" the client has applied to
the message for HTTP digest auth. |
def kmer_counter(seq, k=4):
"""Return a sequence of all the unique substrings (k-mer or q-gram) within a short (<128 symbol) string
Used for algorithms like UniqTag for genome unique identifier locality sensitive hashing.
jellyfish is a C implementation of k-mer counting
If seq is a string generate a... | Return a sequence of all the unique substrings (k-mer or q-gram) within a short (<128 symbol) string
Used for algorithms like UniqTag for genome unique identifier locality sensitive hashing.
jellyfish is a C implementation of k-mer counting
If seq is a string generate a sequence of k-mer string
If se... |
def _allocate_address(self, instance, network_ids):
"""
Allocates a floating/public ip address to the given instance.
:param instance: instance to assign address to
:param list network_id: List of IDs (as strings) of networks where to
request allocation the floating IP.
... | Allocates a floating/public ip address to the given instance.
:param instance: instance to assign address to
:param list network_id: List of IDs (as strings) of networks where to
request allocation the floating IP.
:return: public ip address |
def DeleteDatabase(self, database_link, options=None):
"""Deletes a database.
:param str database_link:
The link to the database.
:param dict options:
The request options for the request.
:return:
The deleted Database.
:rtype:
dic... | Deletes a database.
:param str database_link:
The link to the database.
:param dict options:
The request options for the request.
:return:
The deleted Database.
:rtype:
dict |
def get_masters(ppgraph):
"""From a protein-peptide graph dictionary (keys proteins,
values peptides), return master proteins aka those which
have no proteins whose peptides are supersets of them.
If shared master proteins are found, report only the first,
we will sort the whole proteingroup later a... | From a protein-peptide graph dictionary (keys proteins,
values peptides), return master proteins aka those which
have no proteins whose peptides are supersets of them.
If shared master proteins are found, report only the first,
we will sort the whole proteingroup later anyway. In that
case, the mast... |
def construct_codons_dict(alphabet_file = None):
"""Generate the sub_codons_right dictionary of codon suffixes.
syntax of custom alphabet_files:
char: list,of,amino,acids,or,codons,separated,by,commas
Parameters
----------
alphabet_file : str
File name for a custom al... | Generate the sub_codons_right dictionary of codon suffixes.
syntax of custom alphabet_files:
char: list,of,amino,acids,or,codons,separated,by,commas
Parameters
----------
alphabet_file : str
File name for a custom alphabet definition. If no file is provided, the
... |
def singleton(*args, **kwargs):
'''
a lazy init singleton pattern.
usage:
``` py
@singleton()
class X: ...
```
`args` and `kwargs` will pass to ctor of `X` as args.
'''
def decorator(cls: type) -> Callable[[], object]:
if issubclass(type(cls), _SingletonMetaClassBase)... | a lazy init singleton pattern.
usage:
``` py
@singleton()
class X: ...
```
`args` and `kwargs` will pass to ctor of `X` as args. |
def get_icloud_folder_location():
"""
Try to locate the iCloud Drive folder.
Returns:
(str) Full path to the iCloud Drive folder.
"""
yosemite_icloud_path = '~/Library/Mobile Documents/com~apple~CloudDocs/'
icloud_home = os.path.expanduser(yosemite_icloud_path)
if not os.path.isdi... | Try to locate the iCloud Drive folder.
Returns:
(str) Full path to the iCloud Drive folder. |
def unassigned(data, as_json=False):
""" https://sendgrid.com/docs/API_Reference/api_v3.html#ip-addresses
The /ips rest endpoint returns information about the IP addresses
and the usernames assigned to an IP
unassigned returns a listing of the IP addresses that are allocated
but hav... | https://sendgrid.com/docs/API_Reference/api_v3.html#ip-addresses
The /ips rest endpoint returns information about the IP addresses
and the usernames assigned to an IP
unassigned returns a listing of the IP addresses that are allocated
but have 0 users assigned
data (response.b... |
def count_objects_by_tags(self, metric, scraper_config):
""" Count objects by whitelisted tags and submit counts as gauges. """
config = self.object_count_params[metric.name]
metric_name = "{}.{}".format(scraper_config['namespace'], config['metric_name'])
object_counter = Counter()
... | Count objects by whitelisted tags and submit counts as gauges. |
def _set_copy(self, v, load=False):
"""
Setter method for copy, mapped from YANG variable /copy (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_copy is considered as a private
method. Backends looking to populate this variable should
do so via calling... | Setter method for copy, mapped from YANG variable /copy (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_copy is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_copy() directly. |
def has_subdirectories(path, include, exclude, show_all):
"""Return True if path has subdirectories"""
try:
# > 1 because of '..'
return len( listdir(path, include, exclude,
show_all, folders_only=True) ) > 1
except (IOError, OSError):
return False | Return True if path has subdirectories |
def rvs(self, size=1, param=None):
"""Gives a set of random values drawn from this distribution.
Parameters
----------
size : {1, int}
The number of values to generate; default is 1.
param : {None, string}
If provided, will just return values for the give... | Gives a set of random values drawn from this distribution.
Parameters
----------
size : {1, int}
The number of values to generate; default is 1.
param : {None, string}
If provided, will just return values for the given parameter.
Otherwise, returns ra... |
def gifs_categories_category_get(self, api_key, category, **kwargs):
"""
Category Tags Endpoint.
Returns a list of tags for a given category. NOTE `limit` and `offset` must both be set; otherwise they're ignored.
This method makes a synchronous HTTP request by default. To make an
... | Category Tags Endpoint.
Returns a list of tags for a given category. NOTE `limit` and `offset` must both be set; otherwise they're ignored.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked whe... |
def get_hash(self):
"""Generate and return the dict index hash of the given queue item.
Note:
Cookies should not be included in the hash calculation because
otherwise requests are crawled multiple times with e.g. different
session keys, causing infinite crawling recu... | Generate and return the dict index hash of the given queue item.
Note:
Cookies should not be included in the hash calculation because
otherwise requests are crawled multiple times with e.g. different
session keys, causing infinite crawling recursion.
Note:
... |
def page_strip(page, versioned):
"""Remove bits in content results to minimize memory utilization.
TODO: evolve this to a key filter on metadata, like date
"""
# page strip filtering should be conditional
page.pop('ResponseMetadata', None)
contents_key = versioned and 'Versions' or 'Contents'
... | Remove bits in content results to minimize memory utilization.
TODO: evolve this to a key filter on metadata, like date |
def _wrapinstance(ptr, base=None):
"""Enable implicit cast of pointer to most suitable class
This behaviour is available in sip per default.
Based on http://nathanhorne.com/pyqtpyside-wrap-instance
Usage:
This mechanism kicks in under these circumstances.
1. Qt.py is using PySide 1 or... | Enable implicit cast of pointer to most suitable class
This behaviour is available in sip per default.
Based on http://nathanhorne.com/pyqtpyside-wrap-instance
Usage:
This mechanism kicks in under these circumstances.
1. Qt.py is using PySide 1 or 2.
2. A `base` argument is not pr... |
def _init_client():
'''Setup client and init datastore.
'''
global client, path_prefix
if client is not None:
return
etcd_kwargs = {
'host': __opts__.get('etcd.host', '127.0.0.1'),
'port': __opts__.get('etcd.port', 2379),
'protocol': __opts__.get('etcd.pr... | Setup client and init datastore. |
def logtrick_minimizer(minimizer):
r"""
Log-Trick decorator for optimizers.
This decorator implements the "log trick" for optimizing positive bounded
variables. It will apply this trick for any variables that correspond to a
Positive() bound.
Examples
--------
>>> from scipy.optimize i... | r"""
Log-Trick decorator for optimizers.
This decorator implements the "log trick" for optimizing positive bounded
variables. It will apply this trick for any variables that correspond to a
Positive() bound.
Examples
--------
>>> from scipy.optimize import minimize as sp_min
>>> from .... |
def get_path(self):
"""
Returns a temporary file path based on a MD5 hash generated with the task's name and its arguments
"""
md5_hash = hashlib.md5(self.task_id.encode()).hexdigest()
logger.debug('Hash %s corresponds to task %s', md5_hash, self.task_id)
return os.path.... | Returns a temporary file path based on a MD5 hash generated with the task's name and its arguments |
def diri(table):
"""
from SparCC - "randomly draw from the corresponding posterior
Dirichlet distribution with a uniform prior"
"""
t = []
for i in table:
a = [j + 1 for j in i]
t.append(np.ndarray.tolist(np.random.mtrand.dirichlet(a)))
return t | from SparCC - "randomly draw from the corresponding posterior
Dirichlet distribution with a uniform prior" |
def _Build(self, storage_file):
"""Builds the event tag index.
Args:
storage_file (BaseStorageFile): storage file.
"""
self._index = {}
for event_tag in storage_file.GetEventTags():
self.SetEventTag(event_tag) | Builds the event tag index.
Args:
storage_file (BaseStorageFile): storage file. |
def process_tls(self, data, name):
"""
Remote TLS processing - one address:port per line
:param data:
:param name:
:return:
"""
ret = []
try:
lines = [x.strip() for x in data.split('\n')]
for idx, line in enumerate(lines):
... | Remote TLS processing - one address:port per line
:param data:
:param name:
:return: |
def get_sdk_dir(self):
"""Return the MSSSDK given the version string."""
try:
return self._sdk_dir
except AttributeError:
sdk_dir = self.find_sdk_dir()
self._sdk_dir = sdk_dir
return sdk_dir | Return the MSSSDK given the version string. |
def fetch(bank, key):
'''
Fetch a key value.
'''
c_key = '{0}/{1}'.format(bank, key)
try:
_, value = api.kv.get(c_key)
if value is None:
return {}
return __context__['serial'].loads(value['Value'])
except Exception as exc:
raise SaltCacheError(
... | Fetch a key value. |
def pluralize(data_type):
"""
adds s to the data type or the correct english plural form
"""
known = {
u"address": u"addresses",
u"company": u"companies"
}
if data_type in known.keys():
return known[data_type]
else:
return u"%ss" % data_type | adds s to the data type or the correct english plural form |
def __get_pid_by_scanning(self):
'Internally used by get_pid().'
dwProcessId = None
dwThreadId = self.get_tid()
with win32.CreateToolhelp32Snapshot(win32.TH32CS_SNAPTHREAD) as hSnapshot:
te = win32.Thread32First(hSnapshot)
while te is not None:
if ... | Internally used by get_pid(). |
def create_app(config_name):
""" Factory Function """
app = Flask(__name__)
app.config.from_object(CONFIG[config_name])
BOOTSTRAP.init_app(app)
# call controllers
from flask_seguro.controllers.main import main as main_blueprint
app.register_blueprint(main_blueprint)
return app | Factory Function |
async def promote_chat_member(self, chat_id: typing.Union[base.Integer, base.String],
user_id: base.Integer,
can_change_info: typing.Union[base.Boolean, None] = None,
can_post_messages: typing.Union[base.Boolean, None]... | Use this method to promote or demote a user in a supergroup or a channel.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Pass False for all boolean parameters to demote a user.
Source: https://core.telegram.org/bots/api#promotechatmembe... |
def copy(
ctx,
opts,
owner_repo_package,
destination,
skip_errors,
wait_interval,
no_wait_for_sync,
sync_attempts,
):
"""
Copy a package to another repository.
This requires appropriate permissions for both the source
repository/package and the destination repository.
... | Copy a package to another repository.
This requires appropriate permissions for both the source
repository/package and the destination repository.
- OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the
REPO name where the package is stored, and the PACKAGE name (slug) of the
pac... |
def _has_fileno(stream):
"""Returns whether the stream object seems to have a working fileno()
Tells whether _redirect_stderr is likely to work.
Parameters
----------
stream : IO stream object
Returns
-------
has_fileno : bool
True if stream.fileno() exists and doesn't raise O... | Returns whether the stream object seems to have a working fileno()
Tells whether _redirect_stderr is likely to work.
Parameters
----------
stream : IO stream object
Returns
-------
has_fileno : bool
True if stream.fileno() exists and doesn't raise OSError or
UnsupportedOpe... |
def log_interp1d(self, xx, yy, kind='linear'):
"""
Performs a log space 1d interpolation.
:param xx: the x values.
:param yy: the y values.
:param kind: the type of interpolation to apply (as per scipy interp1d)
:return: the interpolation function.
"""
log... | Performs a log space 1d interpolation.
:param xx: the x values.
:param yy: the y values.
:param kind: the type of interpolation to apply (as per scipy interp1d)
:return: the interpolation function. |
def protocol_version_to_kmip_version(value):
"""
Convert a ProtocolVersion struct to its KMIPVersion enumeration equivalent.
Args:
value (ProtocolVersion): A ProtocolVersion struct to be converted into
a KMIPVersion enumeration.
Returns:
KMIPVersion: The enumeration equival... | Convert a ProtocolVersion struct to its KMIPVersion enumeration equivalent.
Args:
value (ProtocolVersion): A ProtocolVersion struct to be converted into
a KMIPVersion enumeration.
Returns:
KMIPVersion: The enumeration equivalent of the struct. If the struct
cannot be co... |
def plot_element_profile(self, element, comp, show_label_index=None,
xlim=5):
"""
Draw the element profile plot for a composition varying different
chemical potential of an element.
X value is the negative value of the chemical potential reference to
... | Draw the element profile plot for a composition varying different
chemical potential of an element.
X value is the negative value of the chemical potential reference to
elemental chemical potential. For example, if choose Element("Li"),
X= -(µLi-µLi0), which corresponds to the voltage ve... |
def create_presentation(self):
""" Create the presentation.
The audio track is mixed with the slides. The resulting file is saved as self.output
DownloadError is raised if some resources cannot be fetched.
ConversionError is raised if the final video cannot be created.
"""
... | Create the presentation.
The audio track is mixed with the slides. The resulting file is saved as self.output
DownloadError is raised if some resources cannot be fetched.
ConversionError is raised if the final video cannot be created. |
async def getStickerSet(self, name):
"""
See: https://core.telegram.org/bots/api#getstickerset
"""
p = _strip(locals())
return await self._api_request('getStickerSet', _rectify(p)) | See: https://core.telegram.org/bots/api#getstickerset |
def fromDatetime(klass, dtime):
"""Return a new Time instance from a datetime.datetime instance.
If the datetime instance does not have an associated timezone, it is
assumed to be UTC.
"""
self = klass.__new__(klass)
if dtime.tzinfo is not None:
self._time = ... | Return a new Time instance from a datetime.datetime instance.
If the datetime instance does not have an associated timezone, it is
assumed to be UTC. |
def fit(self, Z, **fit_params):
"""Fit all the transforms one after the other and transform the
data, then fit the transformed data using the final estimator.
Parameters
----------
Z : ArrayRDD, TupleRDD or DictRDD
Input data in blocked distributed format.
R... | Fit all the transforms one after the other and transform the
data, then fit the transformed data using the final estimator.
Parameters
----------
Z : ArrayRDD, TupleRDD or DictRDD
Input data in blocked distributed format.
Returns
-------
self : Spark... |
def request(self, method, url, params=None, **aio_kwargs):
"""Make a request to provider."""
oparams = {
'oauth_consumer_key': self.consumer_key,
'oauth_nonce': sha1(str(RANDOM()).encode('ascii')).hexdigest(),
'oauth_signature_method': self.signature.name,
... | Make a request to provider. |
def heading_title(self):
"""
Makes the Article Title for the Heading.
Metadata element, content derived from FrontMatter
"""
art_title = self.article.root.xpath('./front/article-meta/title-group/article-title')[0]
article_title = deepcopy(art_title)
article_title... | Makes the Article Title for the Heading.
Metadata element, content derived from FrontMatter |
def create_new_dispatch(self, dispatch):
"""
Create a new dispatch
:param dispatch:
is the new dispatch that the client wants to create
"""
self._validate_uuid(dispatch.dispatch_id)
# Create new dispatch
url = "/notification/v1/dispatch"
post_resp... | Create a new dispatch
:param dispatch:
is the new dispatch that the client wants to create |
def _get_function_name(self, fn, default="None"):
""" Return name of function, using default value if function not defined
"""
if fn is None:
fn_name = default
else:
fn_name = fn.__name__
return fn_name | Return name of function, using default value if function not defined |
def _get_ssh_client(self):
"""Return a new or existing SSH client for given ip."""
return ipa_utils.get_ssh_client(
self.instance_ip,
self.ssh_private_key_file,
self.ssh_user,
timeout=self.timeout
) | Return a new or existing SSH client for given ip. |
def default(self, request, exception):
"""
Provide a default behavior for the objects of :class:`ErrorHandler`.
If a developer chooses to extent the :class:`ErrorHandler` they can
provide a custom implementation for this method to behave in a way
they see fit.
:param req... | Provide a default behavior for the objects of :class:`ErrorHandler`.
If a developer chooses to extent the :class:`ErrorHandler` they can
provide a custom implementation for this method to behave in a way
they see fit.
:param request: Incoming request
:param exception: Exception ... |
def _nth_of_quarter(self, nth, day_of_week):
"""
Modify to the given occurrence of a given day of the week
in the current quarter. If the calculated occurrence is outside,
the scope of the current quarter, then return False and no
modifications are made. Use the supplied consts
... | Modify to the given occurrence of a given day of the week
in the current quarter. If the calculated occurrence is outside,
the scope of the current quarter, then return False and no
modifications are made. Use the supplied consts
to indicate the desired day_of_week, ex. pendulum.MONDAY.
... |
def add(self, element, multiplicity=1):
"""Adds an element to the multiset.
>>> ms = Multiset()
>>> ms.add('a')
>>> sorted(ms)
['a']
An optional multiplicity can be specified to define how many of the element are added:
>>> ms.add('b', 2)
>>> sorted(ms)... | Adds an element to the multiset.
>>> ms = Multiset()
>>> ms.add('a')
>>> sorted(ms)
['a']
An optional multiplicity can be specified to define how many of the element are added:
>>> ms.add('b', 2)
>>> sorted(ms)
['a', 'b', 'b']
This extends the ... |
def _unpack_basis_label_or_index(self, label_or_index):
"""return tuple (label, ind) from `label_or_index`
If `label_or_int` is a :class:`.SymbolicLabelBase` sub-instance, it
will be stored in the `label` attribute, and the `ind` attribute will
return the value of the label's :attr:`.Fo... | return tuple (label, ind) from `label_or_index`
If `label_or_int` is a :class:`.SymbolicLabelBase` sub-instance, it
will be stored in the `label` attribute, and the `ind` attribute will
return the value of the label's :attr:`.FockIndex.fock_index`
attribute. No checks are performed for... |
def p_primary_expr_no_brace_4(self, p):
"""primary_expr_no_brace : LPAREN expr RPAREN"""
if isinstance(p[2], self.asttypes.GroupingOp):
# this reduces the grouping operator to one.
p[0] = p[2]
else:
p[0] = self.asttypes.GroupingOp(expr=p[2])
p[0].s... | primary_expr_no_brace : LPAREN expr RPAREN |
def get_accent_string(string):
"""
Get the first accent from the right of a string.
"""
accents = list(filter(lambda accent: accent != Accent.NONE,
map(get_accent_char, string)))
return accents[-1] if accents else Accent.NONE | Get the first accent from the right of a string. |
def is_modified(self):
"""
Returns whether model is modified or not
"""
if len(self.__modified_data__) or len(self.__deleted_fields__):
return True
for value in self.__original_data__.values():
try:
if value.is_modified():
... | Returns whether model is modified or not |
def ajax_preview(request, **kwargs):
"""
Currently only supports markdown
"""
data = {
"html": render_to_string("pinax/blog/_preview.html", {
"content": parse(request.POST.get("markup"))
})
}
return JsonResponse(data) | Currently only supports markdown |
def from_array(self, coeffs, r0, errors=None, normalization='schmidt',
csphase=1, lmax=None, copy=True):
"""
Initialize the class with spherical harmonic coefficients from an input
array.
Usage
-----
x = SHMagCoeffs.from_array(array, r0, [errors, norma... | Initialize the class with spherical harmonic coefficients from an input
array.
Usage
-----
x = SHMagCoeffs.from_array(array, r0, [errors, normalization, csphase,
lmax, copy])
Returns
-------
x : SHMagCoeffs class in... |
def is_complete(self):
"""Do all required parameters have values?"""
return all(p.name in self.values for p in self.parameters if p.required) | Do all required parameters have values? |
def get_assessment_part_item_session(self, *args, **kwargs):
"""Gets the ``OsidSession`` associated with the assessment part item service.
return: (osid.assessment.authoring.AssessmentPartItemSession)
- an ``AssessmentPartItemSession``
raise: OperationFailed - unable to complet... | Gets the ``OsidSession`` associated with the assessment part item service.
return: (osid.assessment.authoring.AssessmentPartItemSession)
- an ``AssessmentPartItemSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_assessment_part_ite... |
def create_list_stories(
list_id_stories, number_of_stories, shuffle, max_threads
):
"""Show in a formatted way the stories for each item of the list."""
list_stories = []
with ThreadPoolExecutor(max_workers=max_threads) as executor:
futures = {
executor.submit(get_story, new)
... | Show in a formatted way the stories for each item of the list. |
def GetAll(alias=None,location=None,session=None):
"""Gets a list of anti-affinity policies within a given account.
https://t3n.zendesk.com/entries/44657214-Get-Anti-Affinity-Policies
>>> clc.v2.AntiAffinity.GetAll()
[<clc.APIv2.anti_affinity.AntiAffinity object at 0x10c65e910>, <clc.APIv2.anti_affinity.AntiA... | Gets a list of anti-affinity policies within a given account.
https://t3n.zendesk.com/entries/44657214-Get-Anti-Affinity-Policies
>>> clc.v2.AntiAffinity.GetAll()
[<clc.APIv2.anti_affinity.AntiAffinity object at 0x10c65e910>, <clc.APIv2.anti_affinity.AntiAffinity object at 0x10c65ec90>] |
def conversations_replies(self, *, channel: str, ts: str, **kwargs) -> SlackResponse:
"""Retrieve a thread of messages posted to a conversation
Args:
channel (str): Conversation ID to fetch thread from. e.g. 'C1234567890'
ts (str): Unique identifier of a thread's parent message.... | Retrieve a thread of messages posted to a conversation
Args:
channel (str): Conversation ID to fetch thread from. e.g. 'C1234567890'
ts (str): Unique identifier of a thread's parent message. e.g. '1234567890.123456' |
def _find_value(key, *args):
"""Find a value for 'key' in any of the objects given as 'args'"""
for arg in args:
v = _get_value(arg, key)
if v is not None:
return v | Find a value for 'key' in any of the objects given as 'args |
def initialize(self):
"""Create the laboratory directories."""
mkdir_p(self.archive_path)
mkdir_p(self.bin_path)
mkdir_p(self.codebase_path)
mkdir_p(self.input_basepath) | Create the laboratory directories. |
def propose_value(self, value):
'''
Sets the proposal value for this node iff this node is not already aware of
a previous proposal value. If the node additionally believes itself to be
the current leader, an Accept message will be returned
'''
if self.proposed_value is N... | Sets the proposal value for this node iff this node is not already aware of
a previous proposal value. If the node additionally believes itself to be
the current leader, an Accept message will be returned |
def handle_exc(exc):
""" Given a database exception determine how to fail
Attempt to lookup a known error & abort on a meaningful
error. Otherwise issue a generic DatabaseUnavailable exception.
:param exc: psycopg2 exception
"""
err = ERRORS_TABLE.get(exc.pgcode)
if err:
abort(ex... | Given a database exception determine how to fail
Attempt to lookup a known error & abort on a meaningful
error. Otherwise issue a generic DatabaseUnavailable exception.
:param exc: psycopg2 exception |
def is_unwrapped(f):
"""If `f` was imported and then unwrapped, this function might return True.
.. |is_unwrapped| replace:: :py:func:`is_unwrapped`"""
try:
g = look_up(object_name(f))
return g != f and unwrap(g) == f
except (AttributeError, TypeError, ImportError):
return Fals... | If `f` was imported and then unwrapped, this function might return True.
.. |is_unwrapped| replace:: :py:func:`is_unwrapped` |
def put_metadata(self, key, value, namespace='default'):
"""
Add metadata to the current active trace entity.
Metadata is not indexed but can be later retrieved
by BatchGetTraces API.
:param str namespace: optional. Default namespace is `default`.
It must be a string... | Add metadata to the current active trace entity.
Metadata is not indexed but can be later retrieved
by BatchGetTraces API.
:param str namespace: optional. Default namespace is `default`.
It must be a string and prefix `AWS.` is reserved.
:param str key: metadata key under sp... |
def to_json(self):
"""
Serialize object to json dict
:return: dict
"""
res = dict()
res['Count'] = self.count
res['Messages'] = self.messages
res['ForcedState'] = self.forced
res['ForcedKeyboard'] = self.keyboard
res['Entities'] = list()
... | Serialize object to json dict
:return: dict |
def page_url(self) -> str:
"""(:class:`str`) The canonical url of the page."""
url = self.attributes['canonicalurl']
assert isinstance(url, str)
return url | (:class:`str`) The canonical url of the page. |
def main():
""" Read the options given on the command line and do the required actions.
This method is used in the entry_point `cast`.
"""
opts = docopt(__doc__, version="cast 0.1")
cast = pychromecast.PyChromecast(CHROMECAST_HOST)
ramp = cast.get_protocol(pychromecast.PROTOCOL_RAMP)
# Wa... | Read the options given on the command line and do the required actions.
This method is used in the entry_point `cast`. |
def batch(self, timelimit=None):
"""
Run the flow in batch mode, return exit status of the job script.
Requires a manager.yml file and a batch_adapter adapter.
Args:
timelimit: Time limit (int with seconds or string with time given with the slurm convention:
"day... | Run the flow in batch mode, return exit status of the job script.
Requires a manager.yml file and a batch_adapter adapter.
Args:
timelimit: Time limit (int with seconds or string with time given with the slurm convention:
"days-hours:minutes:seconds"). If timelimit is None, the ... |
def describe_change_set(awsclient, change_set_name, stack_name):
"""Print out the change_set to console.
This needs to run create_change_set first.
:param awsclient:
:param change_set_name:
:param stack_name:
"""
client = awsclient.get_client('cloudformation')
status = None
while s... | Print out the change_set to console.
This needs to run create_change_set first.
:param awsclient:
:param change_set_name:
:param stack_name: |
def rpc_get_usages(self, filename, source, offset):
"""Return the uses of the symbol at offset.
Returns a list of occurrences of the symbol, as dicts with the
fields name, filename, and offset.
"""
line, column = pos_to_linecol(source, offset)
uses = run_with_debug(jedi... | Return the uses of the symbol at offset.
Returns a list of occurrences of the symbol, as dicts with the
fields name, filename, and offset. |
def birch(args):
"""
%prog birch seqids layout
Plot birch macro-synteny, with an embedded phylogenetic tree to the right.
"""
p = OptionParser(birch.__doc__)
opts, args, iopts = p.set_image_options(args, figsize="8x6")
if len(args) != 2:
sys.exit(not p.print_help())
seqids, la... | %prog birch seqids layout
Plot birch macro-synteny, with an embedded phylogenetic tree to the right. |
def p_DictionaryMember(p):
"""DictionaryMember : Type IDENTIFIER Default ";"
"""
p[0] = model.DictionaryMember(type=p[1], name=p[2], default=p[3]) | DictionaryMember : Type IDENTIFIER Default ";" |
def url(self):
"""Return the admin url of the object."""
return urlresolvers.reverse(
"admin:%s_%s_change" % (self.content_type.app_label,
self.content_type.model),
args = (self.get_object().uid,)) | Return the admin url of the object. |
def _reprJSON(self):
"""Returns a JSON serializable represenation of a ``MzmlPrecursor``
class instance. Use :func:`maspy.core.MzmlPrecursor._fromJSON()` to
generate a new ``MzmlPrecursor`` instance from the return value.
:returns: a JSON serializable python object
"""
r... | Returns a JSON serializable represenation of a ``MzmlPrecursor``
class instance. Use :func:`maspy.core.MzmlPrecursor._fromJSON()` to
generate a new ``MzmlPrecursor`` instance from the return value.
:returns: a JSON serializable python object |
def _fast_read(self, infile):
"""Function for fast reading from sensor files."""
infile.seek(0)
return(int(infile.read().decode().strip())) | Function for fast reading from sensor files. |
def load_directory(self, top_path, followlinks):
"""
Traverse top_path directory and save patterns in any .ddsignore files found.
:param top_path: str: directory name we should traverse looking for ignore files
:param followlinks: boolean: should we traverse symbolic links
"""
... | Traverse top_path directory and save patterns in any .ddsignore files found.
:param top_path: str: directory name we should traverse looking for ignore files
:param followlinks: boolean: should we traverse symbolic links |
def tokens2ids(tokens: Iterable[str], vocab: Dict[str, int]) -> List[int]:
"""
Returns sequence of integer ids given a sequence of tokens and vocab.
:param tokens: List of string tokens.
:param vocab: Vocabulary (containing UNK symbol).
:return: List of word ids.
"""
return [vocab.get(w, vo... | Returns sequence of integer ids given a sequence of tokens and vocab.
:param tokens: List of string tokens.
:param vocab: Vocabulary (containing UNK symbol).
:return: List of word ids. |
def run_npm(self):
""" h/t https://github.com/elbaschid/virtual-node/blob/master/setup.py """
for name, version in npm_dependencies.items():
# packages are installed globally to make sure that they are
# installed in the virtualenv rather than the current directory.
... | h/t https://github.com/elbaschid/virtual-node/blob/master/setup.py |
def add_members(self, users=None, role=TeamRoles.MEMBER):
"""Members to add to a team.
:param members: list of members, either `User` objects or usernames
:type members: List of `User` or List of pk
:param role: (optional) role of the users to add (default `TeamRoles.MEMBER`)
:t... | Members to add to a team.
:param members: list of members, either `User` objects or usernames
:type members: List of `User` or List of pk
:param role: (optional) role of the users to add (default `TeamRoles.MEMBER`)
:type role: basestring
:raises IllegalArgumentError: when provi... |
def single_violation(self, column=None, value=None, **kwargs):
"""
A single event violation is a one-time event that occurred on a fixed
date, and is associated with one permitted facility.
>>> PCS().single_violation('single_event_viol_date', '16-MAR-01')
"""
return self... | A single event violation is a one-time event that occurred on a fixed
date, and is associated with one permitted facility.
>>> PCS().single_violation('single_event_viol_date', '16-MAR-01') |
def _add_genetic_models(self, variant_obj, info_dict):
"""Add the genetic models found
Args:
variant_obj (puzzle.models.Variant)
info_dict (dict): A info dictionary
"""
genetic_models_entry = info_dict.get('GeneticModels')
if genetic_mode... | Add the genetic models found
Args:
variant_obj (puzzle.models.Variant)
info_dict (dict): A info dictionary |
def _prep_acl_for_compare(ACL):
'''
Prepares the ACL returned from the AWS API for comparison with a given one.
'''
ret = copy.deepcopy(ACL)
ret['Owner'] = _normalize_user(ret['Owner'])
for item in ret.get('Grants', ()):
item['Grantee'] = _normalize_user(item.get('Grantee'))
return r... | Prepares the ACL returned from the AWS API for comparison with a given one. |
def handle(client_message, handle_event_imap_invalidation=None, handle_event_imap_batch_invalidation=None, to_object=None):
""" Event handler """
message_type = client_message.get_message_type()
if message_type == EVENT_IMAPINVALIDATION and handle_event_imap_invalidation is not None:
key = None
... | Event handler |
def apply_operation(self, symmop):
"""
Apply a symmetry operation to the molecule.
Args:
symmop (SymmOp): Symmetry operation to apply.
"""
def operate_site(site):
new_cart = symmop.operate(site.coords)
return Site(site.species, new_cart,
... | Apply a symmetry operation to the molecule.
Args:
symmop (SymmOp): Symmetry operation to apply. |
def handle_label_relation(self, line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Handle statements like ``p(X) label "Label for X"``.
:raises: RelabelWarning
"""
subject_node_dsl = self.ensure_node(tokens[SUBJECT])
description = tokens[OBJECT]
if self... | Handle statements like ``p(X) label "Label for X"``.
:raises: RelabelWarning |
def _validate_bag(self, bag, **kwargs):
"""
Validate BagIt (checksums, payload.oxum etc)
"""
failed = None
try:
bag.validate(**kwargs)
except BagValidationError as e:
failed = e
# for d in e.details:
# if isinstance(d,... | Validate BagIt (checksums, payload.oxum etc) |
def _process_added_port_event(self, port_name):
"""Callback for added ports."""
LOG.info("Hyper-V VM vNIC added: %s", port_name)
self._added_ports.add(port_name) | Callback for added ports. |
def parse_tweet(raw_tweet, source, now=None):
"""
Parses a single raw tweet line from a twtxt file
and returns a :class:`Tweet` object.
:param str raw_tweet: a single raw tweet line
:param Source source: the source of the given tweet
:param Datetime now: the current datetime... | Parses a single raw tweet line from a twtxt file
and returns a :class:`Tweet` object.
:param str raw_tweet: a single raw tweet line
:param Source source: the source of the given tweet
:param Datetime now: the current datetime
:returns: the parsed tweet
:rtype: Tweet |
def attention_lm_moe_large():
"""Large model for distributed training.
Over 1B parameters, so requires multi-gpu training due to memory
requirements.
on lm1b_32k:
After 45K steps on 8 GPUs (synchronous):
eval_log_ppl_per_token = 3.18
eval_ppl_per_word = exp(1.107893 * eval_log_ppl_per_to... | Large model for distributed training.
Over 1B parameters, so requires multi-gpu training due to memory
requirements.
on lm1b_32k:
After 45K steps on 8 GPUs (synchronous):
eval_log_ppl_per_token = 3.18
eval_ppl_per_word = exp(1.107893 * eval_log_ppl_per_token) = 33.9
Returns:
an hpar... |
def _get_app_version(self, app_config):
"""
Some plugins ship multiple applications and extensions.
However all of them have the same version, because they are released together.
That's why only-top level module is used to fetch version information.
"""
base_name = app_c... | Some plugins ship multiple applications and extensions.
However all of them have the same version, because they are released together.
That's why only-top level module is used to fetch version information. |
def get_portchannel_info_by_intf_output_lacp_actor_brcd_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_portchannel_info_by_intf = ET.Element("get_portchannel_info_by_intf")
config = get_portchannel_info_by_intf
output = ET.SubElement(g... | Auto Generated Code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.