code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def num_columns(self):
"""Number of columns displayed."""
if self.term.is_a_tty:
return self.term.width // self.hint_width
return 1 | def function[num_columns, parameter[self]]:
constant[Number of columns displayed.]
if name[self].term.is_a_tty begin[:]
return[binary_operation[name[self].term.width <ast.FloorDiv object at 0x7da2590d6bc0> name[self].hint_width]]
return[constant[1]] | keyword[def] identifier[num_columns] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[term] . identifier[is_a_tty] :
keyword[return] identifier[self] . identifier[term] . identifier[width] // identifier[self] . identifier[hint_width]
keyword[r... | def num_columns(self):
"""Number of columns displayed."""
if self.term.is_a_tty:
return self.term.width // self.hint_width # depends on [control=['if'], data=[]]
return 1 |
def __get_reserve_details(self, account_id, **kwargs):
"""Call documentation: `/account/get_reserve_details
<https://www.wepay.com/developer/reference/account#reserve>`_, plus extra
keyword parameters:
:keyword str access_token: will be used instead of instance's
``ac... | def function[__get_reserve_details, parameter[self, account_id]]:
constant[Call documentation: `/account/get_reserve_details
<https://www.wepay.com/developer/reference/account#reserve>`_, plus extra
keyword parameters:
:keyword str access_token: will be used instead of instance'... | keyword[def] identifier[__get_reserve_details] ( identifier[self] , identifier[account_id] ,** identifier[kwargs] ):
literal[string]
identifier[params] ={
literal[string] : identifier[account_id]
}
keyword[return] identifier[self] . identifier[make_call] ( identifier[sel... | def __get_reserve_details(self, account_id, **kwargs):
"""Call documentation: `/account/get_reserve_details
<https://www.wepay.com/developer/reference/account#reserve>`_, plus extra
keyword parameters:
:keyword str access_token: will be used instead of instance's
``access... |
def _dateversion(self):
# type: () -> int
"""Return the build/revision date as an integer "yyyymmdd"."""
import re
if self._head:
ma = re.search(r'(?<=\()(.*)(?=\))', self._head)
if ma:
s = re.split(r'[, ]+', ma.group(0))
if len(s) ... | def function[_dateversion, parameter[self]]:
constant[Return the build/revision date as an integer "yyyymmdd".]
import module[re]
if name[self]._head begin[:]
variable[ma] assign[=] call[name[re].search, parameter[constant[(?<=\()(.*)(?=\))], name[self]._head]]
if nam... | keyword[def] identifier[_dateversion] ( identifier[self] ):
literal[string]
keyword[import] identifier[re]
keyword[if] identifier[self] . identifier[_head] :
identifier[ma] = identifier[re] . identifier[search] ( literal[string] , identifier[self] . identifier[_head] )
... | def _dateversion(self):
# type: () -> int
'Return the build/revision date as an integer "yyyymmdd".'
import re
if self._head:
ma = re.search('(?<=\\()(.*)(?=\\))', self._head)
if ma:
s = re.split('[, ]+', ma.group(0))
if len(s) >= 3:
# month
... |
def apply_dict_default(dictionary, arg, default):
'''
Used to avoid generating a defaultdict object, or assigning defaults to a dict-like object
apply_dict_default({}, 'test', list)
# => {'test': []}
apply_dict_default({'test': 'ok'}, 'test', list)
# => {'test': 'ok'}
'''
if ... | def function[apply_dict_default, parameter[dictionary, arg, default]]:
constant[
Used to avoid generating a defaultdict object, or assigning defaults to a dict-like object
apply_dict_default({}, 'test', list)
# => {'test': []}
apply_dict_default({'test': 'ok'}, 'test', list)
# => {'test': ... | keyword[def] identifier[apply_dict_default] ( identifier[dictionary] , identifier[arg] , identifier[default] ):
literal[string]
keyword[if] identifier[arg] keyword[not] keyword[in] identifier[dictionary] :
keyword[if] identifier[hasattr] ( identifier[default] , literal[string] ):
... | def apply_dict_default(dictionary, arg, default):
"""
Used to avoid generating a defaultdict object, or assigning defaults to a dict-like object
apply_dict_default({}, 'test', list)
# => {'test': []}
apply_dict_default({'test': 'ok'}, 'test', list)
# => {'test': 'ok'}
"""
if arg not in... |
def print_info(self, obj=None, buf=sys.stdout):
"""Print a status message about the given object.
If an object is not provided, status info is shown about the current
environment - what the active context is if any, and what suites are
visible.
Args:
obj (str): Stri... | def function[print_info, parameter[self, obj, buf]]:
constant[Print a status message about the given object.
If an object is not provided, status info is shown about the current
environment - what the active context is if any, and what suites are
visible.
Args:
obj ... | keyword[def] identifier[print_info] ( identifier[self] , identifier[obj] = keyword[None] , identifier[buf] = identifier[sys] . identifier[stdout] ):
literal[string]
keyword[if] keyword[not] identifier[obj] :
identifier[self] . identifier[_print_info] ( identifier[buf] )
... | def print_info(self, obj=None, buf=sys.stdout):
"""Print a status message about the given object.
If an object is not provided, status info is shown about the current
environment - what the active context is if any, and what suites are
visible.
Args:
obj (str): String w... |
def get_file_location(self, pathformat=None):
"""Returns a tuple with the location of the file in the form
``(server, location)``. If the netloc is empty in the URL or
points to localhost, it's represented as ``None``.
The `pathformat` by default is autodetection but needs to be set
... | def function[get_file_location, parameter[self, pathformat]]:
constant[Returns a tuple with the location of the file in the form
``(server, location)``. If the netloc is empty in the URL or
points to localhost, it's represented as ``None``.
The `pathformat` by default is autodetection ... | keyword[def] identifier[get_file_location] ( identifier[self] , identifier[pathformat] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[scheme] != literal[string] :
keyword[return] keyword[None] , keyword[None]
identifier[path] = identifier[url_... | def get_file_location(self, pathformat=None):
"""Returns a tuple with the location of the file in the form
``(server, location)``. If the netloc is empty in the URL or
points to localhost, it's represented as ``None``.
The `pathformat` by default is autodetection but needs to be set
... |
async def disable_analog_reporting(self, pin):
"""
Disables analog reporting for a single analog pin.
:param pin: Analog pin number. For example for A0, the number is 0.
:returns: No return value
"""
command = [PrivateConstants.REPORT_ANALOG + pin,
Pr... | <ast.AsyncFunctionDef object at 0x7da20c76e950> | keyword[async] keyword[def] identifier[disable_analog_reporting] ( identifier[self] , identifier[pin] ):
literal[string]
identifier[command] =[ identifier[PrivateConstants] . identifier[REPORT_ANALOG] + identifier[pin] ,
identifier[PrivateConstants] . identifier[REPORTING_DISABLE] ]
... | async def disable_analog_reporting(self, pin):
"""
Disables analog reporting for a single analog pin.
:param pin: Analog pin number. For example for A0, the number is 0.
:returns: No return value
"""
command = [PrivateConstants.REPORT_ANALOG + pin, PrivateConstants.REPORTING_DI... |
def generate(env, version=None, abi=None, topdir=None, verbose=0):
"""Add Builders and construction variables for Intel C/C++ compiler
to an Environment.
args:
version: (string) compiler version to use, like "80"
abi: (string) 'win32' or whatever Itanium version wants
topdir: (string)... | def function[generate, parameter[env, version, abi, topdir, verbose]]:
constant[Add Builders and construction variables for Intel C/C++ compiler
to an Environment.
args:
version: (string) compiler version to use, like "80"
abi: (string) 'win32' or whatever Itanium version wants
top... | keyword[def] identifier[generate] ( identifier[env] , identifier[version] = keyword[None] , identifier[abi] = keyword[None] , identifier[topdir] = keyword[None] , identifier[verbose] = literal[int] ):
literal[string]
keyword[if] keyword[not] ( identifier[is_mac] keyword[or] identifier[is_linux] keyword... | def generate(env, version=None, abi=None, topdir=None, verbose=0):
"""Add Builders and construction variables for Intel C/C++ compiler
to an Environment.
args:
version: (string) compiler version to use, like "80"
abi: (string) 'win32' or whatever Itanium version wants
topdir: (string)... |
def from_json(cls, data):
"""Create a DDY from a dictionary.
Args:
data = {
"location": ladybug Location schema,
"design_days": [] // list of ladybug DesignDay schemas}
"""
required_keys = ('location', 'design_days')
for key in required_keys:
... | def function[from_json, parameter[cls, data]]:
constant[Create a DDY from a dictionary.
Args:
data = {
"location": ladybug Location schema,
"design_days": [] // list of ladybug DesignDay schemas}
]
variable[required_keys] assign[=] tuple[[<ast.Constan... | keyword[def] identifier[from_json] ( identifier[cls] , identifier[data] ):
literal[string]
identifier[required_keys] =( literal[string] , literal[string] )
keyword[for] identifier[key] keyword[in] identifier[required_keys] :
keyword[assert] identifier[key] keyword[in] id... | def from_json(cls, data):
"""Create a DDY from a dictionary.
Args:
data = {
"location": ladybug Location schema,
"design_days": [] // list of ladybug DesignDay schemas}
"""
required_keys = ('location', 'design_days')
for key in required_keys:
asse... |
def subfield_get(self, obj, type=None):
"""
Verbatim copy from:
https://github.com/django/django/blob/1.9.13/django/db/models/fields/subclassing.py#L38
"""
if obj is None:
return self
return obj.__dict__[self.field.name] | def function[subfield_get, parameter[self, obj, type]]:
constant[
Verbatim copy from:
https://github.com/django/django/blob/1.9.13/django/db/models/fields/subclassing.py#L38
]
if compare[name[obj] is constant[None]] begin[:]
return[name[self]]
return[call[name[obj].__dict__][name... | keyword[def] identifier[subfield_get] ( identifier[self] , identifier[obj] , identifier[type] = keyword[None] ):
literal[string]
keyword[if] identifier[obj] keyword[is] keyword[None] :
keyword[return] identifier[self]
keyword[return] identifier[obj] . identifier[__dict__] [ identifier[s... | def subfield_get(self, obj, type=None):
"""
Verbatim copy from:
https://github.com/django/django/blob/1.9.13/django/db/models/fields/subclassing.py#L38
"""
if obj is None:
return self # depends on [control=['if'], data=[]]
return obj.__dict__[self.field.name] |
def execute(self):
"""Start this action command in a subprocess.
:raise: ActionError
'toomanyopenfiles' if too many opened files on the system
'no_process_launched' if arguments parsing failed
'process_launch_failed': if the process launch failed
:return: re... | def function[execute, parameter[self]]:
constant[Start this action command in a subprocess.
:raise: ActionError
'toomanyopenfiles' if too many opened files on the system
'no_process_launched' if arguments parsing failed
'process_launch_failed': if the process launch ... | keyword[def] identifier[execute] ( identifier[self] ):
literal[string]
identifier[self] . identifier[status] = identifier[ACT_STATUS_LAUNCHED]
identifier[self] . identifier[check_time] = identifier[time] . identifier[time] ()
identifier[self] . identifier[wait_time] = literal[int... | def execute(self):
"""Start this action command in a subprocess.
:raise: ActionError
'toomanyopenfiles' if too many opened files on the system
'no_process_launched' if arguments parsing failed
'process_launch_failed': if the process launch failed
:return: refere... |
def _determine_default_project(project=None):
"""Determine default project explicitly or implicitly as fall-back.
In implicit case, supports four environments. In order of precedence, the
implicit environments are:
* DATASTORE_DATASET environment variable (for ``gcd`` / emulator testing)
* GOOGLE_... | def function[_determine_default_project, parameter[project]]:
constant[Determine default project explicitly or implicitly as fall-back.
In implicit case, supports four environments. In order of precedence, the
implicit environments are:
* DATASTORE_DATASET environment variable (for ``gcd`` / emula... | keyword[def] identifier[_determine_default_project] ( identifier[project] = keyword[None] ):
literal[string]
keyword[if] identifier[project] keyword[is] keyword[None] :
identifier[project] = identifier[_get_gcd_project] ()
keyword[if] identifier[project] keyword[is] keyword[None] :
... | def _determine_default_project(project=None):
"""Determine default project explicitly or implicitly as fall-back.
In implicit case, supports four environments. In order of precedence, the
implicit environments are:
* DATASTORE_DATASET environment variable (for ``gcd`` / emulator testing)
* GOOGLE_... |
async def set(self, full, valu):
'''
A set operation at the hive level (full path).
'''
node = await self._getHiveNode(full)
oldv = node.valu
node.valu = await self.storNodeValu(full, valu)
await node.fire('hive:set', path=full, valu=valu, oldv=oldv)
r... | <ast.AsyncFunctionDef object at 0x7da1b1c3b550> | keyword[async] keyword[def] identifier[set] ( identifier[self] , identifier[full] , identifier[valu] ):
literal[string]
identifier[node] = keyword[await] identifier[self] . identifier[_getHiveNode] ( identifier[full] )
identifier[oldv] = identifier[node] . identifier[valu]
id... | async def set(self, full, valu):
"""
A set operation at the hive level (full path).
"""
node = await self._getHiveNode(full)
oldv = node.valu
node.valu = await self.storNodeValu(full, valu)
await node.fire('hive:set', path=full, valu=valu, oldv=oldv)
return oldv |
def normalize_cpp_function(self, function, line):
"""Normalizes a single cpp frame with a function"""
# Drop member function cv/ref qualifiers like const, const&, &, and &&
for ref in ('const', 'const&', '&&', '&'):
if function.endswith(ref):
function = function[:-len... | def function[normalize_cpp_function, parameter[self, function, line]]:
constant[Normalizes a single cpp frame with a function]
for taget[name[ref]] in starred[tuple[[<ast.Constant object at 0x7da18f09e4d0>, <ast.Constant object at 0x7da18f09f9a0>, <ast.Constant object at 0x7da18f09c5b0>, <ast.Constant o... | keyword[def] identifier[normalize_cpp_function] ( identifier[self] , identifier[function] , identifier[line] ):
literal[string]
keyword[for] identifier[ref] keyword[in] ( literal[string] , literal[string] , literal[string] , literal[string] ):
keyword[if] identifier[functio... | def normalize_cpp_function(self, function, line):
"""Normalizes a single cpp frame with a function"""
# Drop member function cv/ref qualifiers like const, const&, &, and &&
for ref in ('const', 'const&', '&&', '&'):
if function.endswith(ref):
function = function[:-len(ref)].strip() # de... |
def Generate(self, items, token=None):
"""Generates archive from a given collection.
Iterates the collection and generates an archive by yielding contents
of every referenced AFF4Stream.
Args:
items: Iterable of rdf_client_fs.StatEntry objects
token: User's ACLToken.
Yields:
Bin... | def function[Generate, parameter[self, items, token]]:
constant[Generates archive from a given collection.
Iterates the collection and generates an archive by yielding contents
of every referenced AFF4Stream.
Args:
items: Iterable of rdf_client_fs.StatEntry objects
token: User's ACLTok... | keyword[def] identifier[Generate] ( identifier[self] , identifier[items] , identifier[token] = keyword[None] ):
literal[string]
keyword[del] identifier[token]
identifier[client_ids] = identifier[set] ()
keyword[for] identifier[item_batch] keyword[in] identifier[collection] . identifier[Bat... | def Generate(self, items, token=None):
"""Generates archive from a given collection.
Iterates the collection and generates an archive by yielding contents
of every referenced AFF4Stream.
Args:
items: Iterable of rdf_client_fs.StatEntry objects
token: User's ACLToken.
Yields:
Bin... |
def line_distance_similarity(p1a, p1b, p2a, p2b, T=CLOSE_DISTANCE_THRESHOLD):
"""Line distance similarity between two line segments
Args:
p1a ([float, float]): x and y coordinates. Line A start
p1b ([float, float]): x and y coordinates. Line A end
p2a ([float, float]): x and y coordinat... | def function[line_distance_similarity, parameter[p1a, p1b, p2a, p2b, T]]:
constant[Line distance similarity between two line segments
Args:
p1a ([float, float]): x and y coordinates. Line A start
p1b ([float, float]): x and y coordinates. Line A end
p2a ([float, float]): x and y coo... | keyword[def] identifier[line_distance_similarity] ( identifier[p1a] , identifier[p1b] , identifier[p2a] , identifier[p2b] , identifier[T] = identifier[CLOSE_DISTANCE_THRESHOLD] ):
literal[string]
identifier[d1] = identifier[distance_similarity] ( identifier[p1a] , identifier[p1b] , identifier[p2a] , identi... | def line_distance_similarity(p1a, p1b, p2a, p2b, T=CLOSE_DISTANCE_THRESHOLD):
"""Line distance similarity between two line segments
Args:
p1a ([float, float]): x and y coordinates. Line A start
p1b ([float, float]): x and y coordinates. Line A end
p2a ([float, float]): x and y coordinat... |
def detect(self):
"""
Try to contact a remote webservice and parse the returned output.
Determine the IP address from the parsed output and return.
"""
if self.opts_url and self.opts_parser:
url = self.opts_url
parser = self.opts_parser
else:
... | def function[detect, parameter[self]]:
constant[
Try to contact a remote webservice and parse the returned output.
Determine the IP address from the parsed output and return.
]
if <ast.BoolOp object at 0x7da1b1b69420> begin[:]
variable[url] assign[=] name[self].o... | keyword[def] identifier[detect] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[opts_url] keyword[and] identifier[self] . identifier[opts_parser] :
identifier[url] = identifier[self] . identifier[opts_url]
identifier[parser] = identifier... | def detect(self):
"""
Try to contact a remote webservice and parse the returned output.
Determine the IP address from the parsed output and return.
"""
if self.opts_url and self.opts_parser:
url = self.opts_url
parser = self.opts_parser # depends on [control=['if'], dat... |
def assemble_notification_request(method, params=tuple()):
"""serialize a JSON-RPC-Notification
:Parameters: see dumps_request
:Returns: | {"method": "...", "params": ..., "id": null}
| "method", "params" and "id" are always in this order.
:Raises: see dumps_req... | def function[assemble_notification_request, parameter[method, params]]:
constant[serialize a JSON-RPC-Notification
:Parameters: see dumps_request
:Returns: | {"method": "...", "params": ..., "id": null}
| "method", "params" and "id" are always in this order.
:Raise... | keyword[def] identifier[assemble_notification_request] ( identifier[method] , identifier[params] = identifier[tuple] ()):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[method] ,( identifier[str] , identifier[unicode] )):
keyword[raise] identifier[TypeE... | def assemble_notification_request(method, params=tuple()):
"""serialize a JSON-RPC-Notification
:Parameters: see dumps_request
:Returns: | {"method": "...", "params": ..., "id": null}
| "method", "params" and "id" are always in this order.
:Raises: see dumps_request... |
def get_countries_geo_zone_by_id(cls, countries_geo_zone_id, **kwargs):
"""Find CountriesGeoZone
Return single instance of CountriesGeoZone by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread... | def function[get_countries_geo_zone_by_id, parameter[cls, countries_geo_zone_id]]:
constant[Find CountriesGeoZone
Return single instance of CountriesGeoZone by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
... | keyword[def] identifier[get_countries_geo_zone_by_id] ( identifier[cls] , identifier[countries_geo_zone_id] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
k... | def get_countries_geo_zone_by_id(cls, countries_geo_zone_id, **kwargs):
"""Find CountriesGeoZone
Return single instance of CountriesGeoZone by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = a... |
def get_complete_version(version=None):
"""
Returns a tuple of the django_cryptography version. If version
argument is non-empty, then checks for correctness of the tuple
provided.
"""
if version is None:
from django_cryptography import VERSION as version
else:
assert len(ver... | def function[get_complete_version, parameter[version]]:
constant[
Returns a tuple of the django_cryptography version. If version
argument is non-empty, then checks for correctness of the tuple
provided.
]
if compare[name[version] is constant[None]] begin[:]
from relative_module[d... | keyword[def] identifier[get_complete_version] ( identifier[version] = keyword[None] ):
literal[string]
keyword[if] identifier[version] keyword[is] keyword[None] :
keyword[from] identifier[django_cryptography] keyword[import] identifier[VERSION] keyword[as] identifier[version]
keyword... | def get_complete_version(version=None):
"""
Returns a tuple of the django_cryptography version. If version
argument is non-empty, then checks for correctness of the tuple
provided.
"""
if version is None:
from django_cryptography import VERSION as version # depends on [control=['if'], d... |
def compress_delete_outdir(outdir):
"""Compress the contents of the passed directory to .tar.gz and delete."""
# Compress output in .tar.gz file and remove raw output
tarfn = outdir + ".tar.gz"
logger.info("\tCompressing output from %s to %s", outdir, tarfn)
with tarfile.open(tarfn, "w:gz") as fh:
... | def function[compress_delete_outdir, parameter[outdir]]:
constant[Compress the contents of the passed directory to .tar.gz and delete.]
variable[tarfn] assign[=] binary_operation[name[outdir] + constant[.tar.gz]]
call[name[logger].info, parameter[constant[ Compressing output from %s to %s], name... | keyword[def] identifier[compress_delete_outdir] ( identifier[outdir] ):
literal[string]
identifier[tarfn] = identifier[outdir] + literal[string]
identifier[logger] . identifier[info] ( literal[string] , identifier[outdir] , identifier[tarfn] )
keyword[with] identifier[tarfile] . identifier... | def compress_delete_outdir(outdir):
"""Compress the contents of the passed directory to .tar.gz and delete."""
# Compress output in .tar.gz file and remove raw output
tarfn = outdir + '.tar.gz'
logger.info('\tCompressing output from %s to %s', outdir, tarfn)
with tarfile.open(tarfn, 'w:gz') as fh:
... |
def current_app_is_admin(self):
"""Returns boolean whether current application is Admin contrib.
:rtype: bool
"""
is_admin = self._current_app_is_admin
if is_admin is None:
context = self.current_page_context
current_app = getattr(
# Try ... | def function[current_app_is_admin, parameter[self]]:
constant[Returns boolean whether current application is Admin contrib.
:rtype: bool
]
variable[is_admin] assign[=] name[self]._current_app_is_admin
if compare[name[is_admin] is constant[None]] begin[:]
variable... | keyword[def] identifier[current_app_is_admin] ( identifier[self] ):
literal[string]
identifier[is_admin] = identifier[self] . identifier[_current_app_is_admin]
keyword[if] identifier[is_admin] keyword[is] keyword[None] :
identifier[context] = identifier[self] . identifier[... | def current_app_is_admin(self):
"""Returns boolean whether current application is Admin contrib.
:rtype: bool
"""
is_admin = self._current_app_is_admin
if is_admin is None:
context = self.current_page_context
# Try from request.resolver_match.app_name
# Try from glob... |
def matches_at_fpr(fg_vals, bg_vals, fpr=0.01):
"""
Computes the hypergeometric p-value at a specific FPR (default 1%).
Parameters
----------
fg_vals : array_like
The list of values for the positive set.
bg_vals : array_like
The list of values for the negative set.
fpr... | def function[matches_at_fpr, parameter[fg_vals, bg_vals, fpr]]:
constant[
Computes the hypergeometric p-value at a specific FPR (default 1%).
Parameters
----------
fg_vals : array_like
The list of values for the positive set.
bg_vals : array_like
The list of values for the ... | keyword[def] identifier[matches_at_fpr] ( identifier[fg_vals] , identifier[bg_vals] , identifier[fpr] = literal[int] ):
literal[string]
identifier[fg_vals] = identifier[np] . identifier[array] ( identifier[fg_vals] )
identifier[s] = identifier[scoreatpercentile] ( identifier[bg_vals] , literal[int] - ... | def matches_at_fpr(fg_vals, bg_vals, fpr=0.01):
"""
Computes the hypergeometric p-value at a specific FPR (default 1%).
Parameters
----------
fg_vals : array_like
The list of values for the positive set.
bg_vals : array_like
The list of values for the negative set.
fpr... |
def generate_user_token(self, user, salt=None):
"""Generates a unique token associated to the user
"""
return self.token_serializer.dumps(str(user.id), salt=salt) | def function[generate_user_token, parameter[self, user, salt]]:
constant[Generates a unique token associated to the user
]
return[call[name[self].token_serializer.dumps, parameter[call[name[str], parameter[name[user].id]]]]] | keyword[def] identifier[generate_user_token] ( identifier[self] , identifier[user] , identifier[salt] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[token_serializer] . identifier[dumps] ( identifier[str] ( identifier[user] . identifier[id] ), identifier[salt] = i... | def generate_user_token(self, user, salt=None):
"""Generates a unique token associated to the user
"""
return self.token_serializer.dumps(str(user.id), salt=salt) |
def transform(v1, v2):
"""
Create an affine transformation matrix that maps vector 1
onto vector 2
https://math.stackexchange.com/questions/293116/rotating-one-3d-vector-to-another
"""
theta = angle(v1,v2)
x = N.cross(v1,v2)
x = x / N.linalg.norm(x)
A = N.array([
[0, -x[2],... | def function[transform, parameter[v1, v2]]:
constant[
Create an affine transformation matrix that maps vector 1
onto vector 2
https://math.stackexchange.com/questions/293116/rotating-one-3d-vector-to-another
]
variable[theta] assign[=] call[name[angle], parameter[name[v1], name[v2]]]
... | keyword[def] identifier[transform] ( identifier[v1] , identifier[v2] ):
literal[string]
identifier[theta] = identifier[angle] ( identifier[v1] , identifier[v2] )
identifier[x] = identifier[N] . identifier[cross] ( identifier[v1] , identifier[v2] )
identifier[x] = identifier[x] / identifier[N] . i... | def transform(v1, v2):
"""
Create an affine transformation matrix that maps vector 1
onto vector 2
https://math.stackexchange.com/questions/293116/rotating-one-3d-vector-to-another
"""
theta = angle(v1, v2)
x = N.cross(v1, v2)
x = x / N.linalg.norm(x)
A = N.array([[0, -x[2], x[1]], ... |
def display_table(headers, table):
"""Print a formatted table.
:param headers: A list of header objects that are displayed in the first
row of the table.
:param table: A list of lists where each sublist is a row of the table.
The number of elements in each row should be equal to the number ... | def function[display_table, parameter[headers, table]]:
constant[Print a formatted table.
:param headers: A list of header objects that are displayed in the first
row of the table.
:param table: A list of lists where each sublist is a row of the table.
The number of elements in each row... | keyword[def] identifier[display_table] ( identifier[headers] , identifier[table] ):
literal[string]
keyword[assert] identifier[all] ( identifier[len] ( identifier[row] )== identifier[len] ( identifier[headers] ) keyword[for] identifier[row] keyword[in] identifier[table] )
identifier[str_headers] ... | def display_table(headers, table):
"""Print a formatted table.
:param headers: A list of header objects that are displayed in the first
row of the table.
:param table: A list of lists where each sublist is a row of the table.
The number of elements in each row should be equal to the number ... |
def strip_brackets(text, brackets=None):
"""Strip brackets and what is inside brackets from text.
.. note::
If the text contains only one opening bracket, the rest of the text
will be ignored. This is a feature, not a bug, as we want to avoid that
this function raises errors too easily.... | def function[strip_brackets, parameter[text, brackets]]:
constant[Strip brackets and what is inside brackets from text.
.. note::
If the text contains only one opening bracket, the rest of the text
will be ignored. This is a feature, not a bug, as we want to avoid that
this function... | keyword[def] identifier[strip_brackets] ( identifier[text] , identifier[brackets] = keyword[None] ):
literal[string]
identifier[res] =[]
keyword[for] identifier[c] , identifier[type_] keyword[in] identifier[_tokens] ( identifier[text] , identifier[brackets] = identifier[brackets] ):
keywor... | def strip_brackets(text, brackets=None):
"""Strip brackets and what is inside brackets from text.
.. note::
If the text contains only one opening bracket, the rest of the text
will be ignored. This is a feature, not a bug, as we want to avoid that
this function raises errors too easily.... |
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
wh... | def function[matches_whitelist, parameter[self, matches, whitelist]]:
constant[
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
]
if <ast.UnaryOp object at 0x7da20cabcdf0> begin[:]
return[name[matches]]
variable[ret_m... | keyword[def] identifier[matches_whitelist] ( identifier[self] , identifier[matches] , identifier[whitelist] ):
literal[string]
keyword[if] keyword[not] identifier[whitelist] :
keyword[return] identifier[matches]
identifier[ret_matches] ={}
keyword[if] keyword[not... | def matches_whitelist(self, matches, whitelist):
"""
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
"""
if not whitelist:
return matches # depends on [control=['if'], data=[]]
ret_matches = {}
if not isinstance(whitelist, l... |
def patch_namespace(self, name, body, **kwargs):
"""
partially update the specified Namespace
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespace(name, body, async_req=True)
... | def function[patch_namespace, parameter[self, name, body]]:
constant[
partially update the specified Namespace
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespace(name, body, as... | keyword[def] identifier[patch_namespace] ( identifier[self] , identifier[name] , identifier[body] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[ret... | def patch_namespace(self, name, body, **kwargs):
"""
partially update the specified Namespace
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespace(name, body, async_req=True)
... |
def _sort(self, concepts, sort=None, language='any', reverse=False):
'''
Returns a sorted version of a list of concepts. Will leave the original
list unsorted.
:param list concepts: A list of concepts and collections.
:param string sort: What to sort on: `id`, `label` or `sortla... | def function[_sort, parameter[self, concepts, sort, language, reverse]]:
constant[
Returns a sorted version of a list of concepts. Will leave the original
list unsorted.
:param list concepts: A list of concepts and collections.
:param string sort: What to sort on: `id`, `label` ... | keyword[def] identifier[_sort] ( identifier[self] , identifier[concepts] , identifier[sort] = keyword[None] , identifier[language] = literal[string] , identifier[reverse] = keyword[False] ):
literal[string]
identifier[sorted] = identifier[copy] . identifier[copy] ( identifier[concepts] )
k... | def _sort(self, concepts, sort=None, language='any', reverse=False):
"""
Returns a sorted version of a list of concepts. Will leave the original
list unsorted.
:param list concepts: A list of concepts and collections.
:param string sort: What to sort on: `id`, `label` or `sortlabel`... |
def get_strip_metadata(self, catID):
'''Retrieves the strip catalog metadata given a cat ID.
Args:
catID (str): The source catalog ID from the platform catalog.
Returns:
metadata (dict): A metadata dictionary .
TODO: have this return a class object with int... | def function[get_strip_metadata, parameter[self, catID]]:
constant[Retrieves the strip catalog metadata given a cat ID.
Args:
catID (str): The source catalog ID from the platform catalog.
Returns:
metadata (dict): A metadata dictionary .
TODO: have this ret... | keyword[def] identifier[get_strip_metadata] ( identifier[self] , identifier[catID] ):
literal[string]
identifier[self] . identifier[logger] . identifier[debug] ( literal[string] )
identifier[url] = literal[string] %{
literal[string] : identifier[self] . identifier[base_url] , lit... | def get_strip_metadata(self, catID):
"""Retrieves the strip catalog metadata given a cat ID.
Args:
catID (str): The source catalog ID from the platform catalog.
Returns:
metadata (dict): A metadata dictionary .
TODO: have this return a class object with interes... |
def is_sorted(self, ranks=None):
"""
Checks whether the stack is sorted.
:arg dict ranks:
The rank dict to reference for checking. If ``None``, it will
default to ``DEFAULT_RANKS``.
:returns:
Whether or not the cards are sorted.
"""
... | def function[is_sorted, parameter[self, ranks]]:
constant[
Checks whether the stack is sorted.
:arg dict ranks:
The rank dict to reference for checking. If ``None``, it will
default to ``DEFAULT_RANKS``.
:returns:
Whether or not the cards are sorted.... | keyword[def] identifier[is_sorted] ( identifier[self] , identifier[ranks] = keyword[None] ):
literal[string]
identifier[ranks] = identifier[ranks] keyword[or] identifier[self] . identifier[ranks]
keyword[return] identifier[check_sorted] ( identifier[self] , identifier[ranks] ) | def is_sorted(self, ranks=None):
"""
Checks whether the stack is sorted.
:arg dict ranks:
The rank dict to reference for checking. If ``None``, it will
default to ``DEFAULT_RANKS``.
:returns:
Whether or not the cards are sorted.
"""
ranks = ... |
def _parse_format(cls, fmt):
"""Attempt to convert a SPEAD format specification to a numpy dtype.
Where necessary, `O` is used.
Raises
------
ValueError
If the format is illegal
"""
fields = []
if not fmt:
raise ValueError('empty f... | def function[_parse_format, parameter[cls, fmt]]:
constant[Attempt to convert a SPEAD format specification to a numpy dtype.
Where necessary, `O` is used.
Raises
------
ValueError
If the format is illegal
]
variable[fields] assign[=] list[[]]
... | keyword[def] identifier[_parse_format] ( identifier[cls] , identifier[fmt] ):
literal[string]
identifier[fields] =[]
keyword[if] keyword[not] identifier[fmt] :
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[for] identifier[code] , identifier[len... | def _parse_format(cls, fmt):
"""Attempt to convert a SPEAD format specification to a numpy dtype.
Where necessary, `O` is used.
Raises
------
ValueError
If the format is illegal
"""
fields = []
if not fmt:
raise ValueError('empty format') # depen... |
def setBusStop(self, vehID, stopID, duration=2**31 - 1, until=-1, flags=tc.STOP_DEFAULT):
"""setBusStop(string, string, integer, integer, integer) -> None
Adds or modifies a bus stop with the given parameters. The duration and the until attribute are
in milliseconds.
"""
self.se... | def function[setBusStop, parameter[self, vehID, stopID, duration, until, flags]]:
constant[setBusStop(string, string, integer, integer, integer) -> None
Adds or modifies a bus stop with the given parameters. The duration and the until attribute are
in milliseconds.
]
call[name[s... | keyword[def] identifier[setBusStop] ( identifier[self] , identifier[vehID] , identifier[stopID] , identifier[duration] = literal[int] ** literal[int] - literal[int] , identifier[until] =- literal[int] , identifier[flags] = identifier[tc] . identifier[STOP_DEFAULT] ):
literal[string]
identifier[self... | def setBusStop(self, vehID, stopID, duration=2 ** 31 - 1, until=-1, flags=tc.STOP_DEFAULT):
"""setBusStop(string, string, integer, integer, integer) -> None
Adds or modifies a bus stop with the given parameters. The duration and the until attribute are
in milliseconds.
"""
self.setStop(... |
def save_waypoints(self, filename):
'''save waypoints to a file'''
try:
#need to remove the leading and trailing quotes in filename
self.wploader.save(filename.strip('"'))
except Exception as msg:
print("Failed to save %s - %s" % (filename, msg))
r... | def function[save_waypoints, parameter[self, filename]]:
constant[save waypoints to a file]
<ast.Try object at 0x7da20c9918d0>
call[name[print], parameter[binary_operation[constant[Saved %u waypoints to %s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Call object at 0x7da20c76dd80>, <ast.Name obje... | keyword[def] identifier[save_waypoints] ( identifier[self] , identifier[filename] ):
literal[string]
keyword[try] :
identifier[self] . identifier[wploader] . identifier[save] ( identifier[filename] . identifier[strip] ( literal[string] ))
keyword[except] identifier[E... | def save_waypoints(self, filename):
"""save waypoints to a file"""
try:
#need to remove the leading and trailing quotes in filename
self.wploader.save(filename.strip('"')) # depends on [control=['try'], data=[]]
except Exception as msg:
print('Failed to save %s - %s' % (filename, ms... |
def schedule(self, elements=None):
"""Iterate over all hosts and services and call schedule method
(schedule next check)
If elements is None all our hosts and services are scheduled for a check.
:param elements: None or list of host / services to schedule
:type elements: None |... | def function[schedule, parameter[self, elements]]:
constant[Iterate over all hosts and services and call schedule method
(schedule next check)
If elements is None all our hosts and services are scheduled for a check.
:param elements: None or list of host / services to schedule
... | keyword[def] identifier[schedule] ( identifier[self] , identifier[elements] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[elements] :
identifier[elements] = identifier[self] . identifier[all_my_hosts_and_services] ()
keyword[for] ident... | def schedule(self, elements=None):
"""Iterate over all hosts and services and call schedule method
(schedule next check)
If elements is None all our hosts and services are scheduled for a check.
:param elements: None or list of host / services to schedule
:type elements: None | lis... |
def default(self, obj):
"""
:returns: obj._reprJSON() if it is defined, else
json.JSONEncoder.default(obj)
"""
if hasattr(obj, '_reprJSON'):
return obj._reprJSON()
#Let the base class default method raise the TypeError
return json.JSONEncoder.defau... | def function[default, parameter[self, obj]]:
constant[
:returns: obj._reprJSON() if it is defined, else
json.JSONEncoder.default(obj)
]
if call[name[hasattr], parameter[name[obj], constant[_reprJSON]]] begin[:]
return[call[name[obj]._reprJSON, parameter[]]]
return... | keyword[def] identifier[default] ( identifier[self] , identifier[obj] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[obj] , literal[string] ):
keyword[return] identifier[obj] . identifier[_reprJSON] ()
keyword[return] identifier[json] . identif... | def default(self, obj):
"""
:returns: obj._reprJSON() if it is defined, else
json.JSONEncoder.default(obj)
"""
if hasattr(obj, '_reprJSON'):
return obj._reprJSON() # depends on [control=['if'], data=[]]
#Let the base class default method raise the TypeError
return js... |
def handle_error(index_name, keep=False):
'''
Handle errors while indexing.
In case of error, properly log it, remove the index and exit.
If `keep` is `True`, index is not deleted.
'''
# Handle keyboard interrupt
signal.signal(signal.SIGINT, signal.default_int_handler)
signal.signal(sign... | def function[handle_error, parameter[index_name, keep]]:
constant[
Handle errors while indexing.
In case of error, properly log it, remove the index and exit.
If `keep` is `True`, index is not deleted.
]
call[name[signal].signal, parameter[name[signal].SIGINT, name[signal].default_int_ha... | keyword[def] identifier[handle_error] ( identifier[index_name] , identifier[keep] = keyword[False] ):
literal[string]
identifier[signal] . identifier[signal] ( identifier[signal] . identifier[SIGINT] , identifier[signal] . identifier[default_int_handler] )
identifier[signal] . identifier[signal] ... | def handle_error(index_name, keep=False):
"""
Handle errors while indexing.
In case of error, properly log it, remove the index and exit.
If `keep` is `True`, index is not deleted.
"""
# Handle keyboard interrupt
signal.signal(signal.SIGINT, signal.default_int_handler)
signal.signal(sign... |
def round_sigfigs(x, n=2):
"""
Rounds the number to the specified significant figures. x can also be
a list or array of numbers (in these cases, a numpy array is returned).
"""
iterable = is_iterable(x)
if not iterable: x = [x]
# make a copy to be safe
x = _n.array(x)
# loop o... | def function[round_sigfigs, parameter[x, n]]:
constant[
Rounds the number to the specified significant figures. x can also be
a list or array of numbers (in these cases, a numpy array is returned).
]
variable[iterable] assign[=] call[name[is_iterable], parameter[name[x]]]
if <ast.Un... | keyword[def] identifier[round_sigfigs] ( identifier[x] , identifier[n] = literal[int] ):
literal[string]
identifier[iterable] = identifier[is_iterable] ( identifier[x] )
keyword[if] keyword[not] identifier[iterable] : identifier[x] =[ identifier[x] ]
identifier[x] = identifier[_n] . ident... | def round_sigfigs(x, n=2):
"""
Rounds the number to the specified significant figures. x can also be
a list or array of numbers (in these cases, a numpy array is returned).
"""
iterable = is_iterable(x)
if not iterable:
x = [x] # depends on [control=['if'], data=[]]
# make a copy t... |
def find_matching(self) -> Dict[TLeft, TRight]:
"""Finds a matching in the bipartite graph.
This is done using the Hopcroft-Karp algorithm with an implementation from the
`hopcroftkarp` package.
Returns:
A dictionary where each edge of the matching is represented by a key-v... | def function[find_matching, parameter[self]]:
constant[Finds a matching in the bipartite graph.
This is done using the Hopcroft-Karp algorithm with an implementation from the
`hopcroftkarp` package.
Returns:
A dictionary where each edge of the matching is represented by a k... | keyword[def] identifier[find_matching] ( identifier[self] )-> identifier[Dict] [ identifier[TLeft] , identifier[TRight] ]:
literal[string]
identifier[directed_graph] ={}
keyword[for] ( identifier[left] , identifier[right] ) keyword[in]... | def find_matching(self) -> Dict[TLeft, TRight]:
"""Finds a matching in the bipartite graph.
This is done using the Hopcroft-Karp algorithm with an implementation from the
`hopcroftkarp` package.
Returns:
A dictionary where each edge of the matching is represented by a key-value... |
def timescales(self):
r"""Implied timescales of the TICA transformation
For each :math:`i`-th eigenvalue, this returns
.. math::
t_i = -\frac{\tau}{\log(|\lambda_i|)}
where :math:`\tau` is the :py:obj:`lag` of the TICA object and :math:`\lambda_i` is the `i`-th
:p... | def function[timescales, parameter[self]]:
constant[Implied timescales of the TICA transformation
For each :math:`i`-th eigenvalue, this returns
.. math::
t_i = -\frac{\tau}{\log(|\lambda_i|)}
where :math:`\tau` is the :py:obj:`lag` of the TICA object and :math:`\lambda_i... | keyword[def] identifier[timescales] ( identifier[self] ):
literal[string]
keyword[return] - identifier[self] . identifier[lag] / identifier[np] . identifier[log] ( identifier[np] . identifier[abs] ( identifier[self] . identifier[eigenvalues] )) | def timescales(self):
"""Implied timescales of the TICA transformation
For each :math:`i`-th eigenvalue, this returns
.. math::
t_i = -\\frac{\\tau}{\\log(|\\lambda_i|)}
where :math:`\\tau` is the :py:obj:`lag` of the TICA object and :math:`\\lambda_i` is the `i`-th
:... |
def get_version(module='spyder_notebook'):
"""Get version."""
with open(os.path.join(HERE, module, '_version.py'), 'r') as f:
data = f.read()
lines = data.split('\n')
for line in lines:
if line.startswith('VERSION_INFO'):
version_tuple = ast.literal_eval(line.split('=')[-1].s... | def function[get_version, parameter[module]]:
constant[Get version.]
with call[name[open], parameter[call[name[os].path.join, parameter[name[HERE], name[module], constant[_version.py]]], constant[r]]] begin[:]
variable[data] assign[=] call[name[f].read, parameter[]]
variable[line... | keyword[def] identifier[get_version] ( identifier[module] = literal[string] ):
literal[string]
keyword[with] identifier[open] ( identifier[os] . identifier[path] . identifier[join] ( identifier[HERE] , identifier[module] , literal[string] ), literal[string] ) keyword[as] identifier[f] :
identifi... | def get_version(module='spyder_notebook'):
"""Get version."""
with open(os.path.join(HERE, module, '_version.py'), 'r') as f:
data = f.read() # depends on [control=['with'], data=['f']]
lines = data.split('\n')
for line in lines:
if line.startswith('VERSION_INFO'):
version_t... |
def push_to_gateway(
gateway, job, registry, grouping_key=None, timeout=30,
handler=default_handler):
"""Push metrics to the given pushgateway.
`gateway` the url for your push gateway. Either of the form
'http://pushgateway.local', or 'pushgateway.local'.
Scheme defa... | def function[push_to_gateway, parameter[gateway, job, registry, grouping_key, timeout, handler]]:
constant[Push metrics to the given pushgateway.
`gateway` the url for your push gateway. Either of the form
'http://pushgateway.local', or 'pushgateway.local'.
Scheme defaults to 'h... | keyword[def] identifier[push_to_gateway] (
identifier[gateway] , identifier[job] , identifier[registry] , identifier[grouping_key] = keyword[None] , identifier[timeout] = literal[int] ,
identifier[handler] = identifier[default_handler] ):
literal[string]
identifier[_use_gateway] ( literal[string] , ident... | def push_to_gateway(gateway, job, registry, grouping_key=None, timeout=30, handler=default_handler):
"""Push metrics to the given pushgateway.
`gateway` the url for your push gateway. Either of the form
'http://pushgateway.local', or 'pushgateway.local'.
Scheme defaults to 'http' if... |
def get_zone():
'''
Displays the current time zone
:return: The current time zone
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' timezone.get_zone
'''
ret = salt.utils.mac_utils.execute_return_result('systemsetup -gettimezone')
return salt.utils.mac_utils.parse_re... | def function[get_zone, parameter[]]:
constant[
Displays the current time zone
:return: The current time zone
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' timezone.get_zone
]
variable[ret] assign[=] call[name[salt].utils.mac_utils.execute_return_result, param... | keyword[def] identifier[get_zone] ():
literal[string]
identifier[ret] = identifier[salt] . identifier[utils] . identifier[mac_utils] . identifier[execute_return_result] ( literal[string] )
keyword[return] identifier[salt] . identifier[utils] . identifier[mac_utils] . identifier[parse_return] ( identi... | def get_zone():
"""
Displays the current time zone
:return: The current time zone
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' timezone.get_zone
"""
ret = salt.utils.mac_utils.execute_return_result('systemsetup -gettimezone')
return salt.utils.mac_utils.parse_re... |
def stop_hb(self):
"""Stop the heartbeating and cancel all related callbacks."""
if self._beating:
self._beating = False
self._hb_periodic_callback.stop()
if not self.hb_stream.closed():
self.hb_stream.on_recv(None) | def function[stop_hb, parameter[self]]:
constant[Stop the heartbeating and cancel all related callbacks.]
if name[self]._beating begin[:]
name[self]._beating assign[=] constant[False]
call[name[self]._hb_periodic_callback.stop, parameter[]]
if <ast.UnaryOp... | keyword[def] identifier[stop_hb] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_beating] :
identifier[self] . identifier[_beating] = keyword[False]
identifier[self] . identifier[_hb_periodic_callback] . identifier[stop] ()
k... | def stop_hb(self):
"""Stop the heartbeating and cancel all related callbacks."""
if self._beating:
self._beating = False
self._hb_periodic_callback.stop()
if not self.hb_stream.closed():
self.hb_stream.on_recv(None) # depends on [control=['if'], data=[]] # depends on [contr... |
def auto(name):
'''
Trigger alternatives to set the path for <name> as
specified by priority.
CLI Example:
.. code-block:: bash
salt '*' alternatives.auto name
'''
cmd = [_get_cmd(), '--auto', name]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] >... | def function[auto, parameter[name]]:
constant[
Trigger alternatives to set the path for <name> as
specified by priority.
CLI Example:
.. code-block:: bash
salt '*' alternatives.auto name
]
variable[cmd] assign[=] list[[<ast.Call object at 0x7da1b21961d0>, <ast.Constant obj... | keyword[def] identifier[auto] ( identifier[name] ):
literal[string]
identifier[cmd] =[ identifier[_get_cmd] (), literal[string] , identifier[name] ]
identifier[out] = identifier[__salt__] [ literal[string] ]( identifier[cmd] , identifier[python_shell] = keyword[False] )
keyword[if] identifier[ou... | def auto(name):
"""
Trigger alternatives to set the path for <name> as
specified by priority.
CLI Example:
.. code-block:: bash
salt '*' alternatives.auto name
"""
cmd = [_get_cmd(), '--auto', name]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] >... |
def protein_only_and_noH(self, keep_ligands=None, force_rerun=False):
"""Isolate the receptor by stripping everything except protein and specified ligands.
Args:
keep_ligands (str, list): Ligand(s) to keep in PDB file
force_rerun (bool): If method should be rerun even if output ... | def function[protein_only_and_noH, parameter[self, keep_ligands, force_rerun]]:
constant[Isolate the receptor by stripping everything except protein and specified ligands.
Args:
keep_ligands (str, list): Ligand(s) to keep in PDB file
force_rerun (bool): If method should be rerun... | keyword[def] identifier[protein_only_and_noH] ( identifier[self] , identifier[keep_ligands] = keyword[None] , identifier[force_rerun] = keyword[False] ):
literal[string]
identifier[log] . identifier[debug] ( literal[string] . identifier[format] ( identifier[self] . identifier[id] ))
keywo... | def protein_only_and_noH(self, keep_ligands=None, force_rerun=False):
"""Isolate the receptor by stripping everything except protein and specified ligands.
Args:
keep_ligands (str, list): Ligand(s) to keep in PDB file
force_rerun (bool): If method should be rerun even if output file... |
def dataset_document_iterator(self, file_path: str) -> Iterator[List[OntonotesSentence]]:
"""
An iterator over CONLL formatted files which yields documents, regardless
of the number of document annotations in a particular file. This is useful
for conll data which has been preprocessed, s... | def function[dataset_document_iterator, parameter[self, file_path]]:
constant[
An iterator over CONLL formatted files which yields documents, regardless
of the number of document annotations in a particular file. This is useful
for conll data which has been preprocessed, such as the prep... | keyword[def] identifier[dataset_document_iterator] ( identifier[self] , identifier[file_path] : identifier[str] )-> identifier[Iterator] [ identifier[List] [ identifier[OntonotesSentence] ]]:
literal[string]
keyword[with] identifier[codecs] . identifier[open] ( identifier[file_path] , literal[stri... | def dataset_document_iterator(self, file_path: str) -> Iterator[List[OntonotesSentence]]:
"""
An iterator over CONLL formatted files which yields documents, regardless
of the number of document annotations in a particular file. This is useful
for conll data which has been preprocessed, such ... |
def query_folder(self, dir_name):
"""查询目录属性(https://www.qcloud.com/document/product/436/6063)
:param dir_name:查询的目录的名称
:return:查询出来的结果,为json格式
"""
if dir_name[0] == '/':
dir_name = dir_name[1:len(dir_name)]
self.url = 'http://' + self.config.region + '.file.m... | def function[query_folder, parameter[self, dir_name]]:
constant[查询目录属性(https://www.qcloud.com/document/product/436/6063)
:param dir_name:查询的目录的名称
:return:查询出来的结果,为json格式
]
if compare[call[name[dir_name]][constant[0]] equal[==] constant[/]] begin[:]
variable[dir_n... | keyword[def] identifier[query_folder] ( identifier[self] , identifier[dir_name] ):
literal[string]
keyword[if] identifier[dir_name] [ literal[int] ]== literal[string] :
identifier[dir_name] = identifier[dir_name] [ literal[int] : identifier[len] ( identifier[dir_name] )]
iden... | def query_folder(self, dir_name):
"""查询目录属性(https://www.qcloud.com/document/product/436/6063)
:param dir_name:查询的目录的名称
:return:查询出来的结果,为json格式
"""
if dir_name[0] == '/':
dir_name = dir_name[1:len(dir_name)] # depends on [control=['if'], data=[]]
self.url = 'http://' + self.... |
def remove_child(self, id_, child_id):
"""Removes a childfrom an ``Id``.
arg: id (osid.id.Id): the ``Id`` of the node
arg: child_id (osid.id.Id): the ``Id`` of the child to remove
raise: NotFound - ``id`` or ``child_id`` was not found or
``child_id`` is not a chil... | def function[remove_child, parameter[self, id_, child_id]]:
constant[Removes a childfrom an ``Id``.
arg: id (osid.id.Id): the ``Id`` of the node
arg: child_id (osid.id.Id): the ``Id`` of the child to remove
raise: NotFound - ``id`` or ``child_id`` was not found or
... | keyword[def] identifier[remove_child] ( identifier[self] , identifier[id_] , identifier[child_id] ):
literal[string]
identifier[result] = identifier[self] . identifier[_rls] . identifier[get_relationships_by_genus_type_for_peers] ( identifier[id_] , identifier[child_id] , identifier[self] . identif... | def remove_child(self, id_, child_id):
"""Removes a childfrom an ``Id``.
arg: id (osid.id.Id): the ``Id`` of the node
arg: child_id (osid.id.Id): the ``Id`` of the child to remove
raise: NotFound - ``id`` or ``child_id`` was not found or
``child_id`` is not a child of... |
def exclude(self):
"""
Custom descriptor for exclude since there is no get_exclude method to
be overridden
"""
exclude = self.VERSIONED_EXCLUDE
if super(VersionedAdmin, self).exclude is not None:
# Force cast to list as super exclude could return a tuple
... | def function[exclude, parameter[self]]:
constant[
Custom descriptor for exclude since there is no get_exclude method to
be overridden
]
variable[exclude] assign[=] name[self].VERSIONED_EXCLUDE
if compare[call[name[super], parameter[name[VersionedAdmin], name[self]]].exclu... | keyword[def] identifier[exclude] ( identifier[self] ):
literal[string]
identifier[exclude] = identifier[self] . identifier[VERSIONED_EXCLUDE]
keyword[if] identifier[super] ( identifier[VersionedAdmin] , identifier[self] ). identifier[exclude] keyword[is] keyword[not] keyword[None] :
... | def exclude(self):
"""
Custom descriptor for exclude since there is no get_exclude method to
be overridden
"""
exclude = self.VERSIONED_EXCLUDE
if super(VersionedAdmin, self).exclude is not None:
# Force cast to list as super exclude could return a tuple
exclude = lis... |
def writetofile(self, filename):
'''Writes the in-memory zip to a file.'''
f = open(filename, "w")
f.write(self.read())
f.close() | def function[writetofile, parameter[self, filename]]:
constant[Writes the in-memory zip to a file.]
variable[f] assign[=] call[name[open], parameter[name[filename], constant[w]]]
call[name[f].write, parameter[call[name[self].read, parameter[]]]]
call[name[f].close, parameter[]] | keyword[def] identifier[writetofile] ( identifier[self] , identifier[filename] ):
literal[string]
identifier[f] = identifier[open] ( identifier[filename] , literal[string] )
identifier[f] . identifier[write] ( identifier[self] . identifier[read] ())
identifier[f] . identifier[clos... | def writetofile(self, filename):
"""Writes the in-memory zip to a file."""
f = open(filename, 'w')
f.write(self.read())
f.close() |
def shutdown(name, message=None, timeout=5, force_close=True, reboot=False,
in_seconds=False, only_on_pending_reboot=False):
'''
Shutdown the computer
:param str message:
An optional message to display to users. It will also be used as a
comment in the event log entry.
... | def function[shutdown, parameter[name, message, timeout, force_close, reboot, in_seconds, only_on_pending_reboot]]:
constant[
Shutdown the computer
:param str message:
An optional message to display to users. It will also be used as a
comment in the event log entry.
The default... | keyword[def] identifier[shutdown] ( identifier[name] , identifier[message] = keyword[None] , identifier[timeout] = literal[int] , identifier[force_close] = keyword[True] , identifier[reboot] = keyword[False] ,
identifier[in_seconds] = keyword[False] , identifier[only_on_pending_reboot] = keyword[False] ):
liter... | def shutdown(name, message=None, timeout=5, force_close=True, reboot=False, in_seconds=False, only_on_pending_reboot=False):
"""
Shutdown the computer
:param str message:
An optional message to display to users. It will also be used as a
comment in the event log entry.
The default ... |
def fill_hazard_class(layer):
"""We need to fill hazard class when it's empty.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:return: The updated vector layer.
:rtype: QgsVectorLayer
.. versionadded:: 4.0
"""
hazard_field = layer.keywords['inasafe_fields'][hazard_class_f... | def function[fill_hazard_class, parameter[layer]]:
constant[We need to fill hazard class when it's empty.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:return: The updated vector layer.
:rtype: QgsVectorLayer
.. versionadded:: 4.0
]
variable[hazard_field] assign... | keyword[def] identifier[fill_hazard_class] ( identifier[layer] ):
literal[string]
identifier[hazard_field] = identifier[layer] . identifier[keywords] [ literal[string] ][ identifier[hazard_class_field] [ literal[string] ]]
identifier[expression] = literal[string] %( identifier[hazard_field] , identif... | def fill_hazard_class(layer):
"""We need to fill hazard class when it's empty.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:return: The updated vector layer.
:rtype: QgsVectorLayer
.. versionadded:: 4.0
"""
hazard_field = layer.keywords['inasafe_fields'][hazard_class_f... |
def probabilities(items, params):
"""Compute the comparison outcome probabilities given a subset of items.
This function computes, for each item in ``items``, the probability that it
would win (i.e., be chosen) in a comparison involving the items, given
model parameters.
Parameters
----------
... | def function[probabilities, parameter[items, params]]:
constant[Compute the comparison outcome probabilities given a subset of items.
This function computes, for each item in ``items``, the probability that it
would win (i.e., be chosen) in a comparison involving the items, given
model parameters.
... | keyword[def] identifier[probabilities] ( identifier[items] , identifier[params] ):
literal[string]
identifier[params] = identifier[np] . identifier[asarray] ( identifier[params] )
keyword[return] identifier[softmax] ( identifier[params] . identifier[take] ( identifier[items] )) | def probabilities(items, params):
"""Compute the comparison outcome probabilities given a subset of items.
This function computes, for each item in ``items``, the probability that it
would win (i.e., be chosen) in a comparison involving the items, given
model parameters.
Parameters
----------
... |
def translate_basic(usercode):
""" Translate a basic color name to color with explanation. """
codenum = get_code_num(codes['fore'][usercode])
colorcode = codeformat(codenum)
msg = 'Name: {:>10}, Number: {:>3}, EscapeCode: {!r}'.format(
usercode,
codenum,
colorcode
)
if d... | def function[translate_basic, parameter[usercode]]:
constant[ Translate a basic color name to color with explanation. ]
variable[codenum] assign[=] call[name[get_code_num], parameter[call[call[name[codes]][constant[fore]]][name[usercode]]]]
variable[colorcode] assign[=] call[name[codeformat], pa... | keyword[def] identifier[translate_basic] ( identifier[usercode] ):
literal[string]
identifier[codenum] = identifier[get_code_num] ( identifier[codes] [ literal[string] ][ identifier[usercode] ])
identifier[colorcode] = identifier[codeformat] ( identifier[codenum] )
identifier[msg] = literal[strin... | def translate_basic(usercode):
""" Translate a basic color name to color with explanation. """
codenum = get_code_num(codes['fore'][usercode])
colorcode = codeformat(codenum)
msg = 'Name: {:>10}, Number: {:>3}, EscapeCode: {!r}'.format(usercode, codenum, colorcode)
if disabled():
return msg ... |
def string_get(self, ypos, xpos, length):
"""
Get a string of `length` at screen co-ordinates `ypos`/`xpos`
Co-ordinates are 1 based, as listed in the status area of the
terminal.
"""
# the screen's co-ordinates are 1 based, but the command is 0 based
... | def function[string_get, parameter[self, ypos, xpos, length]]:
constant[
Get a string of `length` at screen co-ordinates `ypos`/`xpos`
Co-ordinates are 1 based, as listed in the status area of the
terminal.
]
<ast.AugAssign object at 0x7da1b008b820>
<ast.AugA... | keyword[def] identifier[string_get] ( identifier[self] , identifier[ypos] , identifier[xpos] , identifier[length] ):
literal[string]
identifier[xpos] -= literal[int]
identifier[ypos] -= literal[int]
identifier[cmd] = identifier[self] . identifier[exec_command] (
... | def string_get(self, ypos, xpos, length):
"""
Get a string of `length` at screen co-ordinates `ypos`/`xpos`
Co-ordinates are 1 based, as listed in the status area of the
terminal.
"""
# the screen's co-ordinates are 1 based, but the command is 0 based
xpos -= 1
... |
def filtered(self, indices):
"""
:param indices:
a subset of indices in the range [0 .. tot_sites - 1]
:returns:
a filtered SiteCollection instance if `indices` is a proper subset
of the available indices, otherwise returns the full SiteCollection
"""
... | def function[filtered, parameter[self, indices]]:
constant[
:param indices:
a subset of indices in the range [0 .. tot_sites - 1]
:returns:
a filtered SiteCollection instance if `indices` is a proper subset
of the available indices, otherwise returns the full Sit... | keyword[def] identifier[filtered] ( identifier[self] , identifier[indices] ):
literal[string]
keyword[if] identifier[indices] keyword[is] keyword[None] keyword[or] identifier[len] ( identifier[indices] )== identifier[len] ( identifier[self] ):
keyword[return] identifier[self]
... | def filtered(self, indices):
"""
:param indices:
a subset of indices in the range [0 .. tot_sites - 1]
:returns:
a filtered SiteCollection instance if `indices` is a proper subset
of the available indices, otherwise returns the full SiteCollection
"""
if ... |
def get_mobile_number(mobile):
"""
Returns a mobile number after removing blanks
Author: Himanshu Shankar (https://himanshus.com)
Parameters
----------
mobile: str
Returns
-------
str
"""
blanks = [' ', '.', ',', '(', ')', '-']
for b in blanks:
mobile = mobile.... | def function[get_mobile_number, parameter[mobile]]:
constant[
Returns a mobile number after removing blanks
Author: Himanshu Shankar (https://himanshus.com)
Parameters
----------
mobile: str
Returns
-------
str
]
variable[blanks] assign[=] list[[<ast.Constant object... | keyword[def] identifier[get_mobile_number] ( identifier[mobile] ):
literal[string]
identifier[blanks] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ]
keyword[for] identifier[b] keyword[in] identifier[blanks] :
identifier[mobil... | def get_mobile_number(mobile):
"""
Returns a mobile number after removing blanks
Author: Himanshu Shankar (https://himanshus.com)
Parameters
----------
mobile: str
Returns
-------
str
"""
blanks = [' ', '.', ',', '(', ')', '-']
for b in blanks:
mobile = mobile.r... |
def view(tilesets):
'''
Create a higlass viewer that displays the specified tilesets
Parameters:
-----------
Returns
-------
Nothing
'''
from .server import Server
from .client import View
curr_view = View()
server = Server()
server.start(tilesets)
for ts ... | def function[view, parameter[tilesets]]:
constant[
Create a higlass viewer that displays the specified tilesets
Parameters:
-----------
Returns
-------
Nothing
]
from relative_module[server] import module[Server]
from relative_module[client] import module[View]
... | keyword[def] identifier[view] ( identifier[tilesets] ):
literal[string]
keyword[from] . identifier[server] keyword[import] identifier[Server]
keyword[from] . identifier[client] keyword[import] identifier[View]
identifier[curr_view] = identifier[View] ()
identifier[server] = identifier... | def view(tilesets):
"""
Create a higlass viewer that displays the specified tilesets
Parameters:
-----------
Returns
-------
Nothing
"""
from .server import Server
from .client import View
curr_view = View()
server = Server()
server.start(tilesets)
for ts in... |
def relativesymlink(src_file, dest_file):
"""
https://stackoverflow.com/questions/9793631/creating-a-relative-symlink-in-python-without-using-os-chdir
:param src_file: the file to be linked
:param dest_file: the path and filename to which the file is to be linked
"""
# Perform relative symlinkin... | def function[relativesymlink, parameter[src_file, dest_file]]:
constant[
https://stackoverflow.com/questions/9793631/creating-a-relative-symlink-in-python-without-using-os-chdir
:param src_file: the file to be linked
:param dest_file: the path and filename to which the file is to be linked
]
... | keyword[def] identifier[relativesymlink] ( identifier[src_file] , identifier[dest_file] ):
literal[string]
keyword[try] :
identifier[print] ( identifier[os] . identifier[path] . identifier[relpath] ( identifier[src_file] ), identifier[os] . identifier[path] . identifier[relpath] ( identifier[... | def relativesymlink(src_file, dest_file):
"""
https://stackoverflow.com/questions/9793631/creating-a-relative-symlink-in-python-without-using-os-chdir
:param src_file: the file to be linked
:param dest_file: the path and filename to which the file is to be linked
"""
# Perform relative symlinkin... |
def set(self, obj, value):
"""Set value for obj's attribute.
:param obj: Result object or dict to assign the attribute to.
:param value: Value to be assigned.
"""
assert self.setter is not None, "Setter accessor is not specified."
if callable(self.setter):
re... | def function[set, parameter[self, obj, value]]:
constant[Set value for obj's attribute.
:param obj: Result object or dict to assign the attribute to.
:param value: Value to be assigned.
]
assert[compare[name[self].setter is_not constant[None]]]
if call[name[callable], parame... | keyword[def] identifier[set] ( identifier[self] , identifier[obj] , identifier[value] ):
literal[string]
keyword[assert] identifier[self] . identifier[setter] keyword[is] keyword[not] keyword[None] , literal[string]
keyword[if] identifier[callable] ( identifier[self] . identifier[set... | def set(self, obj, value):
"""Set value for obj's attribute.
:param obj: Result object or dict to assign the attribute to.
:param value: Value to be assigned.
"""
assert self.setter is not None, 'Setter accessor is not specified.'
if callable(self.setter):
return self.setter... |
def sortBy(self, keyfunc, ascending=True, numPartitions=None):
"""
Sorts this RDD by the given keyfunc
>>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]
>>> sc.parallelize(tmp).sortBy(lambda x: x[0]).collect()
[('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)]
... | def function[sortBy, parameter[self, keyfunc, ascending, numPartitions]]:
constant[
Sorts this RDD by the given keyfunc
>>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]
>>> sc.parallelize(tmp).sortBy(lambda x: x[0]).collect()
[('1', 3), ('2', 5), ('a', 1), ('b', 2), ... | keyword[def] identifier[sortBy] ( identifier[self] , identifier[keyfunc] , identifier[ascending] = keyword[True] , identifier[numPartitions] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[keyBy] ( identifier[keyfunc] ). identifier[sortByKey] ( identifier[ascending... | def sortBy(self, keyfunc, ascending=True, numPartitions=None):
"""
Sorts this RDD by the given keyfunc
>>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]
>>> sc.parallelize(tmp).sortBy(lambda x: x[0]).collect()
[('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)]
>>>... |
def block_user_signals(self, name, ignore_error=False):
"""
Temporarily disconnects the user-defined signals for the specified
parameter name.
Note this only affects those connections made with
connect_signal_changed(), and I do not recommend adding new connections
... | def function[block_user_signals, parameter[self, name, ignore_error]]:
constant[
Temporarily disconnects the user-defined signals for the specified
parameter name.
Note this only affects those connections made with
connect_signal_changed(), and I do not recommend addi... | keyword[def] identifier[block_user_signals] ( identifier[self] , identifier[name] , identifier[ignore_error] = keyword[False] ):
literal[string]
identifier[x] = identifier[self] . identifier[_find_parameter] ( identifier[name] . identifier[split] ( literal[string] ), identifier[quiet] = identifier[... | def block_user_signals(self, name, ignore_error=False):
"""
Temporarily disconnects the user-defined signals for the specified
parameter name.
Note this only affects those connections made with
connect_signal_changed(), and I do not recommend adding new connections
... |
def _pull_assemble_error_status(logs):
'''
Given input in this form::
u'{"status":"Pulling repository foo/ubuntubox"}:
"image (latest) from foo/ ...
rogress":"complete","id":"2c80228370c9"}'
construct something like that (load JSON data is possible)::
[u'{"status":"Pulli... | def function[_pull_assemble_error_status, parameter[logs]]:
constant[
Given input in this form::
u'{"status":"Pulling repository foo/ubuntubox"}:
"image (latest) from foo/ ...
rogress":"complete","id":"2c80228370c9"}'
construct something like that (load JSON data is possible)... | keyword[def] identifier[_pull_assemble_error_status] ( identifier[logs] ):
literal[string]
identifier[comment] = literal[string]
keyword[try] :
keyword[for] identifier[err_log] keyword[in] identifier[logs] :
keyword[if] identifier[isinstance] ( identifier[err_log] , identifi... | def _pull_assemble_error_status(logs):
"""
Given input in this form::
u'{"status":"Pulling repository foo/ubuntubox"}:
"image (latest) from foo/ ...
rogress":"complete","id":"2c80228370c9"}'
construct something like that (load JSON data is possible)::
[u'{"status":"Pulli... |
def extract_date(value):
"""
Convert timestamp to datetime and set everything to zero except a date
"""
dtime = value.to_datetime()
dtime = (dtime - timedelta(hours=dtime.hour) - timedelta(minutes=dtime.minute) -
timedelta(seconds=dtime.second) - timedelta(microseconds=dtime.microsecond... | def function[extract_date, parameter[value]]:
constant[
Convert timestamp to datetime and set everything to zero except a date
]
variable[dtime] assign[=] call[name[value].to_datetime, parameter[]]
variable[dtime] assign[=] binary_operation[binary_operation[binary_operation[binary_operat... | keyword[def] identifier[extract_date] ( identifier[value] ):
literal[string]
identifier[dtime] = identifier[value] . identifier[to_datetime] ()
identifier[dtime] =( identifier[dtime] - identifier[timedelta] ( identifier[hours] = identifier[dtime] . identifier[hour] )- identifier[timedelta] ( identifie... | def extract_date(value):
"""
Convert timestamp to datetime and set everything to zero except a date
"""
dtime = value.to_datetime()
dtime = dtime - timedelta(hours=dtime.hour) - timedelta(minutes=dtime.minute) - timedelta(seconds=dtime.second) - timedelta(microseconds=dtime.microsecond)
return d... |
def emit(self, event, *event_args):
"""Call the registered listeners for ``event``.
The listeners will be called with any extra arguments passed to
:meth:`emit` first, and then the extra arguments passed to :meth:`on`
"""
listeners = self._listeners[event][:]
for listene... | def function[emit, parameter[self, event]]:
constant[Call the registered listeners for ``event``.
The listeners will be called with any extra arguments passed to
:meth:`emit` first, and then the extra arguments passed to :meth:`on`
]
variable[listeners] assign[=] call[call[name[... | keyword[def] identifier[emit] ( identifier[self] , identifier[event] ,* identifier[event_args] ):
literal[string]
identifier[listeners] = identifier[self] . identifier[_listeners] [ identifier[event] ][:]
keyword[for] identifier[listener] keyword[in] identifier[listeners] :
... | def emit(self, event, *event_args):
"""Call the registered listeners for ``event``.
The listeners will be called with any extra arguments passed to
:meth:`emit` first, and then the extra arguments passed to :meth:`on`
"""
listeners = self._listeners[event][:]
for listener in listene... |
def getAttributeName(self, index):
"""
Returns the String which represents the attribute name
"""
offset = self._get_attribute_offset(index)
name = self.m_attributes[offset + const.ATTRIBUTE_IX_NAME]
res = self.sb[name]
# If the result is a (null) string, we need... | def function[getAttributeName, parameter[self, index]]:
constant[
Returns the String which represents the attribute name
]
variable[offset] assign[=] call[name[self]._get_attribute_offset, parameter[name[index]]]
variable[name] assign[=] call[name[self].m_attributes][binary_opera... | keyword[def] identifier[getAttributeName] ( identifier[self] , identifier[index] ):
literal[string]
identifier[offset] = identifier[self] . identifier[_get_attribute_offset] ( identifier[index] )
identifier[name] = identifier[self] . identifier[m_attributes] [ identifier[offset] + identifi... | def getAttributeName(self, index):
"""
Returns the String which represents the attribute name
"""
offset = self._get_attribute_offset(index)
name = self.m_attributes[offset + const.ATTRIBUTE_IX_NAME]
res = self.sb[name]
# If the result is a (null) string, we need to look it up.
i... |
def _new_song(self):
'''
Used internally to get a metasong index.
'''
# We'll need this later
s = self.song
if self.shuffle:
# If shuffle is on, we need to (1) get a random song that
# (2) accounts for weighting. This line does both.
... | def function[_new_song, parameter[self]]:
constant[
Used internally to get a metasong index.
]
variable[s] assign[=] name[self].song
if name[self].shuffle begin[:]
name[self].song assign[=] call[name[self].shuffles][call[name[random].randrange, parameter[call[name... | keyword[def] identifier[_new_song] ( identifier[self] ):
literal[string]
identifier[s] = identifier[self] . identifier[song]
keyword[if] identifier[self] . identifier[shuffle] :
identifier[self] . identifier[song] = identifier[self] . identifier[s... | def _new_song(self):
"""
Used internally to get a metasong index.
"""
# We'll need this later
s = self.song
if self.shuffle: # If shuffle is on, we need to (1) get a random song that
# (2) accounts for weighting. This line does both.
self.song = self.shuffles[random.ran... |
def dump_counts(self, out=sys.stdout, count_fn=len, colwidth=10):
"""Dump out the summary counts of entries in this pivot table as a tabular listing.
@param out: output stream to write to
@param count_fn: (default=len) function for computing value for each pivot cell
@param colw... | def function[dump_counts, parameter[self, out, count_fn, colwidth]]:
constant[Dump out the summary counts of entries in this pivot table as a tabular listing.
@param out: output stream to write to
@param count_fn: (default=len) function for computing value for each pivot cell
@p... | keyword[def] identifier[dump_counts] ( identifier[self] , identifier[out] = identifier[sys] . identifier[stdout] , identifier[count_fn] = identifier[len] , identifier[colwidth] = literal[int] ):
literal[string]
keyword[if] identifier[len] ( identifier[self] . identifier[_pivot_attrs] )== literal[i... | def dump_counts(self, out=sys.stdout, count_fn=len, colwidth=10):
"""Dump out the summary counts of entries in this pivot table as a tabular listing.
@param out: output stream to write to
@param count_fn: (default=len) function for computing value for each pivot cell
@param colwidth... |
def generate_slices(sliceable_set, batch_len=1, length=None, start_batch=0):
"""Iterate through a sequence (or generator) in batches of length `batch_len`
See Also:
pug.dj.db.generate_queryset_batches
References:
http://stackoverflow.com/a/761125/623735
Examples:
>> [batch for batc... | def function[generate_slices, parameter[sliceable_set, batch_len, length, start_batch]]:
constant[Iterate through a sequence (or generator) in batches of length `batch_len`
See Also:
pug.dj.db.generate_queryset_batches
References:
http://stackoverflow.com/a/761125/623735
Examples:
... | keyword[def] identifier[generate_slices] ( identifier[sliceable_set] , identifier[batch_len] = literal[int] , identifier[length] = keyword[None] , identifier[start_batch] = literal[int] ):
literal[string]
keyword[if] identifier[length] keyword[is] keyword[None] :
keyword[try] :
ide... | def generate_slices(sliceable_set, batch_len=1, length=None, start_batch=0):
"""Iterate through a sequence (or generator) in batches of length `batch_len`
See Also:
pug.dj.db.generate_queryset_batches
References:
http://stackoverflow.com/a/761125/623735
Examples:
>> [batch for batc... |
def cleanup_tail(options):
""" cleanup the tail of a recovery """
if options.kwargs['omode'] == "csv":
options.kwargs['fd'].write("\n")
elif options.kwargs['omode'] == "xml":
options.kwargs['fd'].write("\n</results>\n")
else:
options.kwargs['fd'].write("\n]\n") | def function[cleanup_tail, parameter[options]]:
constant[ cleanup the tail of a recovery ]
if compare[call[name[options].kwargs][constant[omode]] equal[==] constant[csv]] begin[:]
call[call[name[options].kwargs][constant[fd]].write, parameter[constant[
]]] | keyword[def] identifier[cleanup_tail] ( identifier[options] ):
literal[string]
keyword[if] identifier[options] . identifier[kwargs] [ literal[string] ]== literal[string] :
identifier[options] . identifier[kwargs] [ literal[string] ]. identifier[write] ( literal[string] )
keyword[elif] iden... | def cleanup_tail(options):
""" cleanup the tail of a recovery """
if options.kwargs['omode'] == 'csv':
options.kwargs['fd'].write('\n') # depends on [control=['if'], data=[]]
elif options.kwargs['omode'] == 'xml':
options.kwargs['fd'].write('\n</results>\n') # depends on [control=['if'], d... |
def get_icon_url(self, brain):
"""Returns the (big) icon URL for the given catalog brain
"""
icon_url = api.get_icon(brain, html_tag=False)
url, icon = icon_url.rsplit("/", 1)
relative_url = url.lstrip(self.portal.absolute_url())
name, ext = os.path.splitext(icon)
... | def function[get_icon_url, parameter[self, brain]]:
constant[Returns the (big) icon URL for the given catalog brain
]
variable[icon_url] assign[=] call[name[api].get_icon, parameter[name[brain]]]
<ast.Tuple object at 0x7da1b07bbcd0> assign[=] call[name[icon_url].rsplit, parameter[constan... | keyword[def] identifier[get_icon_url] ( identifier[self] , identifier[brain] ):
literal[string]
identifier[icon_url] = identifier[api] . identifier[get_icon] ( identifier[brain] , identifier[html_tag] = keyword[False] )
identifier[url] , identifier[icon] = identifier[icon_url] . identifier... | def get_icon_url(self, brain):
"""Returns the (big) icon URL for the given catalog brain
"""
icon_url = api.get_icon(brain, html_tag=False)
(url, icon) = icon_url.rsplit('/', 1)
relative_url = url.lstrip(self.portal.absolute_url())
(name, ext) = os.path.splitext(icon)
# big icons endwith... |
def event_list(consul_url=None, token=None, **kwargs):
'''
List the recent events.
:param consul_url: The Consul server URL.
:param name: The name of the event to fire.
:return: List of ACLs
CLI Example:
.. code-block:: bash
salt '*' consul.event_list
'''
ret = {}
qu... | def function[event_list, parameter[consul_url, token]]:
constant[
List the recent events.
:param consul_url: The Consul server URL.
:param name: The name of the event to fire.
:return: List of ACLs
CLI Example:
.. code-block:: bash
salt '*' consul.event_list
]
va... | keyword[def] identifier[event_list] ( identifier[consul_url] = keyword[None] , identifier[token] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[ret] ={}
identifier[query_params] ={}
keyword[if] keyword[not] identifier[consul_url] :
identifier[consul_url] = identif... | def event_list(consul_url=None, token=None, **kwargs):
"""
List the recent events.
:param consul_url: The Consul server URL.
:param name: The name of the event to fire.
:return: List of ACLs
CLI Example:
.. code-block:: bash
salt '*' consul.event_list
"""
ret = {}
qu... |
def update_control(self, control, process_id, wit_ref_name, group_id, control_id):
"""UpdateControl.
[Preview API] Updates a control on the work item form.
:param :class:`<Control> <azure.devops.v5_0.work_item_tracking_process.models.Control>` control: The updated control.
:param str pro... | def function[update_control, parameter[self, control, process_id, wit_ref_name, group_id, control_id]]:
constant[UpdateControl.
[Preview API] Updates a control on the work item form.
:param :class:`<Control> <azure.devops.v5_0.work_item_tracking_process.models.Control>` control: The updated cont... | keyword[def] identifier[update_control] ( identifier[self] , identifier[control] , identifier[process_id] , identifier[wit_ref_name] , identifier[group_id] , identifier[control_id] ):
literal[string]
identifier[route_values] ={}
keyword[if] identifier[process_id] keyword[is] keyword[not... | def update_control(self, control, process_id, wit_ref_name, group_id, control_id):
"""UpdateControl.
[Preview API] Updates a control on the work item form.
:param :class:`<Control> <azure.devops.v5_0.work_item_tracking_process.models.Control>` control: The updated control.
:param str process... |
def gen_component_name(self, basename, postfix_length=13):
"""
Creates a resource identifier with a random postfix. This is an
attempt to minimize name collisions in provider namespaces.
:param str basename: The string that will be prefixed with the stack
name, and postfix... | def function[gen_component_name, parameter[self, basename, postfix_length]]:
constant[
Creates a resource identifier with a random postfix. This is an
attempt to minimize name collisions in provider namespaces.
:param str basename: The string that will be prefixed with the stack
... | keyword[def] identifier[gen_component_name] ( identifier[self] , identifier[basename] , identifier[postfix_length] = literal[int] ):
literal[string]
keyword[def] identifier[newcname] ():
identifier[postfix] = literal[string] . identifier[join] (
identifier[random] . ident... | def gen_component_name(self, basename, postfix_length=13):
"""
Creates a resource identifier with a random postfix. This is an
attempt to minimize name collisions in provider namespaces.
:param str basename: The string that will be prefixed with the stack
name, and postfixed w... |
def tplot(self, analytes=None, figsize=[10, 4], scale='log', filt=None,
ranges=False, stats=False, stat='nanmean', err='nanstd',
focus_stage=None, err_envelope=False, ax=None):
"""
Plot analytes as a function of Time.
Parameters
----------
analytes : ... | def function[tplot, parameter[self, analytes, figsize, scale, filt, ranges, stats, stat, err, focus_stage, err_envelope, ax]]:
constant[
Plot analytes as a function of Time.
Parameters
----------
analytes : array_like
list of strings containing names of analytes to p... | keyword[def] identifier[tplot] ( identifier[self] , identifier[analytes] = keyword[None] , identifier[figsize] =[ literal[int] , literal[int] ], identifier[scale] = literal[string] , identifier[filt] = keyword[None] ,
identifier[ranges] = keyword[False] , identifier[stats] = keyword[False] , identifier[stat] = liter... | def tplot(self, analytes=None, figsize=[10, 4], scale='log', filt=None, ranges=False, stats=False, stat='nanmean', err='nanstd', focus_stage=None, err_envelope=False, ax=None):
"""
Plot analytes as a function of Time.
Parameters
----------
analytes : array_like
list of s... |
def set_col_first(df, col_names):
"""set selected columns first in a pandas.DataFrame.
This function sets cols with names given in col_names (a list) first in
the DataFrame. The last col in col_name will come first (processed last)
"""
column_headings = df.columns
colu... | def function[set_col_first, parameter[df, col_names]]:
constant[set selected columns first in a pandas.DataFrame.
This function sets cols with names given in col_names (a list) first in
the DataFrame. The last col in col_name will come first (processed last)
]
variable[column_h... | keyword[def] identifier[set_col_first] ( identifier[df] , identifier[col_names] ):
literal[string]
identifier[column_headings] = identifier[df] . identifier[columns]
identifier[column_headings] = identifier[column_headings] . identifier[tolist] ()
keyword[try] :
key... | def set_col_first(df, col_names):
"""set selected columns first in a pandas.DataFrame.
This function sets cols with names given in col_names (a list) first in
the DataFrame. The last col in col_name will come first (processed last)
"""
column_headings = df.columns
column_headings =... |
def from_image(cls, filename, start, stop, legend,
source="Image",
col_offset=0.1,
row_offset=2,
tolerance=0):
"""
Read an image and generate Striplog.
Args:
filename (str): An image file, preferably high-re... | def function[from_image, parameter[cls, filename, start, stop, legend, source, col_offset, row_offset, tolerance]]:
constant[
Read an image and generate Striplog.
Args:
filename (str): An image file, preferably high-res PNG.
start (float or int): The depth at the top of ... | keyword[def] identifier[from_image] ( identifier[cls] , identifier[filename] , identifier[start] , identifier[stop] , identifier[legend] ,
identifier[source] = literal[string] ,
identifier[col_offset] = literal[int] ,
identifier[row_offset] = literal[int] ,
identifier[tolerance] = literal[int] ):
literal... | def from_image(cls, filename, start, stop, legend, source='Image', col_offset=0.1, row_offset=2, tolerance=0):
"""
Read an image and generate Striplog.
Args:
filename (str): An image file, preferably high-res PNG.
start (float or int): The depth at the top of the image.
... |
def send(self, cumulative_counters=None, gauges=None, counters=None):
"""Send the given metrics to SignalFx.
Args:
cumulative_counters (list): a list of dictionaries representing the
cumulative counters to report.
gauges (list): a list of dictionaries representin... | def function[send, parameter[self, cumulative_counters, gauges, counters]]:
constant[Send the given metrics to SignalFx.
Args:
cumulative_counters (list): a list of dictionaries representing the
cumulative counters to report.
gauges (list): a list of dictionaries... | keyword[def] identifier[send] ( identifier[self] , identifier[cumulative_counters] = keyword[None] , identifier[gauges] = keyword[None] , identifier[counters] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[gauges] keyword[and] keyword[not] identifier[cumulative_counters... | def send(self, cumulative_counters=None, gauges=None, counters=None):
"""Send the given metrics to SignalFx.
Args:
cumulative_counters (list): a list of dictionaries representing the
cumulative counters to report.
gauges (list): a list of dictionaries representing th... |
def get_values(self):
"""Get all visual property values for the object
:return: dictionary of values (VP ID - value)
"""
results = requests.get(self.url).json()
values = {}
for entry in results:
values[entry['visualProperty']] = entry['value']
return... | def function[get_values, parameter[self]]:
constant[Get all visual property values for the object
:return: dictionary of values (VP ID - value)
]
variable[results] assign[=] call[call[name[requests].get, parameter[name[self].url]].json, parameter[]]
variable[values] assign[=] di... | keyword[def] identifier[get_values] ( identifier[self] ):
literal[string]
identifier[results] = identifier[requests] . identifier[get] ( identifier[self] . identifier[url] ). identifier[json] ()
identifier[values] ={}
keyword[for] identifier[entry] keyword[in] identifier[resul... | def get_values(self):
"""Get all visual property values for the object
:return: dictionary of values (VP ID - value)
"""
results = requests.get(self.url).json()
values = {}
for entry in results:
values[entry['visualProperty']] = entry['value'] # depends on [control=['for'], dat... |
def store(self, prof_name, prof_type):
"""
Store a profile with the given name and type.
:param str prof_name:
Profile name.
:param str prof_type:
Profile type.
"""
prof_dir = self.__profile_dir(prof_name)
prof_stub = self.__profile_stub(prof_name, prof_type, prof_dir)
if not os.path.e... | def function[store, parameter[self, prof_name, prof_type]]:
constant[
Store a profile with the given name and type.
:param str prof_name:
Profile name.
:param str prof_type:
Profile type.
]
variable[prof_dir] assign[=] call[name[self].__profile_dir, parameter[name[prof_name]]]
... | keyword[def] identifier[store] ( identifier[self] , identifier[prof_name] , identifier[prof_type] ):
literal[string]
identifier[prof_dir] = identifier[self] . identifier[__profile_dir] ( identifier[prof_name] )
identifier[prof_stub] = identifier[self] . identifier[__profile_stub] ( identifier[prof_name] ,... | def store(self, prof_name, prof_type):
"""
Store a profile with the given name and type.
:param str prof_name:
Profile name.
:param str prof_type:
Profile type.
"""
prof_dir = self.__profile_dir(prof_name)
prof_stub = self.__profile_stub(prof_name, prof_type, prof_dir)
if not os.pat... |
def reload(self, cascadeObjects=True):
'''
reload - Reload this object from the database, overriding any local changes and merging in any updates.
@param cascadeObjects <bool> Default True. If True, foreign-linked objects will be reloaded if their values have changed
since last save/fe... | def function[reload, parameter[self, cascadeObjects]]:
constant[
reload - Reload this object from the database, overriding any local changes and merging in any updates.
@param cascadeObjects <bool> Default True. If True, foreign-linked objects will be reloaded if their values have change... | keyword[def] identifier[reload] ( identifier[self] , identifier[cascadeObjects] = keyword[True] ):
literal[string]
identifier[_id] = identifier[self] . identifier[_id]
keyword[if] keyword[not] identifier[_id] :
keyword[raise] identifier[KeyError] ( literal[string] )
identifier[currentData] = ide... | def reload(self, cascadeObjects=True):
"""
reload - Reload this object from the database, overriding any local changes and merging in any updates.
@param cascadeObjects <bool> Default True. If True, foreign-linked objects will be reloaded if their values have changed
since last save/... |
def load_transaction_config(self, file_id):
"""
Loads the configuration fields file for the id.
:param file_id: the id for the field
:return: the fields configuration
"""
if file_id not in self._transaction_configs:
self._transaction_configs[file_id] = self._... | def function[load_transaction_config, parameter[self, file_id]]:
constant[
Loads the configuration fields file for the id.
:param file_id: the id for the field
:return: the fields configuration
]
if compare[name[file_id] <ast.NotIn object at 0x7da2590d7190> name[self]._t... | keyword[def] identifier[load_transaction_config] ( identifier[self] , identifier[file_id] ):
literal[string]
keyword[if] identifier[file_id] keyword[not] keyword[in] identifier[self] . identifier[_transaction_configs] :
identifier[self] . identifier[_transaction_configs] [ identifi... | def load_transaction_config(self, file_id):
"""
Loads the configuration fields file for the id.
:param file_id: the id for the field
:return: the fields configuration
"""
if file_id not in self._transaction_configs:
self._transaction_configs[file_id] = self._reader.read_... |
def refine_hbonds_ldon(self, all_hbonds, salt_lneg, salt_pneg):
"""Refine selection of hydrogen bonds. Do not allow groups which already form salt bridges to form H-Bonds."""
i_set = {}
for hbond in all_hbonds:
i_set[hbond] = False
for salt in salt_pneg:
p... | def function[refine_hbonds_ldon, parameter[self, all_hbonds, salt_lneg, salt_pneg]]:
constant[Refine selection of hydrogen bonds. Do not allow groups which already form salt bridges to form H-Bonds.]
variable[i_set] assign[=] dictionary[[], []]
for taget[name[hbond]] in starred[name[all_hbonds]]... | keyword[def] identifier[refine_hbonds_ldon] ( identifier[self] , identifier[all_hbonds] , identifier[salt_lneg] , identifier[salt_pneg] ):
literal[string]
identifier[i_set] ={}
keyword[for] identifier[hbond] keyword[in] identifier[all_hbonds] :
identifier[i_set] [ identifie... | def refine_hbonds_ldon(self, all_hbonds, salt_lneg, salt_pneg):
"""Refine selection of hydrogen bonds. Do not allow groups which already form salt bridges to form H-Bonds."""
i_set = {}
for hbond in all_hbonds:
i_set[hbond] = False
for salt in salt_pneg:
(protidx, ligidx) = ([at.... |
def draw(self, points, target=None, **kwargs):
"""
Called from the fit method, this method creates the canvas and
draws the plot on it.
Parameters
----------
kwargs: generic keyword arguments.
"""
# Resolve the labels with the classes
labels = sel... | def function[draw, parameter[self, points, target]]:
constant[
Called from the fit method, this method creates the canvas and
draws the plot on it.
Parameters
----------
kwargs: generic keyword arguments.
]
variable[labels] assign[=] <ast.IfExp object at 0... | keyword[def] identifier[draw] ( identifier[self] , identifier[points] , identifier[target] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[labels] = identifier[self] . identifier[labels] keyword[if] identifier[self] . identifier[labels] keyword[is] keyword[not] k... | def draw(self, points, target=None, **kwargs):
"""
Called from the fit method, this method creates the canvas and
draws the plot on it.
Parameters
----------
kwargs: generic keyword arguments.
"""
# Resolve the labels with the classes
labels = self.labels if s... |
def get(self, metric_id=None, **kwargs):
"""Get metrics
:param int metric_id: Metric ID
:return: Metrics data (:class:`dict`)
Additional named arguments may be passed and are directly transmitted
to API. It is useful to use the API search features.
.. seealso:: https:/... | def function[get, parameter[self, metric_id]]:
constant[Get metrics
:param int metric_id: Metric ID
:return: Metrics data (:class:`dict`)
Additional named arguments may be passed and are directly transmitted
to API. It is useful to use the API search features.
.. seeal... | keyword[def] identifier[get] ( identifier[self] , identifier[metric_id] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[path] = literal[string]
keyword[if] identifier[metric_id] keyword[is] keyword[not] keyword[None] :
identifier[path] += literal[stri... | def get(self, metric_id=None, **kwargs):
"""Get metrics
:param int metric_id: Metric ID
:return: Metrics data (:class:`dict`)
Additional named arguments may be passed and are directly transmitted
to API. It is useful to use the API search features.
.. seealso:: https://doc... |
def add_tween(self, obj, duration = None, easing = None, on_complete = None,
on_update = None, round = False, delay = None, **kwargs):
"""
Add tween for the object to go from current values to set ones.
Example: add_tween(sprite, x = 500, y = 200, duration = 0.4)
... | def function[add_tween, parameter[self, obj, duration, easing, on_complete, on_update, round, delay]]:
constant[
Add tween for the object to go from current values to set ones.
Example: add_tween(sprite, x = 500, y = 200, duration = 0.4)
This will move the sprite to coordinat... | keyword[def] identifier[add_tween] ( identifier[self] , identifier[obj] , identifier[duration] = keyword[None] , identifier[easing] = keyword[None] , identifier[on_complete] = keyword[None] ,
identifier[on_update] = keyword[None] , identifier[round] = keyword[False] , identifier[delay] = keyword[None] ,** identifier... | def add_tween(self, obj, duration=None, easing=None, on_complete=None, on_update=None, round=False, delay=None, **kwargs):
"""
Add tween for the object to go from current values to set ones.
Example: add_tween(sprite, x = 500, y = 200, duration = 0.4)
This will move the sprite to... |
def type(value):
"""string: property name in which to store the computed transform
value.
The valid transform types are as follows:
'array', 'copy', 'cross', 'facet', 'filter', 'flatten', 'fold',
'formula', 'slice', 'sort', 'stats', 'truncate', 'unique', 'window',
'zip',... | def function[type, parameter[value]]:
constant[string: property name in which to store the computed transform
value.
The valid transform types are as follows:
'array', 'copy', 'cross', 'facet', 'filter', 'flatten', 'fold',
'formula', 'slice', 'sort', 'stats', 'truncate', 'unique... | keyword[def] identifier[type] ( identifier[value] ):
literal[string]
identifier[valid_transforms] = identifier[frozenset] ([
literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ,
literal[string] , literal[string] , literal[string] , literal[str... | def type(value):
"""string: property name in which to store the computed transform
value.
The valid transform types are as follows:
'array', 'copy', 'cross', 'facet', 'filter', 'flatten', 'fold',
'formula', 'slice', 'sort', 'stats', 'truncate', 'unique', 'window',
'zip', 'fo... |
def elliconstraint(self, x, cfac=1e8, tough=True, cond=1e6):
"""ellipsoid test objective function with "constraints" """
N = len(x)
f = sum(cond**(np.arange(N)[-1::-1] / (N - 1)) * x**2)
cvals = (x[0] + 1,
x[0] + 1 + 100 * x[1],
x[0] + 1 - 100 * x[1])
... | def function[elliconstraint, parameter[self, x, cfac, tough, cond]]:
constant[ellipsoid test objective function with "constraints" ]
variable[N] assign[=] call[name[len], parameter[name[x]]]
variable[f] assign[=] call[name[sum], parameter[binary_operation[binary_operation[name[cond] ** binary_op... | keyword[def] identifier[elliconstraint] ( identifier[self] , identifier[x] , identifier[cfac] = literal[int] , identifier[tough] = keyword[True] , identifier[cond] = literal[int] ):
literal[string]
identifier[N] = identifier[len] ( identifier[x] )
identifier[f] = identifier[sum] ( identifi... | def elliconstraint(self, x, cfac=100000000.0, tough=True, cond=1000000.0):
"""ellipsoid test objective function with "constraints" """
N = len(x)
f = sum(cond ** (np.arange(N)[-1::-1] / (N - 1)) * x ** 2)
cvals = (x[0] + 1, x[0] + 1 + 100 * x[1], x[0] + 1 - 100 * x[1])
if tough:
f += cfac * ... |
def month_view(
request,
year,
month,
template='swingtime/monthly_view.html',
queryset=None
):
'''
Render a tradional calendar grid view with temporal navigation variables.
Context parameters:
``today``
the current datetime.datetime value
``calendar``
a list of... | def function[month_view, parameter[request, year, month, template, queryset]]:
constant[
Render a tradional calendar grid view with temporal navigation variables.
Context parameters:
``today``
the current datetime.datetime value
``calendar``
a list of rows containing (day, ite... | keyword[def] identifier[month_view] (
identifier[request] ,
identifier[year] ,
identifier[month] ,
identifier[template] = literal[string] ,
identifier[queryset] = keyword[None]
):
literal[string]
identifier[year] , identifier[month] = identifier[int] ( identifier[year] ), identifier[int] ( identifier... | def month_view(request, year, month, template='swingtime/monthly_view.html', queryset=None):
"""
Render a tradional calendar grid view with temporal navigation variables.
Context parameters:
``today``
the current datetime.datetime value
``calendar``
a list of rows containing (day,... |
def create_instance(self, parent):
"""Create an instance based off this placeholder with some parent"""
self.kwargs['instantiate'] = True
self.kwargs['parent'] = parent
instance = self.cls(*self.args, **self.kwargs)
instance._field_seqno = self._field_seqno
return instanc... | def function[create_instance, parameter[self, parent]]:
constant[Create an instance based off this placeholder with some parent]
call[name[self].kwargs][constant[instantiate]] assign[=] constant[True]
call[name[self].kwargs][constant[parent]] assign[=] name[parent]
variable[instance] ass... | keyword[def] identifier[create_instance] ( identifier[self] , identifier[parent] ):
literal[string]
identifier[self] . identifier[kwargs] [ literal[string] ]= keyword[True]
identifier[self] . identifier[kwargs] [ literal[string] ]= identifier[parent]
identifier[instance] = ident... | def create_instance(self, parent):
"""Create an instance based off this placeholder with some parent"""
self.kwargs['instantiate'] = True
self.kwargs['parent'] = parent
instance = self.cls(*self.args, **self.kwargs)
instance._field_seqno = self._field_seqno
return instance |
def toUnicode(data, encoding=DEFAULT_ENCODING):
"""
Converts the inputted data to unicode format.
:param data | <str> || <unicode> || <iterable>
:return <unicode> || <iterable>
"""
if isinstance(data, unicode_type):
return data
if isinstance(data, bytes_type):
... | def function[toUnicode, parameter[data, encoding]]:
constant[
Converts the inputted data to unicode format.
:param data | <str> || <unicode> || <iterable>
:return <unicode> || <iterable>
]
if call[name[isinstance], parameter[name[data], name[unicode_type]]] begin[:]
... | keyword[def] identifier[toUnicode] ( identifier[data] , identifier[encoding] = identifier[DEFAULT_ENCODING] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[data] , identifier[unicode_type] ):
keyword[return] identifier[data]
keyword[if] identifier[isinstance] ( identif... | def toUnicode(data, encoding=DEFAULT_ENCODING):
"""
Converts the inputted data to unicode format.
:param data | <str> || <unicode> || <iterable>
:return <unicode> || <iterable>
"""
if isinstance(data, unicode_type):
return data # depends on [control=['if'], data=[]]
... |
def write_output(self, data, filename=None, args=None):
"""Write log data to a file with one JSON object per line"""
if args:
if not args.linejson:
return 0
if not filename: filename = args.linejson
entrylist = []
for entry in data['entries']:
... | def function[write_output, parameter[self, data, filename, args]]:
constant[Write log data to a file with one JSON object per line]
if name[args] begin[:]
if <ast.UnaryOp object at 0x7da2047e9270> begin[:]
return[constant[0]]
if <ast.UnaryOp object at 0x7da2047e9000> ... | keyword[def] identifier[write_output] ( identifier[self] , identifier[data] , identifier[filename] = keyword[None] , identifier[args] = keyword[None] ):
literal[string]
keyword[if] identifier[args] :
keyword[if] keyword[not] identifier[args] . identifier[linejson] :
... | def write_output(self, data, filename=None, args=None):
"""Write log data to a file with one JSON object per line"""
if args:
if not args.linejson:
return 0 # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]]
if not filename:
filename = args.linejson ... |
def set_threadlocal(self, **values):
"""Set current thread's logging context to specified `values`"""
with self._lock:
self._ensure_threadlocal()
self._tpayload.context = values | def function[set_threadlocal, parameter[self]]:
constant[Set current thread's logging context to specified `values`]
with name[self]._lock begin[:]
call[name[self]._ensure_threadlocal, parameter[]]
name[self]._tpayload.context assign[=] name[values] | keyword[def] identifier[set_threadlocal] ( identifier[self] ,** identifier[values] ):
literal[string]
keyword[with] identifier[self] . identifier[_lock] :
identifier[self] . identifier[_ensure_threadlocal] ()
identifier[self] . identifier[_tpayload] . identifier[context] ... | def set_threadlocal(self, **values):
"""Set current thread's logging context to specified `values`"""
with self._lock:
self._ensure_threadlocal()
self._tpayload.context = values # depends on [control=['with'], data=[]] |
def upload_applications(self, metadata, category=None):
"""
Mimics get starter-kit and wizard functionality to create components
Note: may create component duplicates, not idempotent
:type metadata: str
:type category: Category
:param metadata: url to meta.yml
:pa... | def function[upload_applications, parameter[self, metadata, category]]:
constant[
Mimics get starter-kit and wizard functionality to create components
Note: may create component duplicates, not idempotent
:type metadata: str
:type category: Category
:param metadata: url t... | keyword[def] identifier[upload_applications] ( identifier[self] , identifier[metadata] , identifier[category] = keyword[None] ):
literal[string]
identifier[upload_json] = identifier[self] . identifier[_router] . identifier[get_upload] ( identifier[params] = identifier[dict] ( identifier[metadataUrl... | def upload_applications(self, metadata, category=None):
"""
Mimics get starter-kit and wizard functionality to create components
Note: may create component duplicates, not idempotent
:type metadata: str
:type category: Category
:param metadata: url to meta.yml
:param ... |
def send_wsgi_response(status, headers, content, start_response,
cors_handler=None):
"""Dump reformatted response to CGI start_response.
This calls start_response and returns the response body.
Args:
status: A string containing the HTTP status code to send.
headers: A list of (hea... | def function[send_wsgi_response, parameter[status, headers, content, start_response, cors_handler]]:
constant[Dump reformatted response to CGI start_response.
This calls start_response and returns the response body.
Args:
status: A string containing the HTTP status code to send.
headers: A list of... | keyword[def] identifier[send_wsgi_response] ( identifier[status] , identifier[headers] , identifier[content] , identifier[start_response] ,
identifier[cors_handler] = keyword[None] ):
literal[string]
keyword[if] identifier[cors_handler] :
identifier[cors_handler] . identifier[update_headers] ( identifie... | def send_wsgi_response(status, headers, content, start_response, cors_handler=None):
"""Dump reformatted response to CGI start_response.
This calls start_response and returns the response body.
Args:
status: A string containing the HTTP status code to send.
headers: A list of (header, value) tuples, t... |
def get_target_transcript(self,min_intron=1):
"""Get the mapping of to the target strand
:returns: Transcript mapped to target
:rtype: Transcript
"""
if min_intron < 1:
sys.stderr.write("ERROR minimum intron should be 1 base or longer\n")
sys.exit()
#tx = Transcript()
rngs = [... | def function[get_target_transcript, parameter[self, min_intron]]:
constant[Get the mapping of to the target strand
:returns: Transcript mapped to target
:rtype: Transcript
]
if compare[name[min_intron] less[<] constant[1]] begin[:]
call[name[sys].stderr.write, parameter[con... | keyword[def] identifier[get_target_transcript] ( identifier[self] , identifier[min_intron] = literal[int] ):
literal[string]
keyword[if] identifier[min_intron] < literal[int] :
identifier[sys] . identifier[stderr] . identifier[write] ( literal[string] )
identifier[sys] . identifier[exit] ()
... | def get_target_transcript(self, min_intron=1):
"""Get the mapping of to the target strand
:returns: Transcript mapped to target
:rtype: Transcript
"""
if min_intron < 1:
sys.stderr.write('ERROR minimum intron should be 1 base or longer\n')
sys.exit() # depends on [control=['if'], ... |
def use(self, profile):
"""Define a new default profile."""
if not isinstance(profile, (KnownProfiles, ProfileDefinition)):
raise ValueError("Can only set as default a ProfileDefinition or a KnownProfiles")
type(self).profile = profile | def function[use, parameter[self, profile]]:
constant[Define a new default profile.]
if <ast.UnaryOp object at 0x7da204346860> begin[:]
<ast.Raise object at 0x7da204346020>
call[name[type], parameter[name[self]]].profile assign[=] name[profile] | keyword[def] identifier[use] ( identifier[self] , identifier[profile] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[profile] ,( identifier[KnownProfiles] , identifier[ProfileDefinition] )):
keyword[raise] identifier[ValueError] ( literal[string] )
... | def use(self, profile):
"""Define a new default profile."""
if not isinstance(profile, (KnownProfiles, ProfileDefinition)):
raise ValueError('Can only set as default a ProfileDefinition or a KnownProfiles') # depends on [control=['if'], data=[]]
type(self).profile = profile |
def parse():
"""Parse the command line inputs and execute the subcommand."""
# Build the list of subcommand modules
modnames = [mod for (_, mod, _)
in pkgutil.iter_modules(payu.subcommands.__path__,
prefix=payu.subcommands.__name__ + '.')
... | def function[parse, parameter[]]:
constant[Parse the command line inputs and execute the subcommand.]
variable[modnames] assign[=] <ast.ListComp object at 0x7da1b0492620>
variable[subcmds] assign[=] <ast.ListComp object at 0x7da1b0492740>
variable[parser] assign[=] call[name[argparse].Ar... | keyword[def] identifier[parse] ():
literal[string]
identifier[modnames] =[ identifier[mod] keyword[for] ( identifier[_] , identifier[mod] , identifier[_] )
keyword[in] identifier[pkgutil] . identifier[iter_modules] ( identifier[payu] . identifier[subcommands] . identifier[__path__] ,
iden... | def parse():
"""Parse the command line inputs and execute the subcommand."""
# Build the list of subcommand modules
modnames = [mod for (_, mod, _) in pkgutil.iter_modules(payu.subcommands.__path__, prefix=payu.subcommands.__name__ + '.') if mod.endswith('_cmd')]
subcmds = [importlib.import_module(mod) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.