code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def verify_sns_subscription_current(self, subscription_arn, topic_name,
function_arn):
# type: (str, str, str) -> bool
"""Verify a subscription arn matches the topic and function name.
Given a subscription arn, verify that the associated topic name
... | def function[verify_sns_subscription_current, parameter[self, subscription_arn, topic_name, function_arn]]:
constant[Verify a subscription arn matches the topic and function name.
Given a subscription arn, verify that the associated topic name
and function arn match up to the parameters passed ... | keyword[def] identifier[verify_sns_subscription_current] ( identifier[self] , identifier[subscription_arn] , identifier[topic_name] ,
identifier[function_arn] ):
literal[string]
identifier[sns_client] = identifier[self] . identifier[_client] ( literal[string] )
keyword[try] :
... | def verify_sns_subscription_current(self, subscription_arn, topic_name, function_arn):
# type: (str, str, str) -> bool
'Verify a subscription arn matches the topic and function name.\n\n Given a subscription arn, verify that the associated topic name\n and function arn match up to the parameters p... |
def nest(*content):
"""Define a delimited list by enumerating each element of the list."""
if len(content) == 0:
raise ValueError('no arguments supplied')
return And([LPF, content[0]] + list(itt.chain.from_iterable(zip(itt.repeat(C), content[1:]))) + [RPF]) | def function[nest, parameter[]]:
constant[Define a delimited list by enumerating each element of the list.]
if compare[call[name[len], parameter[name[content]]] equal[==] constant[0]] begin[:]
<ast.Raise object at 0x7da20c76ea10>
return[call[name[And], parameter[binary_operation[binary_opera... | keyword[def] identifier[nest] (* identifier[content] ):
literal[string]
keyword[if] identifier[len] ( identifier[content] )== literal[int] :
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[return] identifier[And] ([ identifier[LPF] , identifier[content] [ literal[int] ]]+... | def nest(*content):
"""Define a delimited list by enumerating each element of the list."""
if len(content) == 0:
raise ValueError('no arguments supplied') # depends on [control=['if'], data=[]]
return And([LPF, content[0]] + list(itt.chain.from_iterable(zip(itt.repeat(C), content[1:]))) + [RPF]) |
def _set_kap_custom_profile(self, v, load=False):
"""
Setter method for kap_custom_profile, mapped from YANG variable /hardware/custom_profile/kap_custom_profile (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_kap_custom_profile is considered as a private
meth... | def function[_set_kap_custom_profile, parameter[self, v, load]]:
constant[
Setter method for kap_custom_profile, mapped from YANG variable /hardware/custom_profile/kap_custom_profile (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_kap_custom_profile is conside... | keyword[def] identifier[_set_kap_custom_profile] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
... | def _set_kap_custom_profile(self, v, load=False):
"""
Setter method for kap_custom_profile, mapped from YANG variable /hardware/custom_profile/kap_custom_profile (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_kap_custom_profile is considered as a private
meth... |
def isclose(a, b, align=False, rtol=1.e-5, atol=1.e-8):
"""Compare two molecules for numerical equality.
Args:
a (Cartesian):
b (Cartesian):
align (bool): a and b are
prealigned along their principal axes of inertia and moved to their
barycenters before comparing... | def function[isclose, parameter[a, b, align, rtol, atol]]:
constant[Compare two molecules for numerical equality.
Args:
a (Cartesian):
b (Cartesian):
align (bool): a and b are
prealigned along their principal axes of inertia and moved to their
barycenters bef... | keyword[def] identifier[isclose] ( identifier[a] , identifier[b] , identifier[align] = keyword[False] , identifier[rtol] = literal[int] , identifier[atol] = literal[int] ):
literal[string]
identifier[coords] =[ literal[string] , literal[string] , literal[string] ]
keyword[if] keyword[not] ( identifie... | def isclose(a, b, align=False, rtol=1e-05, atol=1e-08):
"""Compare two molecules for numerical equality.
Args:
a (Cartesian):
b (Cartesian):
align (bool): a and b are
prealigned along their principal axes of inertia and moved to their
barycenters before comparing... |
def mutual_information(reference_intervals, reference_labels,
estimated_intervals, estimated_labels,
frame_size=0.1):
"""Frame-clustering segmentation: mutual information metrics.
Examples
--------
>>> (ref_intervals,
... ref_labels) = mir_eval.io.load... | def function[mutual_information, parameter[reference_intervals, reference_labels, estimated_intervals, estimated_labels, frame_size]]:
constant[Frame-clustering segmentation: mutual information metrics.
Examples
--------
>>> (ref_intervals,
... ref_labels) = mir_eval.io.load_labeled_intervals(... | keyword[def] identifier[mutual_information] ( identifier[reference_intervals] , identifier[reference_labels] ,
identifier[estimated_intervals] , identifier[estimated_labels] ,
identifier[frame_size] = literal[int] ):
literal[string]
identifier[validate_structure] ( identifier[reference_intervals] , ident... | def mutual_information(reference_intervals, reference_labels, estimated_intervals, estimated_labels, frame_size=0.1):
"""Frame-clustering segmentation: mutual information metrics.
Examples
--------
>>> (ref_intervals,
... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')
>>> (est_int... |
def remote(self, func, *args, xfer_func=None, **kwargs):
"""Calls func with the indicated args on the micropython board."""
global HAS_BUFFER
HAS_BUFFER = self.has_buffer
if hasattr(func, 'extra_funcs'):
func_name = func.name
func_lines = []
for extra_func i... | def function[remote, parameter[self, func]]:
constant[Calls func with the indicated args on the micropython board.]
<ast.Global object at 0x7da2054a7d30>
variable[HAS_BUFFER] assign[=] name[self].has_buffer
if call[name[hasattr], parameter[name[func], constant[extra_funcs]]] begin[:]
... | keyword[def] identifier[remote] ( identifier[self] , identifier[func] ,* identifier[args] , identifier[xfer_func] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[global] identifier[HAS_BUFFER]
identifier[HAS_BUFFER] = identifier[self] . identifier[has_buffer]
... | def remote(self, func, *args, xfer_func=None, **kwargs):
"""Calls func with the indicated args on the micropython board."""
global HAS_BUFFER
HAS_BUFFER = self.has_buffer
if hasattr(func, 'extra_funcs'):
func_name = func.name
func_lines = []
for extra_func in func.extra_funcs:
... |
def position_result_list(change_list):
"""
Returns a template which iters through the models and appends a new
position column.
"""
result = result_list(change_list)
# Remove sortable attributes
for x in range(0, len(result['result_headers'])):
result['result_headers'][x]['sorted'] ... | def function[position_result_list, parameter[change_list]]:
constant[
Returns a template which iters through the models and appends a new
position column.
]
variable[result] assign[=] call[name[result_list], parameter[name[change_list]]]
for taget[name[x]] in starred[call[name[range... | keyword[def] identifier[position_result_list] ( identifier[change_list] ):
literal[string]
identifier[result] = identifier[result_list] ( identifier[change_list] )
keyword[for] identifier[x] keyword[in] identifier[range] ( literal[int] , identifier[len] ( identifier[result] [ literal[string] ]... | def position_result_list(change_list):
"""
Returns a template which iters through the models and appends a new
position column.
"""
result = result_list(change_list)
# Remove sortable attributes
for x in range(0, len(result['result_headers'])):
result['result_headers'][x]['sorted'] ... |
def get_attachment_content(self, file_name, repository_id, pull_request_id, project=None, **kwargs):
"""GetAttachmentContent.
[Preview API] Get the file content of a pull request attachment.
:param str file_name: The name of the attachment.
:param str repository_id: The repository ID of ... | def function[get_attachment_content, parameter[self, file_name, repository_id, pull_request_id, project]]:
constant[GetAttachmentContent.
[Preview API] Get the file content of a pull request attachment.
:param str file_name: The name of the attachment.
:param str repository_id: The repos... | keyword[def] identifier[get_attachment_content] ( identifier[self] , identifier[file_name] , identifier[repository_id] , identifier[pull_request_id] , identifier[project] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[route_values] ={}
keyword[if] identifier[project]... | def get_attachment_content(self, file_name, repository_id, pull_request_id, project=None, **kwargs):
"""GetAttachmentContent.
[Preview API] Get the file content of a pull request attachment.
:param str file_name: The name of the attachment.
:param str repository_id: The repository ID of the ... |
def sequence(self, other, exclude_list_fields=None):
"""Return a copy of this object which combines all the fields common to both `self` and `other`.
List fields will be concatenated.
The return type of this method is the type of `self` (or whatever `.copy()` returns), but the
`other` argument can be ... | def function[sequence, parameter[self, other, exclude_list_fields]]:
constant[Return a copy of this object which combines all the fields common to both `self` and `other`.
List fields will be concatenated.
The return type of this method is the type of `self` (or whatever `.copy()` returns), but the
... | keyword[def] identifier[sequence] ( identifier[self] , identifier[other] , identifier[exclude_list_fields] = keyword[None] ):
literal[string]
identifier[exclude_list_fields] = identifier[frozenset] ( identifier[exclude_list_fields] keyword[or] [])
identifier[overwrite_kwargs] ={}
identifier[non... | def sequence(self, other, exclude_list_fields=None):
"""Return a copy of this object which combines all the fields common to both `self` and `other`.
List fields will be concatenated.
The return type of this method is the type of `self` (or whatever `.copy()` returns), but the
`other` argument can be ... |
def delete_download_task(self, task_id, **kwargs):
"""删除离线下载任务.
:param task_id: 要删除的任务ID号。
:type task_id: str
:return: requests.Response
"""
data = {
'task_id': task_id,
}
url = 'http://{0}/rest/2.0/services/cloud_dl'.format(BAIDUPAN_SERVER)
... | def function[delete_download_task, parameter[self, task_id]]:
constant[删除离线下载任务.
:param task_id: 要删除的任务ID号。
:type task_id: str
:return: requests.Response
]
variable[data] assign[=] dictionary[[<ast.Constant object at 0x7da18fe91990>], [<ast.Name object at 0x7da18fe926e0>... | keyword[def] identifier[delete_download_task] ( identifier[self] , identifier[task_id] ,** identifier[kwargs] ):
literal[string]
identifier[data] ={
literal[string] : identifier[task_id] ,
}
identifier[url] = literal[string] . identifier[format] ( identifier[BAIDUPAN_SERV... | def delete_download_task(self, task_id, **kwargs):
"""删除离线下载任务.
:param task_id: 要删除的任务ID号。
:type task_id: str
:return: requests.Response
"""
data = {'task_id': task_id}
url = 'http://{0}/rest/2.0/services/cloud_dl'.format(BAIDUPAN_SERVER)
return self._request('services/c... |
def __make_user_api_request(server_context, target_ids, api, container_path=None):
"""
Make a request to the LabKey User Controller
:param server_context: A LabKey server context. See utils.create_server_context.
:param target_ids: Array of User ids to affect
:param api: action to take
:param co... | def function[__make_user_api_request, parameter[server_context, target_ids, api, container_path]]:
constant[
Make a request to the LabKey User Controller
:param server_context: A LabKey server context. See utils.create_server_context.
:param target_ids: Array of User ids to affect
:param api: ac... | keyword[def] identifier[__make_user_api_request] ( identifier[server_context] , identifier[target_ids] , identifier[api] , identifier[container_path] = keyword[None] ):
literal[string]
identifier[url] = identifier[server_context] . identifier[build_url] ( identifier[user_controller] , identifier[api] , ide... | def __make_user_api_request(server_context, target_ids, api, container_path=None):
"""
Make a request to the LabKey User Controller
:param server_context: A LabKey server context. See utils.create_server_context.
:param target_ids: Array of User ids to affect
:param api: action to take
:param co... |
def optimize(self, optimizer=None, start=None, messages=False, max_iters=1000, ipython_notebook=True, clear_after_finish=False, **kwargs):
"""
Optimize the model using self.log_likelihood and self.log_likelihood_gradient, as well as self.priors.
kwargs are passed to the optimizer. They can be:
... | def function[optimize, parameter[self, optimizer, start, messages, max_iters, ipython_notebook, clear_after_finish]]:
constant[
Optimize the model using self.log_likelihood and self.log_likelihood_gradient, as well as self.priors.
kwargs are passed to the optimizer. They can be:
:param... | keyword[def] identifier[optimize] ( identifier[self] , identifier[optimizer] = keyword[None] , identifier[start] = keyword[None] , identifier[messages] = keyword[False] , identifier[max_iters] = literal[int] , identifier[ipython_notebook] = keyword[True] , identifier[clear_after_finish] = keyword[False] ,** identifie... | def optimize(self, optimizer=None, start=None, messages=False, max_iters=1000, ipython_notebook=True, clear_after_finish=False, **kwargs):
"""
Optimize the model using self.log_likelihood and self.log_likelihood_gradient, as well as self.priors.
kwargs are passed to the optimizer. They can be:
... |
def write(self):
'''Write this Scrims commands to its path'''
if self.path is None:
raise Exception('Scrim.path is None')
dirname = os.path.dirname(os.path.abspath(self.path))
if not os.path.exists(dirname):
try:
os.makedirs(dirname)
... | def function[write, parameter[self]]:
constant[Write this Scrims commands to its path]
if compare[name[self].path is constant[None]] begin[:]
<ast.Raise object at 0x7da20c6c7f40>
variable[dirname] assign[=] call[name[os].path.dirname, parameter[call[name[os].path.abspath, parameter[name[... | keyword[def] identifier[write] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[path] keyword[is] keyword[None] :
keyword[raise] identifier[Exception] ( literal[string] )
identifier[dirname] = identifier[os] . identifier[path] . identifier[... | def write(self):
"""Write this Scrims commands to its path"""
if self.path is None:
raise Exception('Scrim.path is None') # depends on [control=['if'], data=[]]
dirname = os.path.dirname(os.path.abspath(self.path))
if not os.path.exists(dirname):
try:
os.makedirs(dirname) #... |
def absent(name=None, images=None, force=False):
'''
Ensure that an image is absent from the Minion. Image names can be
specified either using ``repo:tag`` notation, or just the repo name (in
which case a tag of ``latest`` is assumed).
images
Run this state on more than one image at a time.... | def function[absent, parameter[name, images, force]]:
constant[
Ensure that an image is absent from the Minion. Image names can be
specified either using ``repo:tag`` notation, or just the repo name (in
which case a tag of ``latest`` is assumed).
images
Run this state on more than one i... | keyword[def] identifier[absent] ( identifier[name] = keyword[None] , identifier[images] = keyword[None] , identifier[force] = keyword[False] ):
literal[string]
identifier[ret] ={ literal[string] : identifier[name] ,
literal[string] :{},
literal[string] : keyword[False] ,
literal[string] : li... | def absent(name=None, images=None, force=False):
"""
Ensure that an image is absent from the Minion. Image names can be
specified either using ``repo:tag`` notation, or just the repo name (in
which case a tag of ``latest`` is assumed).
images
Run this state on more than one image at a time.... |
def init_app(self, app):
"""
Initializes a Flask object `app`: binds the HTML prettifying with
app.after_request.
:param app: The Flask application object.
"""
app.config.setdefault('PRETTIFY', False)
if app.config['PRETTIFY']:
app.after_request(self... | def function[init_app, parameter[self, app]]:
constant[
Initializes a Flask object `app`: binds the HTML prettifying with
app.after_request.
:param app: The Flask application object.
]
call[name[app].config.setdefault, parameter[constant[PRETTIFY], constant[False]]]
... | keyword[def] identifier[init_app] ( identifier[self] , identifier[app] ):
literal[string]
identifier[app] . identifier[config] . identifier[setdefault] ( literal[string] , keyword[False] )
keyword[if] identifier[app] . identifier[config] [ literal[string] ]:
identifier[app] ... | def init_app(self, app):
"""
Initializes a Flask object `app`: binds the HTML prettifying with
app.after_request.
:param app: The Flask application object.
"""
app.config.setdefault('PRETTIFY', False)
if app.config['PRETTIFY']:
app.after_request(self._prettify_respon... |
def human_and_00(X, y, model_generator, method_name):
""" AND (false/false)
This tests how well a feature attribution method agrees with human intuition
for an AND operation combined with linear effects. This metric deals
specifically with the question of credit allocation for the following function
... | def function[human_and_00, parameter[X, y, model_generator, method_name]]:
constant[ AND (false/false)
This tests how well a feature attribution method agrees with human intuition
for an AND operation combined with linear effects. This metric deals
specifically with the question of credit allocatio... | keyword[def] identifier[human_and_00] ( identifier[X] , identifier[y] , identifier[model_generator] , identifier[method_name] ):
literal[string]
keyword[return] identifier[_human_and] ( identifier[X] , identifier[model_generator] , identifier[method_name] , keyword[False] , keyword[False] ) | def human_and_00(X, y, model_generator, method_name):
""" AND (false/false)
This tests how well a feature attribution method agrees with human intuition
for an AND operation combined with linear effects. This metric deals
specifically with the question of credit allocation for the following function
... |
def disable_napp(mgr):
"""Disable a NApp."""
if mgr.is_enabled():
LOG.info(' Disabling...')
mgr.disable()
LOG.info(' Disabled.')
else:
LOG.error(" NApp isn't enabled.") | def function[disable_napp, parameter[mgr]]:
constant[Disable a NApp.]
if call[name[mgr].is_enabled, parameter[]] begin[:]
call[name[LOG].info, parameter[constant[ Disabling...]]]
call[name[mgr].disable, parameter[]]
call[name[LOG].info, parameter[constant... | keyword[def] identifier[disable_napp] ( identifier[mgr] ):
literal[string]
keyword[if] identifier[mgr] . identifier[is_enabled] ():
identifier[LOG] . identifier[info] ( literal[string] )
identifier[mgr] . identifier[disable] ()
identifier[LOG] . identifier[in... | def disable_napp(mgr):
"""Disable a NApp."""
if mgr.is_enabled():
LOG.info(' Disabling...')
mgr.disable()
LOG.info(' Disabled.') # depends on [control=['if'], data=[]]
else:
LOG.error(" NApp isn't enabled.") |
def threeD_seismplot(stations, nodes, size=(10.5, 7.5), **kwargs):
"""
Plot seismicity and stations in a 3D, movable, zoomable space.
Uses matplotlibs Axes3D package.
:type stations: list
:param stations: list of one tuple per station of (lat, long, elevation), \
with up positive.
:typ... | def function[threeD_seismplot, parameter[stations, nodes, size]]:
constant[
Plot seismicity and stations in a 3D, movable, zoomable space.
Uses matplotlibs Axes3D package.
:type stations: list
:param stations: list of one tuple per station of (lat, long, elevation), with up positive.
... | keyword[def] identifier[threeD_seismplot] ( identifier[stations] , identifier[nodes] , identifier[size] =( literal[int] , literal[int] ),** identifier[kwargs] ):
literal[string]
keyword[import] identifier[matplotlib] . identifier[pyplot] keyword[as] identifier[plt]
keyword[from] identifier[mpl_to... | def threeD_seismplot(stations, nodes, size=(10.5, 7.5), **kwargs):
"""
Plot seismicity and stations in a 3D, movable, zoomable space.
Uses matplotlibs Axes3D package.
:type stations: list
:param stations: list of one tuple per station of (lat, long, elevation), with up positive.
:type ... |
def track_time(self, name, description='', max_rows=None):
"""
Create a Timer object in the Tracker.
"""
if name in self._tables:
raise TableConflictError(name)
if max_rows is None:
max_rows = AnonymousUsageTracker.MAX_ROWS_PER_TABLE
self.register_... | def function[track_time, parameter[self, name, description, max_rows]]:
constant[
Create a Timer object in the Tracker.
]
if compare[name[name] in name[self]._tables] begin[:]
<ast.Raise object at 0x7da1b09e83d0>
if compare[name[max_rows] is constant[None]] begin[:]
... | keyword[def] identifier[track_time] ( identifier[self] , identifier[name] , identifier[description] = literal[string] , identifier[max_rows] = keyword[None] ):
literal[string]
keyword[if] identifier[name] keyword[in] identifier[self] . identifier[_tables] :
keyword[raise] identifie... | def track_time(self, name, description='', max_rows=None):
"""
Create a Timer object in the Tracker.
"""
if name in self._tables:
raise TableConflictError(name) # depends on [control=['if'], data=['name']]
if max_rows is None:
max_rows = AnonymousUsageTracker.MAX_ROWS_PER_TA... |
def ceil(self, value, *args):
""" Ceil number
args:
value (str): target
returns:
str
"""
n, u = utility.analyze_number(value)
return utility.with_unit(int(math.ceil(n)), u) | def function[ceil, parameter[self, value]]:
constant[ Ceil number
args:
value (str): target
returns:
str
]
<ast.Tuple object at 0x7da1affc3730> assign[=] call[name[utility].analyze_number, parameter[name[value]]]
return[call[name[utility].with_unit, pa... | keyword[def] identifier[ceil] ( identifier[self] , identifier[value] ,* identifier[args] ):
literal[string]
identifier[n] , identifier[u] = identifier[utility] . identifier[analyze_number] ( identifier[value] )
keyword[return] identifier[utility] . identifier[with_unit] ( identifier[int] ... | def ceil(self, value, *args):
""" Ceil number
args:
value (str): target
returns:
str
"""
(n, u) = utility.analyze_number(value)
return utility.with_unit(int(math.ceil(n)), u) |
def get_attributes(file, *, attributes=None, mime_type=None,
force_document=False, voice_note=False, video_note=False,
supports_streaming=False):
"""
Get a list of attributes for the given file and
the mime type as a tuple ([attribute], mime_type).
"""
# Note: `... | def function[get_attributes, parameter[file]]:
constant[
Get a list of attributes for the given file and
the mime type as a tuple ([attribute], mime_type).
]
variable[name] assign[=] <ast.IfExp object at 0x7da1b2188340>
if compare[name[mime_type] is constant[None]] begin[:]
... | keyword[def] identifier[get_attributes] ( identifier[file] ,*, identifier[attributes] = keyword[None] , identifier[mime_type] = keyword[None] ,
identifier[force_document] = keyword[False] , identifier[voice_note] = keyword[False] , identifier[video_note] = keyword[False] ,
identifier[supports_streaming] = keyword[F... | def get_attributes(file, *, attributes=None, mime_type=None, force_document=False, voice_note=False, video_note=False, supports_streaming=False):
"""
Get a list of attributes for the given file and
the mime type as a tuple ([attribute], mime_type).
"""
# Note: ``file.name`` works for :tl:`InputFile`... |
def requestExec(self, commandLine):
"""Request execution of :commandLine: and return a deferred reply.
"""
data = common.NS(commandLine)
return self.sendRequest('exec', data, wantReply=True) | def function[requestExec, parameter[self, commandLine]]:
constant[Request execution of :commandLine: and return a deferred reply.
]
variable[data] assign[=] call[name[common].NS, parameter[name[commandLine]]]
return[call[name[self].sendRequest, parameter[constant[exec], name[data]]]] | keyword[def] identifier[requestExec] ( identifier[self] , identifier[commandLine] ):
literal[string]
identifier[data] = identifier[common] . identifier[NS] ( identifier[commandLine] )
keyword[return] identifier[self] . identifier[sendRequest] ( literal[string] , identifier[data] , identif... | def requestExec(self, commandLine):
"""Request execution of :commandLine: and return a deferred reply.
"""
data = common.NS(commandLine)
return self.sendRequest('exec', data, wantReply=True) |
def short_codes(self):
"""
Access the short_codes
:returns: twilio.rest.api.v2010.account.short_code.ShortCodeList
:rtype: twilio.rest.api.v2010.account.short_code.ShortCodeList
"""
if self._short_codes is None:
self._short_codes = ShortCodeList(self._version... | def function[short_codes, parameter[self]]:
constant[
Access the short_codes
:returns: twilio.rest.api.v2010.account.short_code.ShortCodeList
:rtype: twilio.rest.api.v2010.account.short_code.ShortCodeList
]
if compare[name[self]._short_codes is constant[None]] begin[:]
... | keyword[def] identifier[short_codes] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_short_codes] keyword[is] keyword[None] :
identifier[self] . identifier[_short_codes] = identifier[ShortCodeList] ( identifier[self] . identifier[_version] , identifi... | def short_codes(self):
"""
Access the short_codes
:returns: twilio.rest.api.v2010.account.short_code.ShortCodeList
:rtype: twilio.rest.api.v2010.account.short_code.ShortCodeList
"""
if self._short_codes is None:
self._short_codes = ShortCodeList(self._version, account_si... |
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
... | def function[db_remove, parameter[name]]:
constant[
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
]
if <ast.UnaryOp object at 0x7da1b21e2650> begin[:]
call[name[log].info, parameter[constant[DB '%... | keyword[def] identifier[db_remove] ( identifier[name] ,** identifier[connection_args] ):
literal[string]
keyword[if] keyword[not] identifier[db_exists] ( identifier[name] ,** identifier[connection_args] ):
identifier[log] . identifier[info] ( literal[string] , identifier[name] )
ke... | def db_remove(name, **connection_args):
"""
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
"""
# check if db exists
if not db_exists(name, **connection_args):
log.info("DB '%s' does not exist", name)
r... |
def package(self, output=None):
"""
Only build the package
"""
# Make sure we're in a venv.
self.check_venv()
# force not to delete the local zip
self.override_stage_config_setting('delete_local_zip', False)
# Execute the prebuild script
if self.p... | def function[package, parameter[self, output]]:
constant[
Only build the package
]
call[name[self].check_venv, parameter[]]
call[name[self].override_stage_config_setting, parameter[constant[delete_local_zip], constant[False]]]
if name[self].prebuild_script begin[:]
... | keyword[def] identifier[package] ( identifier[self] , identifier[output] = keyword[None] ):
literal[string]
identifier[self] . identifier[check_venv] ()
identifier[self] . identifier[override_stage_config_setting] ( literal[string] , keyword[False] )
ke... | def package(self, output=None):
"""
Only build the package
"""
# Make sure we're in a venv.
self.check_venv()
# force not to delete the local zip
self.override_stage_config_setting('delete_local_zip', False)
# Execute the prebuild script
if self.prebuild_script:
self.... |
def get_partition(self, db_name, tbl_name, part_vals):
"""
Parameters:
- db_name
- tbl_name
- part_vals
"""
self.send_get_partition(db_name, tbl_name, part_vals)
return self.recv_get_partition() | def function[get_partition, parameter[self, db_name, tbl_name, part_vals]]:
constant[
Parameters:
- db_name
- tbl_name
- part_vals
]
call[name[self].send_get_partition, parameter[name[db_name], name[tbl_name], name[part_vals]]]
return[call[name[self].recv_get_partition, parame... | keyword[def] identifier[get_partition] ( identifier[self] , identifier[db_name] , identifier[tbl_name] , identifier[part_vals] ):
literal[string]
identifier[self] . identifier[send_get_partition] ( identifier[db_name] , identifier[tbl_name] , identifier[part_vals] )
keyword[return] identifier[self] .... | def get_partition(self, db_name, tbl_name, part_vals):
"""
Parameters:
- db_name
- tbl_name
- part_vals
"""
self.send_get_partition(db_name, tbl_name, part_vals)
return self.recv_get_partition() |
def _remove_bcbiovm_path():
"""Avoid referencing minimal bcbio_nextgen in bcbio_vm installation.
"""
cur_path = os.path.dirname(os.path.realpath(sys.executable))
paths = os.environ["PATH"].split(":")
if cur_path in paths:
paths.remove(cur_path)
os.environ["PATH"] = ":".join(paths) | def function[_remove_bcbiovm_path, parameter[]]:
constant[Avoid referencing minimal bcbio_nextgen in bcbio_vm installation.
]
variable[cur_path] assign[=] call[name[os].path.dirname, parameter[call[name[os].path.realpath, parameter[name[sys].executable]]]]
variable[paths] assign[=] call[call... | keyword[def] identifier[_remove_bcbiovm_path] ():
literal[string]
identifier[cur_path] = identifier[os] . identifier[path] . identifier[dirname] ( identifier[os] . identifier[path] . identifier[realpath] ( identifier[sys] . identifier[executable] ))
identifier[paths] = identifier[os] . identifier[envi... | def _remove_bcbiovm_path():
"""Avoid referencing minimal bcbio_nextgen in bcbio_vm installation.
"""
cur_path = os.path.dirname(os.path.realpath(sys.executable))
paths = os.environ['PATH'].split(':')
if cur_path in paths:
paths.remove(cur_path)
os.environ['PATH'] = ':'.join(paths) #... |
def vrrp_shutdown(app, instance_name):
"""shutdown the instance.
"""
shutdown_request = vrrp_event.EventVRRPShutdownRequest(instance_name)
app.send_event(vrrp_event.VRRP_MANAGER_NAME, shutdown_request) | def function[vrrp_shutdown, parameter[app, instance_name]]:
constant[shutdown the instance.
]
variable[shutdown_request] assign[=] call[name[vrrp_event].EventVRRPShutdownRequest, parameter[name[instance_name]]]
call[name[app].send_event, parameter[name[vrrp_event].VRRP_MANAGER_NAME, name[shu... | keyword[def] identifier[vrrp_shutdown] ( identifier[app] , identifier[instance_name] ):
literal[string]
identifier[shutdown_request] = identifier[vrrp_event] . identifier[EventVRRPShutdownRequest] ( identifier[instance_name] )
identifier[app] . identifier[send_event] ( identifier[vrrp_event] . identif... | def vrrp_shutdown(app, instance_name):
"""shutdown the instance.
"""
shutdown_request = vrrp_event.EventVRRPShutdownRequest(instance_name)
app.send_event(vrrp_event.VRRP_MANAGER_NAME, shutdown_request) |
def _munge(self, value):
"""
Possibly munges a value.
"""
if self.translations and value in self.translations:
value = self.translations[value]
return value | def function[_munge, parameter[self, value]]:
constant[
Possibly munges a value.
]
if <ast.BoolOp object at 0x7da1b0a4cb50> begin[:]
variable[value] assign[=] call[name[self].translations][name[value]]
return[name[value]] | keyword[def] identifier[_munge] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[self] . identifier[translations] keyword[and] identifier[value] keyword[in] identifier[self] . identifier[translations] :
identifier[value] = identifier[self] . identif... | def _munge(self, value):
"""
Possibly munges a value.
"""
if self.translations and value in self.translations:
value = self.translations[value] # depends on [control=['if'], data=[]]
return value |
def file_signature(file_name: str) -> Optional[Tuple]:
"""
Return an identity signature for file name
:param file_name: name of file
:return: mode, size, last modified time if file exists, otherwise none
"""
try:
st = os.stat(file_name)
except FileNotFoundError:
return None
... | def function[file_signature, parameter[file_name]]:
constant[
Return an identity signature for file name
:param file_name: name of file
:return: mode, size, last modified time if file exists, otherwise none
]
<ast.Try object at 0x7da20c6c6b90>
return[tuple[[<ast.Call object at 0x7da18c4c... | keyword[def] identifier[file_signature] ( identifier[file_name] : identifier[str] )-> identifier[Optional] [ identifier[Tuple] ]:
literal[string]
keyword[try] :
identifier[st] = identifier[os] . identifier[stat] ( identifier[file_name] )
keyword[except] identifier[FileNotFoundError] :
... | def file_signature(file_name: str) -> Optional[Tuple]:
"""
Return an identity signature for file name
:param file_name: name of file
:return: mode, size, last modified time if file exists, otherwise none
"""
try:
st = os.stat(file_name) # depends on [control=['try'], data=[]]
except... |
def pending_confirmations(self):
"""Return all published messages that have yet to be acked, nacked, or
returned.
:return: [(int, Published)]
"""
return sorted([(idx, msg)
for idx, msg in enumerate(self.published_messages)
if not ms... | def function[pending_confirmations, parameter[self]]:
constant[Return all published messages that have yet to be acked, nacked, or
returned.
:return: [(int, Published)]
]
return[call[name[sorted], parameter[<ast.ListComp object at 0x7da204960190>]]] | keyword[def] identifier[pending_confirmations] ( identifier[self] ):
literal[string]
keyword[return] identifier[sorted] ([( identifier[idx] , identifier[msg] )
keyword[for] identifier[idx] , identifier[msg] keyword[in] identifier[enumerate] ( identifier[self] . identifier[published_mes... | def pending_confirmations(self):
"""Return all published messages that have yet to be acked, nacked, or
returned.
:return: [(int, Published)]
"""
return sorted([(idx, msg) for (idx, msg) in enumerate(self.published_messages) if not msg.future.done()], key=lambda x: x[1].delivery_tag) |
def clean(self):
"""
Always raise the default error message, because we don't
care what they entered here.
"""
raise forms.ValidationError(
self.error_messages['invalid_login'],
code='invalid_login',
params={'username': self.username_field.verb... | def function[clean, parameter[self]]:
constant[
Always raise the default error message, because we don't
care what they entered here.
]
<ast.Raise object at 0x7da18c4cd540> | keyword[def] identifier[clean] ( identifier[self] ):
literal[string]
keyword[raise] identifier[forms] . identifier[ValidationError] (
identifier[self] . identifier[error_messages] [ literal[string] ],
identifier[code] = literal[string] ,
identifier[params] ={ literal[str... | def clean(self):
"""
Always raise the default error message, because we don't
care what they entered here.
"""
raise forms.ValidationError(self.error_messages['invalid_login'], code='invalid_login', params={'username': self.username_field.verbose_name}) |
def watch(self, path, recursive=False):
"""Watch for files in a directory and apply normalizations.
Watch for new or changed files in a directory and apply
normalizations over them.
Args:
path: Path to the directory.
recursive: Whether to find files recursively ... | def function[watch, parameter[self, path, recursive]]:
constant[Watch for files in a directory and apply normalizations.
Watch for new or changed files in a directory and apply
normalizations over them.
Args:
path: Path to the directory.
recursive: Whether to fi... | keyword[def] identifier[watch] ( identifier[self] , identifier[path] , identifier[recursive] = keyword[False] ):
literal[string]
identifier[self] . identifier[_logger] . identifier[info] ( literal[string] , identifier[path] )
identifier[handler] = identifier[FileHandler] ( identifier[self... | def watch(self, path, recursive=False):
"""Watch for files in a directory and apply normalizations.
Watch for new or changed files in a directory and apply
normalizations over them.
Args:
path: Path to the directory.
recursive: Whether to find files recursively or n... |
def synfind(args):
"""
%prog synfind all.last *.bed
Prepare input for SynFind.
"""
p = OptionParser(synfind.__doc__)
opts, args = p.parse_args(args)
if len(args) < 2:
sys.exit(not p.print_help())
lastfile = args[0]
bedfiles = args[1:]
fp = open(lastfile)
filteredla... | def function[synfind, parameter[args]]:
constant[
%prog synfind all.last *.bed
Prepare input for SynFind.
]
variable[p] assign[=] call[name[OptionParser], parameter[name[synfind].__doc__]]
<ast.Tuple object at 0x7da1b09eb6d0> assign[=] call[name[p].parse_args, parameter[name[args]]]... | keyword[def] identifier[synfind] ( identifier[args] ):
literal[string]
identifier[p] = identifier[OptionParser] ( identifier[synfind] . identifier[__doc__] )
identifier[opts] , identifier[args] = identifier[p] . identifier[parse_args] ( identifier[args] )
keyword[if] identifier[len] ( identifie... | def synfind(args):
"""
%prog synfind all.last *.bed
Prepare input for SynFind.
"""
p = OptionParser(synfind.__doc__)
(opts, args) = p.parse_args(args)
if len(args) < 2:
sys.exit(not p.print_help()) # depends on [control=['if'], data=[]]
lastfile = args[0]
bedfiles = args[1:... |
def generate_term(self, **kwargs):
"""Method generates a rdflib.Term based on kwargs"""
term_map = kwargs.pop('term_map')
if hasattr(term_map, "termType") and\
term_map.termType == NS_MGR.rr.BlankNode.rdflib:
return rdflib.BNode()
if not hasattr(term_map, 'datatyp... | def function[generate_term, parameter[self]]:
constant[Method generates a rdflib.Term based on kwargs]
variable[term_map] assign[=] call[name[kwargs].pop, parameter[constant[term_map]]]
if <ast.BoolOp object at 0x7da1b2344460> begin[:]
return[call[name[rdflib].BNode, parameter[]]]
... | keyword[def] identifier[generate_term] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[term_map] = identifier[kwargs] . identifier[pop] ( literal[string] )
keyword[if] identifier[hasattr] ( identifier[term_map] , literal[string] ) keyword[and] identifier[term_map]... | def generate_term(self, **kwargs):
"""Method generates a rdflib.Term based on kwargs"""
term_map = kwargs.pop('term_map')
if hasattr(term_map, 'termType') and term_map.termType == NS_MGR.rr.BlankNode.rdflib:
return rdflib.BNode() # depends on [control=['if'], data=[]]
if not hasattr(term_map, '... |
def fmtdeglat (radians, norm='raise', precision=2, seps='::'):
"""Format a latitudinal angle as sexagesimal degrees in a string.
Arguments are:
radians
The angle, in radians.
norm (default "raise")
The normalization mode, used for angles outside of the standard range
of -π/2 to π/2. ... | def function[fmtdeglat, parameter[radians, norm, precision, seps]]:
constant[Format a latitudinal angle as sexagesimal degrees in a string.
Arguments are:
radians
The angle, in radians.
norm (default "raise")
The normalization mode, used for angles outside of the standard range
o... | keyword[def] identifier[fmtdeglat] ( identifier[radians] , identifier[norm] = literal[string] , identifier[precision] = literal[int] , identifier[seps] = literal[string] ):
literal[string]
keyword[if] identifier[norm] == literal[string] :
keyword[pass]
keyword[elif] identifier[norm] == lit... | def fmtdeglat(radians, norm='raise', precision=2, seps='::'):
"""Format a latitudinal angle as sexagesimal degrees in a string.
Arguments are:
radians
The angle, in radians.
norm (default "raise")
The normalization mode, used for angles outside of the standard range
of -π/2 to π/2. I... |
def create_wsgi_request(event, server_name='apigw'):
"""Create a wsgi environment from an apigw request.
"""
path = urllib.url2pathname(event['path'])
script_name = (
event['headers']['Host'].endswith('.amazonaws.com') and
event['requestContext']['stage'] or '').encode('utf8')
query ... | def function[create_wsgi_request, parameter[event, server_name]]:
constant[Create a wsgi environment from an apigw request.
]
variable[path] assign[=] call[name[urllib].url2pathname, parameter[call[name[event]][constant[path]]]]
variable[script_name] assign[=] call[<ast.BoolOp object at 0x7d... | keyword[def] identifier[create_wsgi_request] ( identifier[event] , identifier[server_name] = literal[string] ):
literal[string]
identifier[path] = identifier[urllib] . identifier[url2pathname] ( identifier[event] [ literal[string] ])
identifier[script_name] =(
identifier[event] [ literal[string] ... | def create_wsgi_request(event, server_name='apigw'):
"""Create a wsgi environment from an apigw request.
"""
path = urllib.url2pathname(event['path'])
script_name = (event['headers']['Host'].endswith('.amazonaws.com') and event['requestContext']['stage'] or '').encode('utf8')
query = event['queryStr... |
def visit_attribute(self, node, parent):
"""visit an Attribute node by returning a fresh instance of it"""
context = self._get_context(node)
if context == astroid.Del:
# FIXME : maybe we should reintroduce and visit_delattr ?
# for instance, deactivating assign_ctx
... | def function[visit_attribute, parameter[self, node, parent]]:
constant[visit an Attribute node by returning a fresh instance of it]
variable[context] assign[=] call[name[self]._get_context, parameter[name[node]]]
if compare[name[context] equal[==] name[astroid].Del] begin[:]
vari... | keyword[def] identifier[visit_attribute] ( identifier[self] , identifier[node] , identifier[parent] ):
literal[string]
identifier[context] = identifier[self] . identifier[_get_context] ( identifier[node] )
keyword[if] identifier[context] == identifier[astroid] . identifier[Del] :
... | def visit_attribute(self, node, parent):
"""visit an Attribute node by returning a fresh instance of it"""
context = self._get_context(node)
if context == astroid.Del:
# FIXME : maybe we should reintroduce and visit_delattr ?
# for instance, deactivating assign_ctx
newnode = nodes.De... |
def logos(check):
"""Validate logo files. Specifying no check will validate all logos"""
valid_checks = get_valid_integrations()
if check:
if check in valid_checks:
checks = [check]
else:
echo_info('{} is not an integration.'.format(check))
return
el... | def function[logos, parameter[check]]:
constant[Validate logo files. Specifying no check will validate all logos]
variable[valid_checks] assign[=] call[name[get_valid_integrations], parameter[]]
if name[check] begin[:]
if compare[name[check] in name[valid_checks]] begin[:]
... | keyword[def] identifier[logos] ( identifier[check] ):
literal[string]
identifier[valid_checks] = identifier[get_valid_integrations] ()
keyword[if] identifier[check] :
keyword[if] identifier[check] keyword[in] identifier[valid_checks] :
identifier[checks] =[ identifier[check... | def logos(check):
"""Validate logo files. Specifying no check will validate all logos"""
valid_checks = get_valid_integrations()
if check:
if check in valid_checks:
checks = [check] # depends on [control=['if'], data=['check']]
else:
echo_info('{} is not an integrati... |
def model_attr(attr_name):
"""
Creates a getter that will drop the current value
and retrieve the model's attribute with specified name.
@param attr_name: the name of an attribute belonging to the model.
@type attr_name: str
"""
def model_attr(_value, context, **_params):
value = ge... | def function[model_attr, parameter[attr_name]]:
constant[
Creates a getter that will drop the current value
and retrieve the model's attribute with specified name.
@param attr_name: the name of an attribute belonging to the model.
@type attr_name: str
]
def function[model_attr, param... | keyword[def] identifier[model_attr] ( identifier[attr_name] ):
literal[string]
keyword[def] identifier[model_attr] ( identifier[_value] , identifier[context] ,** identifier[_params] ):
identifier[value] = identifier[getattr] ( identifier[context] [ literal[string] ], identifier[attr_name] )
... | def model_attr(attr_name):
"""
Creates a getter that will drop the current value
and retrieve the model's attribute with specified name.
@param attr_name: the name of an attribute belonging to the model.
@type attr_name: str
"""
def model_attr(_value, context, **_params):
value = ge... |
def show_schemas(schemaname):
"""
Show anchore document schemas.
"""
ecode = 0
try:
schemas = {}
schema_dir = os.path.join(contexts['anchore_config']['pkg_dir'], 'schemas')
for f in os.listdir(schema_dir):
sdata = {}
try:
with open(os.... | def function[show_schemas, parameter[schemaname]]:
constant[
Show anchore document schemas.
]
variable[ecode] assign[=] constant[0]
<ast.Try object at 0x7da1b0b6e1d0>
call[name[sys].exit, parameter[name[ecode]]] | keyword[def] identifier[show_schemas] ( identifier[schemaname] ):
literal[string]
identifier[ecode] = literal[int]
keyword[try] :
identifier[schemas] ={}
identifier[schema_dir] = identifier[os] . identifier[path] . identifier[join] ( identifier[contexts] [ literal[string] ][ litera... | def show_schemas(schemaname):
"""
Show anchore document schemas.
"""
ecode = 0
try:
schemas = {}
schema_dir = os.path.join(contexts['anchore_config']['pkg_dir'], 'schemas')
for f in os.listdir(schema_dir):
sdata = {}
try:
with open(os.p... |
def close(i, j, tolerance):
"""
check two float values are within a bound of one another
"""
return i <= j + tolerance and i >= j - tolerance | def function[close, parameter[i, j, tolerance]]:
constant[
check two float values are within a bound of one another
]
return[<ast.BoolOp object at 0x7da20e954ee0>] | keyword[def] identifier[close] ( identifier[i] , identifier[j] , identifier[tolerance] ):
literal[string]
keyword[return] identifier[i] <= identifier[j] + identifier[tolerance] keyword[and] identifier[i] >= identifier[j] - identifier[tolerance] | def close(i, j, tolerance):
"""
check two float values are within a bound of one another
"""
return i <= j + tolerance and i >= j - tolerance |
async def zremrangebyscore(self, name, min, max):
"""
Remove all elements in the sorted set ``name`` with scores
between ``min`` and ``max``. Returns the number of elements removed.
"""
return await self.execute_command('ZREMRANGEBYSCORE', name, min, max) | <ast.AsyncFunctionDef object at 0x7da1b07cf550> | keyword[async] keyword[def] identifier[zremrangebyscore] ( identifier[self] , identifier[name] , identifier[min] , identifier[max] ):
literal[string]
keyword[return] keyword[await] identifier[self] . identifier[execute_command] ( literal[string] , identifier[name] , identifier[min] , identifier[... | async def zremrangebyscore(self, name, min, max):
"""
Remove all elements in the sorted set ``name`` with scores
between ``min`` and ``max``. Returns the number of elements removed.
"""
return await self.execute_command('ZREMRANGEBYSCORE', name, min, max) |
def GetForwardedIps(self, interface, interface_ip=None):
"""Retrieve the list of configured forwarded IP addresses.
Args:
interface: string, the output device to query.
interface_ip: string, current interface ip address.
Returns:
list, the IP address strings.
"""
try:
ips =... | def function[GetForwardedIps, parameter[self, interface, interface_ip]]:
constant[Retrieve the list of configured forwarded IP addresses.
Args:
interface: string, the output device to query.
interface_ip: string, current interface ip address.
Returns:
list, the IP address strings.
... | keyword[def] identifier[GetForwardedIps] ( identifier[self] , identifier[interface] , identifier[interface_ip] = keyword[None] ):
literal[string]
keyword[try] :
identifier[ips] = identifier[netifaces] . identifier[ifaddresses] ( identifier[interface] )
identifier[ips] = identifier[ips] [ iden... | def GetForwardedIps(self, interface, interface_ip=None):
"""Retrieve the list of configured forwarded IP addresses.
Args:
interface: string, the output device to query.
interface_ip: string, current interface ip address.
Returns:
list, the IP address strings.
"""
try:
ips... |
def alias_composition(self, composition_id, alias_id):
"""Adds an ``Id`` to a ``Composition`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Composition`` is determined by the
provider. The new ``Id`` is an alias to the primary ``Id``. If
the alias is a pointer t... | def function[alias_composition, parameter[self, composition_id, alias_id]]:
constant[Adds an ``Id`` to a ``Composition`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Composition`` is determined by the
provider. The new ``Id`` is an alias to the primary ``Id``. If
... | keyword[def] identifier[alias_composition] ( identifier[self] , identifier[composition_id] , identifier[alias_id] ):
literal[string]
identifier[self] . identifier[_alias_id] ( identifier[primary_id] = identifier[composition_id] , identifier[equivalent_id] = identifier[alias_id] ) | def alias_composition(self, composition_id, alias_id):
"""Adds an ``Id`` to a ``Composition`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Composition`` is determined by the
provider. The new ``Id`` is an alias to the primary ``Id``. If
the alias is a pointer to an... |
def check_python_version():
"""Check if the currently running Python version is new enough."""
# Required due to multiple with statements on one line
req_version = (2, 7)
cur_version = sys.version_info
if cur_version >= req_version:
print("Python version... %sOK%s (found %s, requires %s)" %
... | def function[check_python_version, parameter[]]:
constant[Check if the currently running Python version is new enough.]
variable[req_version] assign[=] tuple[[<ast.Constant object at 0x7da1b28504f0>, <ast.Constant object at 0x7da1b2852ad0>]]
variable[cur_version] assign[=] name[sys].version_info... | keyword[def] identifier[check_python_version] ():
literal[string]
identifier[req_version] =( literal[int] , literal[int] )
identifier[cur_version] = identifier[sys] . identifier[version_info]
keyword[if] identifier[cur_version] >= identifier[req_version] :
identifier[print] ( lite... | def check_python_version():
"""Check if the currently running Python version is new enough."""
# Required due to multiple with statements on one line
req_version = (2, 7)
cur_version = sys.version_info
if cur_version >= req_version:
print('Python version... %sOK%s (found %s, requires %s)' % ... |
def main():
"""
NAME
odp_spn_magic.py
DESCRIPTION
converts ODP's Molspin's .spn format files to magic_measurements format files
SYNTAX
odp_spn_magic.py [command line options]
OPTIONS
-h: prints the help message and quits.
-f FILE: specify .spn format input ... | def function[main, parameter[]]:
constant[
NAME
odp_spn_magic.py
DESCRIPTION
converts ODP's Molspin's .spn format files to magic_measurements format files
SYNTAX
odp_spn_magic.py [command line options]
OPTIONS
-h: prints the help message and quits.
-f F... | keyword[def] identifier[main] ():
literal[string]
identifier[noave] = literal[int]
identifier[methcode] , identifier[inst] = literal[string] , literal[string]
identifier[phi] , identifier[theta] , identifier[peakfield] , identifier[labfield] = literal[int] , literal[int] , literal[int] , l... | def main():
"""
NAME
odp_spn_magic.py
DESCRIPTION
converts ODP's Molspin's .spn format files to magic_measurements format files
SYNTAX
odp_spn_magic.py [command line options]
OPTIONS
-h: prints the help message and quits.
-f FILE: specify .spn format input ... |
def knn_initialize(
X,
missing_mask,
verbose=False,
min_dist=1e-6,
max_dist_multiplier=1e6):
"""
Fill X with NaN values if necessary, construct the n_samples x n_samples
distance matrix and set the self-distance of each row to infinity.
Returns contents of X laid... | def function[knn_initialize, parameter[X, missing_mask, verbose, min_dist, max_dist_multiplier]]:
constant[
Fill X with NaN values if necessary, construct the n_samples x n_samples
distance matrix and set the self-distance of each row to infinity.
Returns contents of X laid out in row-major, the di... | keyword[def] identifier[knn_initialize] (
identifier[X] ,
identifier[missing_mask] ,
identifier[verbose] = keyword[False] ,
identifier[min_dist] = literal[int] ,
identifier[max_dist_multiplier] = literal[int] ):
literal[string]
identifier[X_row_major] = identifier[X] . identifier[copy] ( literal[strin... | def knn_initialize(X, missing_mask, verbose=False, min_dist=1e-06, max_dist_multiplier=1000000.0):
"""
Fill X with NaN values if necessary, construct the n_samples x n_samples
distance matrix and set the self-distance of each row to infinity.
Returns contents of X laid out in row-major, the distance ma... |
def from_df(cls, df_long, df_short):
"""
Builds TripleOrbitPopulation from DataFrame
``DataFrame`` objects must be of appropriate form to pass
to :func:`OrbitPopulation.from_df`.
:param df_long, df_short:
:class:`pandas.DataFrame` objects to pass to
:fun... | def function[from_df, parameter[cls, df_long, df_short]]:
constant[
Builds TripleOrbitPopulation from DataFrame
``DataFrame`` objects must be of appropriate form to pass
to :func:`OrbitPopulation.from_df`.
:param df_long, df_short:
:class:`pandas.DataFrame` objects ... | keyword[def] identifier[from_df] ( identifier[cls] , identifier[df_long] , identifier[df_short] ):
literal[string]
identifier[pop] = identifier[cls] ( literal[int] , literal[int] , literal[int] , literal[int] , literal[int] )
identifier[pop] . identifier[orbpop_long] = identifier[OrbitPopu... | def from_df(cls, df_long, df_short):
"""
Builds TripleOrbitPopulation from DataFrame
``DataFrame`` objects must be of appropriate form to pass
to :func:`OrbitPopulation.from_df`.
:param df_long, df_short:
:class:`pandas.DataFrame` objects to pass to
:func:`O... |
def array2mask(cls, array=None, **kwargs):
"""Create a new mask object based on the given |numpy.ndarray|
and return it."""
kwargs['dtype'] = bool
if array is None:
return numpy.ndarray.__new__(cls, 0, **kwargs)
return numpy.asarray(array, **kwargs).view(cls) | def function[array2mask, parameter[cls, array]]:
constant[Create a new mask object based on the given |numpy.ndarray|
and return it.]
call[name[kwargs]][constant[dtype]] assign[=] name[bool]
if compare[name[array] is constant[None]] begin[:]
return[call[name[numpy].ndarray.__new_... | keyword[def] identifier[array2mask] ( identifier[cls] , identifier[array] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= identifier[bool]
keyword[if] identifier[array] keyword[is] keyword[None] :
keyword[return] identifie... | def array2mask(cls, array=None, **kwargs):
"""Create a new mask object based on the given |numpy.ndarray|
and return it."""
kwargs['dtype'] = bool
if array is None:
return numpy.ndarray.__new__(cls, 0, **kwargs) # depends on [control=['if'], data=[]]
return numpy.asarray(array, **kwargs... |
def adjoin(space: int, *lists: Sequence[str]) -> str:
"""Glue together two sets of strings using `space`."""
lengths = [max(map(len, x)) + space for x in lists[:-1]]
# not the last one
lengths.append(max(map(len, lists[-1])))
max_len = max(map(len, lists))
chains = (
itertools.chain(
... | def function[adjoin, parameter[space]]:
constant[Glue together two sets of strings using `space`.]
variable[lengths] assign[=] <ast.ListComp object at 0x7da20e954e80>
call[name[lengths].append, parameter[call[name[max], parameter[call[name[map], parameter[name[len], call[name[lists]][<ast.UnaryO... | keyword[def] identifier[adjoin] ( identifier[space] : identifier[int] ,* identifier[lists] : identifier[Sequence] [ identifier[str] ])-> identifier[str] :
literal[string]
identifier[lengths] =[ identifier[max] ( identifier[map] ( identifier[len] , identifier[x] ))+ identifier[space] keyword[for] identifi... | def adjoin(space: int, *lists: Sequence[str]) -> str:
"""Glue together two sets of strings using `space`."""
lengths = [max(map(len, x)) + space for x in lists[:-1]]
# not the last one
lengths.append(max(map(len, lists[-1])))
max_len = max(map(len, lists))
chains = (itertools.chain((x.ljust(leng... |
def freivalds(A, B, C):
"""Tests matrix product AB=C by Freivalds
:param A: n by n numerical matrix
:param B: same
:param C: same
:returns: False with high probability if AB != C
:complexity:
:math:`O(n^2)`
"""
n = len(A)
x = [randint(0, 1000000) for j in range(n)]
retu... | def function[freivalds, parameter[A, B, C]]:
constant[Tests matrix product AB=C by Freivalds
:param A: n by n numerical matrix
:param B: same
:param C: same
:returns: False with high probability if AB != C
:complexity:
:math:`O(n^2)`
]
variable[n] assign[=] call[name[le... | keyword[def] identifier[freivalds] ( identifier[A] , identifier[B] , identifier[C] ):
literal[string]
identifier[n] = identifier[len] ( identifier[A] )
identifier[x] =[ identifier[randint] ( literal[int] , literal[int] ) keyword[for] identifier[j] keyword[in] identifier[range] ( identifier[n] )]
... | def freivalds(A, B, C):
"""Tests matrix product AB=C by Freivalds
:param A: n by n numerical matrix
:param B: same
:param C: same
:returns: False with high probability if AB != C
:complexity:
:math:`O(n^2)`
"""
n = len(A)
x = [randint(0, 1000000) for j in range(n)]
retu... |
def alignment_chart(data):
"""Make the HighCharts HTML to plot the alignment rates """
keys = OrderedDict()
keys['reads_mapped'] = {'color': '#437bb1', 'name': 'Mapped'}
keys['reads_unmapped'] = {'color': '#b1084c', 'name': 'Unmapped'}
# Config for the plot
plot_conf = {
'id': 'samtools... | def function[alignment_chart, parameter[data]]:
constant[Make the HighCharts HTML to plot the alignment rates ]
variable[keys] assign[=] call[name[OrderedDict], parameter[]]
call[name[keys]][constant[reads_mapped]] assign[=] dictionary[[<ast.Constant object at 0x7da18c4cf100>, <ast.Constant obje... | keyword[def] identifier[alignment_chart] ( identifier[data] ):
literal[string]
identifier[keys] = identifier[OrderedDict] ()
identifier[keys] [ literal[string] ]={ literal[string] : literal[string] , literal[string] : literal[string] }
identifier[keys] [ literal[string] ]={ literal[string] : lite... | def alignment_chart(data):
"""Make the HighCharts HTML to plot the alignment rates """
keys = OrderedDict()
keys['reads_mapped'] = {'color': '#437bb1', 'name': 'Mapped'}
keys['reads_unmapped'] = {'color': '#b1084c', 'name': 'Unmapped'}
# Config for the plot
plot_conf = {'id': 'samtools_alignment... |
def read_indexed(i,flds=None,sclr=None,
gzip='guess', dir='.', vector_norms=True,
keep_xs=False,gettime=False):
'''
A smart indexing reader that reads files by names. Looks for files
like "<dir>/flds<i>.p4<compression>" where dir and the index are
passed, as well as stu... | def function[read_indexed, parameter[i, flds, sclr, gzip, dir, vector_norms, keep_xs, gettime]]:
constant[
A smart indexing reader that reads files by names. Looks for files
like "<dir>/flds<i>.p4<compression>" where dir and the index are
passed, as well as stuff from sclrs and saves them into one
... | keyword[def] identifier[read_indexed] ( identifier[i] , identifier[flds] = keyword[None] , identifier[sclr] = keyword[None] ,
identifier[gzip] = literal[string] , identifier[dir] = literal[string] , identifier[vector_norms] = keyword[True] ,
identifier[keep_xs] = keyword[False] , identifier[gettime] = keyword[False... | def read_indexed(i, flds=None, sclr=None, gzip='guess', dir='.', vector_norms=True, keep_xs=False, gettime=False):
"""
A smart indexing reader that reads files by names. Looks for files
like "<dir>/flds<i>.p4<compression>" where dir and the index are
passed, as well as stuff from sclrs and saves them in... |
def handle_fdid_aliases(module_or_package_name, import_alias_mapping):
"""Returns either None or the handled alias.
Used in add_module.
fdid means from directory import directory.
"""
for key, val in import_alias_mapping.items():
if module_or_package_name == val:
return key
r... | def function[handle_fdid_aliases, parameter[module_or_package_name, import_alias_mapping]]:
constant[Returns either None or the handled alias.
Used in add_module.
fdid means from directory import directory.
]
for taget[tuple[[<ast.Name object at 0x7da1b1e78520>, <ast.Name object at 0x7da1b1e... | keyword[def] identifier[handle_fdid_aliases] ( identifier[module_or_package_name] , identifier[import_alias_mapping] ):
literal[string]
keyword[for] identifier[key] , identifier[val] keyword[in] identifier[import_alias_mapping] . identifier[items] ():
keyword[if] identifier[module_or_package_n... | def handle_fdid_aliases(module_or_package_name, import_alias_mapping):
"""Returns either None or the handled alias.
Used in add_module.
fdid means from directory import directory.
"""
for (key, val) in import_alias_mapping.items():
if module_or_package_name == val:
return key # ... |
def matrix(
m, n, lst,
m_text: list=None,
n_text: list=None):
"""
m: row
n: column
lst: items
>>> print(_matrix(2, 3, [(1, 1), (2, 3)]))
|x| | |
| | |x|
"""
fmt = ""
if n_text:
fmt += " {}\n".format(" ".join(n_text))
for ... | def function[matrix, parameter[m, n, lst, m_text, n_text]]:
constant[
m: row
n: column
lst: items
>>> print(_matrix(2, 3, [(1, 1), (2, 3)]))
|x| | |
| | |x|
]
variable[fmt] assign[=] constant[]
if name[n_text] begin[:]
<ast.AugAssign object at 0x7da1b1495690>... | keyword[def] identifier[matrix] (
identifier[m] , identifier[n] , identifier[lst] ,
identifier[m_text] : identifier[list] = keyword[None] ,
identifier[n_text] : identifier[list] = keyword[None] ):
literal[string]
identifier[fmt] = literal[string]
keyword[if] identifier[n_text] :
... | def matrix(m, n, lst, m_text: list=None, n_text: list=None):
"""
m: row
n: column
lst: items
>>> print(_matrix(2, 3, [(1, 1), (2, 3)]))
|x| | |
| | |x|
"""
fmt = ''
if n_text:
fmt += ' {}\n'.format(' '.join(n_text)) # depends on [control=['if'], data=[]]
for i i... |
def create_signature(cls, method, base, params,
consumer_secret, token_secret=''):
"""
Returns HMAC-SHA1 signature as specified at:
http://oauth.net/core/1.0a/#rfc.section.9.2.
:param str method:
HTTP method of the request to be signed.
:par... | def function[create_signature, parameter[cls, method, base, params, consumer_secret, token_secret]]:
constant[
Returns HMAC-SHA1 signature as specified at:
http://oauth.net/core/1.0a/#rfc.section.9.2.
:param str method:
HTTP method of the request to be signed.
:para... | keyword[def] identifier[create_signature] ( identifier[cls] , identifier[method] , identifier[base] , identifier[params] ,
identifier[consumer_secret] , identifier[token_secret] = literal[string] ):
literal[string]
identifier[base_string] = identifier[_create_base_string] ( identifier[method] , i... | def create_signature(cls, method, base, params, consumer_secret, token_secret=''):
"""
Returns HMAC-SHA1 signature as specified at:
http://oauth.net/core/1.0a/#rfc.section.9.2.
:param str method:
HTTP method of the request to be signed.
:param str base:
Base... |
def get_suitable_date_for_daily_extract(self, date=None, ut=False):
"""
Parameters
----------
date : str
ut : bool
Whether to return the date as a string or as a an int (seconds after epoch).
Returns
-------
Selects suitable date for daily ext... | def function[get_suitable_date_for_daily_extract, parameter[self, date, ut]]:
constant[
Parameters
----------
date : str
ut : bool
Whether to return the date as a string or as a an int (seconds after epoch).
Returns
-------
Selects suitable da... | keyword[def] identifier[get_suitable_date_for_daily_extract] ( identifier[self] , identifier[date] = keyword[None] , identifier[ut] = keyword[False] ):
literal[string]
identifier[daily_trips] = identifier[self] . identifier[get_trip_counts_per_day] ()
identifier[max_daily_trips] = identifi... | def get_suitable_date_for_daily_extract(self, date=None, ut=False):
"""
Parameters
----------
date : str
ut : bool
Whether to return the date as a string or as a an int (seconds after epoch).
Returns
-------
Selects suitable date for daily extract... |
def _get_error_code(self, e):
"""Extract error code from ftp exception"""
try:
matches = self.error_code_pattern.match(str(e))
code = int(matches.group(0))
return code
except ValueError:
return e | def function[_get_error_code, parameter[self, e]]:
constant[Extract error code from ftp exception]
<ast.Try object at 0x7da1b056da20> | keyword[def] identifier[_get_error_code] ( identifier[self] , identifier[e] ):
literal[string]
keyword[try] :
identifier[matches] = identifier[self] . identifier[error_code_pattern] . identifier[match] ( identifier[str] ( identifier[e] ))
identifier[code] = identifier[int]... | def _get_error_code(self, e):
"""Extract error code from ftp exception"""
try:
matches = self.error_code_pattern.match(str(e))
code = int(matches.group(0))
return code # depends on [control=['try'], data=[]]
except ValueError:
return e # depends on [control=['except'], data... |
def excmessage_decorator(description) -> Callable:
"""Wrap a function with |augment_excmessage|.
Function |excmessage_decorator| is a means to apply function
|augment_excmessage| more efficiently. Suppose you would apply
function |augment_excmessage| in a function that adds and returns
to numbers:... | def function[excmessage_decorator, parameter[description]]:
constant[Wrap a function with |augment_excmessage|.
Function |excmessage_decorator| is a means to apply function
|augment_excmessage| more efficiently. Suppose you would apply
function |augment_excmessage| in a function that adds and retu... | keyword[def] identifier[excmessage_decorator] ( identifier[description] )-> identifier[Callable] :
literal[string]
@ identifier[wrapt] . identifier[decorator]
keyword[def] identifier[wrapper] ( identifier[wrapped] , identifier[instance] , identifier[args] , identifier[kwargs] ):
literal[stri... | def excmessage_decorator(description) -> Callable:
"""Wrap a function with |augment_excmessage|.
Function |excmessage_decorator| is a means to apply function
|augment_excmessage| more efficiently. Suppose you would apply
function |augment_excmessage| in a function that adds and returns
to numbers:... |
def create_datastore_write_config(mapreduce_spec):
"""Creates datastore config to use in write operations.
Args:
mapreduce_spec: current mapreduce specification as MapreduceSpec.
Returns:
an instance of datastore_rpc.Configuration to use for all write
operations in the mapreduce.
"""
force_write... | def function[create_datastore_write_config, parameter[mapreduce_spec]]:
constant[Creates datastore config to use in write operations.
Args:
mapreduce_spec: current mapreduce specification as MapreduceSpec.
Returns:
an instance of datastore_rpc.Configuration to use for all write
operations in t... | keyword[def] identifier[create_datastore_write_config] ( identifier[mapreduce_spec] ):
literal[string]
identifier[force_writes] = identifier[parse_bool] ( identifier[mapreduce_spec] . identifier[params] . identifier[get] ( literal[string] , literal[string] ))
keyword[if] identifier[force_writes] :
key... | def create_datastore_write_config(mapreduce_spec):
"""Creates datastore config to use in write operations.
Args:
mapreduce_spec: current mapreduce specification as MapreduceSpec.
Returns:
an instance of datastore_rpc.Configuration to use for all write
operations in the mapreduce.
"""
force_w... |
def add_format(mimetype, format, requires_context=False):
""" Registers a new format to be used in a graph's serialize call
If you've installed an rdflib serializer plugin, use this
to add it to the content negotiation system
Set requires_context=True if this format requires a context-aware graph
"""
... | def function[add_format, parameter[mimetype, format, requires_context]]:
constant[ Registers a new format to be used in a graph's serialize call
If you've installed an rdflib serializer plugin, use this
to add it to the content negotiation system
Set requires_context=True if this format requires ... | keyword[def] identifier[add_format] ( identifier[mimetype] , identifier[format] , identifier[requires_context] = keyword[False] ):
literal[string]
keyword[global] identifier[formats]
keyword[global] identifier[ctxless_mimetypes]
keyword[global] identifier[all_mimetypes]
identifier[formats] [ identifi... | def add_format(mimetype, format, requires_context=False):
""" Registers a new format to be used in a graph's serialize call
If you've installed an rdflib serializer plugin, use this
to add it to the content negotiation system
Set requires_context=True if this format requires a context-aware graph
""... |
def send_templated_mail(tpl, subject, context, to=getattr(settings, 'MIDNIGHT_MAIN_ADMIN_EMAIL', 'admin@example.com')):
"""
Отправляет письмо на основе шаблона
:param tpl: шаблон
:param subject: тема письма
:param context: контекст для рендеринга шаблона
:param to: кому слать письмо
:return:... | def function[send_templated_mail, parameter[tpl, subject, context, to]]:
constant[
Отправляет письмо на основе шаблона
:param tpl: шаблон
:param subject: тема письма
:param context: контекст для рендеринга шаблона
:param to: кому слать письмо
:return:
]
variable[msg_html] ass... | keyword[def] identifier[send_templated_mail] ( identifier[tpl] , identifier[subject] , identifier[context] , identifier[to] = identifier[getattr] ( identifier[settings] , literal[string] , literal[string] )):
literal[string]
identifier[msg_html] = identifier[render_to_string] ( identifier[tpl] ,{ literal[s... | def send_templated_mail(tpl, subject, context, to=getattr(settings, 'MIDNIGHT_MAIN_ADMIN_EMAIL', 'admin@example.com')):
"""
Отправляет письмо на основе шаблона
:param tpl: шаблон
:param subject: тема письма
:param context: контекст для рендеринга шаблона
:param to: кому слать письмо
:return:... |
def merge(*range_lists, **kwargs):
'''
Join given range groups, collapsing their overlapping ranges. If only one
group is given, this method will still fix it (sort and collapsing).
No typecheck is performed, so a valid range group will be any iterable
(or iterator) containing an (start, end) itera... | def function[merge, parameter[]]:
constant[
Join given range groups, collapsing their overlapping ranges. If only one
group is given, this method will still fix it (sort and collapsing).
No typecheck is performed, so a valid range group will be any iterable
(or iterator) containing an (start, e... | keyword[def] identifier[merge] (* identifier[range_lists] ,** identifier[kwargs] ):
literal[string]
identifier[group_class] = identifier[kwargs] . identifier[pop] ( literal[string] , identifier[RangeGroup] )
identifier[range_list] =[
identifier[unirange]
keyword[for] identifier[range_list]... | def merge(*range_lists, **kwargs):
"""
Join given range groups, collapsing their overlapping ranges. If only one
group is given, this method will still fix it (sort and collapsing).
No typecheck is performed, so a valid range group will be any iterable
(or iterator) containing an (start, end) itera... |
def run(self):
"""Start the FTP Server for pulsar search."""
self._log.info('Starting Pulsar Search Interface')
# Instantiate a dummy authorizer for managing 'virtual' users
authorizer = DummyAuthorizer()
# Define a new user having full r/w permissions and a read-only
# ... | def function[run, parameter[self]]:
constant[Start the FTP Server for pulsar search.]
call[name[self]._log.info, parameter[constant[Starting Pulsar Search Interface]]]
variable[authorizer] assign[=] call[name[DummyAuthorizer], parameter[]]
call[name[authorizer].add_user, parameter[call[c... | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_log] . identifier[info] ( literal[string] )
identifier[authorizer] = identifier[DummyAuthorizer] ()
identifier[authorizer] . identifier[add_user] ( identif... | def run(self):
"""Start the FTP Server for pulsar search."""
self._log.info('Starting Pulsar Search Interface')
# Instantiate a dummy authorizer for managing 'virtual' users
authorizer = DummyAuthorizer()
# Define a new user having full r/w permissions and a read-only
# anonymous user
author... |
def insert_tag(tag, before, root):
"""
Insert `tag` before `before` tag if present. If not, insert it into `root`.
Args:
tag (obj): HTMLElement instance.
before (obj): HTMLElement instance.
root (obj): HTMLElement instance.
"""
if not before:
root.childs.append(tag)
... | def function[insert_tag, parameter[tag, before, root]]:
constant[
Insert `tag` before `before` tag if present. If not, insert it into `root`.
Args:
tag (obj): HTMLElement instance.
before (obj): HTMLElement instance.
root (obj): HTMLElement instance.
]
if <ast.UnaryO... | keyword[def] identifier[insert_tag] ( identifier[tag] , identifier[before] , identifier[root] ):
literal[string]
keyword[if] keyword[not] identifier[before] :
identifier[root] . identifier[childs] . identifier[append] ( identifier[tag] )
identifier[tag] . identifier[parent] = identifier... | def insert_tag(tag, before, root):
"""
Insert `tag` before `before` tag if present. If not, insert it into `root`.
Args:
tag (obj): HTMLElement instance.
before (obj): HTMLElement instance.
root (obj): HTMLElement instance.
"""
if not before:
root.childs.append(tag)
... |
def from_json(s):
"""Given a JSON-encoded message, build an object.
"""
d = json.loads(s)
sbp = SBP.from_json_dict(d)
return sbp | def function[from_json, parameter[s]]:
constant[Given a JSON-encoded message, build an object.
]
variable[d] assign[=] call[name[json].loads, parameter[name[s]]]
variable[sbp] assign[=] call[name[SBP].from_json_dict, parameter[name[d]]]
return[name[sbp]] | keyword[def] identifier[from_json] ( identifier[s] ):
literal[string]
identifier[d] = identifier[json] . identifier[loads] ( identifier[s] )
identifier[sbp] = identifier[SBP] . identifier[from_json_dict] ( identifier[d] )
keyword[return] identifier[sbp] | def from_json(s):
"""Given a JSON-encoded message, build an object.
"""
d = json.loads(s)
sbp = SBP.from_json_dict(d)
return sbp |
def create(self, public=False, **kwargs):
"""Creates the device. Attempts to create private devices by default,
but if public is set to true, creates public devices.
You can also set other default properties by passing in the relevant information.
For example, setting a device with the ... | def function[create, parameter[self, public]]:
constant[Creates the device. Attempts to create private devices by default,
but if public is set to true, creates public devices.
You can also set other default properties by passing in the relevant information.
For example, setting a devic... | keyword[def] identifier[create] ( identifier[self] , identifier[public] = keyword[False] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= identifier[public]
identifier[self] . identifier[metadata] = identifier[self] . identifier[db] . identifier[create] ( ... | def create(self, public=False, **kwargs):
"""Creates the device. Attempts to create private devices by default,
but if public is set to true, creates public devices.
You can also set other default properties by passing in the relevant information.
For example, setting a device with the give... |
def cache(func):
"""Caches the HTML returned by the specified function `func`. Caches it in
the user cache determined by the appdirs package.
"""
CACHE_DIR = appdirs.user_cache_dir('sportsref', getpass.getuser())
if not os.path.isdir(CACHE_DIR):
os.makedirs(CACHE_DIR)
@funcutils.wraps(... | def function[cache, parameter[func]]:
constant[Caches the HTML returned by the specified function `func`. Caches it in
the user cache determined by the appdirs package.
]
variable[CACHE_DIR] assign[=] call[name[appdirs].user_cache_dir, parameter[constant[sportsref], call[name[getpass].getuser, p... | keyword[def] identifier[cache] ( identifier[func] ):
literal[string]
identifier[CACHE_DIR] = identifier[appdirs] . identifier[user_cache_dir] ( literal[string] , identifier[getpass] . identifier[getuser] ())
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isdir] ( identifier... | def cache(func):
"""Caches the HTML returned by the specified function `func`. Caches it in
the user cache determined by the appdirs package.
"""
CACHE_DIR = appdirs.user_cache_dir('sportsref', getpass.getuser())
if not os.path.isdir(CACHE_DIR):
os.makedirs(CACHE_DIR) # depends on [control=... |
def isdir(self, path=None, client_kwargs=None, virtual_dir=True,
assume_exists=None):
"""
Return True if path is an existing directory.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
virtual_dir (bool): If True, checks if... | def function[isdir, parameter[self, path, client_kwargs, virtual_dir, assume_exists]]:
constant[
Return True if path is an existing directory.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
virtual_dir (bool): If True, checks if direct... | keyword[def] identifier[isdir] ( identifier[self] , identifier[path] = keyword[None] , identifier[client_kwargs] = keyword[None] , identifier[virtual_dir] = keyword[True] ,
identifier[assume_exists] = keyword[None] ):
literal[string]
identifier[relative] = identifier[self] . identifier[relpath] ( ... | def isdir(self, path=None, client_kwargs=None, virtual_dir=True, assume_exists=None):
"""
Return True if path is an existing directory.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
virtual_dir (bool): If True, checks if directory exists ... |
def activate(self, profile_name=NotSet):
"""
Sets <PROFILE_ROOT>_PROFILE environment variable to the name of the current profile.
"""
if profile_name is NotSet:
profile_name = self.profile_name
self._active_profile_name = profile_name | def function[activate, parameter[self, profile_name]]:
constant[
Sets <PROFILE_ROOT>_PROFILE environment variable to the name of the current profile.
]
if compare[name[profile_name] is name[NotSet]] begin[:]
variable[profile_name] assign[=] name[self].profile_name
... | keyword[def] identifier[activate] ( identifier[self] , identifier[profile_name] = identifier[NotSet] ):
literal[string]
keyword[if] identifier[profile_name] keyword[is] identifier[NotSet] :
identifier[profile_name] = identifier[self] . identifier[profile_name]
identifier[s... | def activate(self, profile_name=NotSet):
"""
Sets <PROFILE_ROOT>_PROFILE environment variable to the name of the current profile.
"""
if profile_name is NotSet:
profile_name = self.profile_name # depends on [control=['if'], data=['profile_name']]
self._active_profile_name = profile_... |
def _match(self, pred):
"""
Helper function to determine if this node matches the given predicate.
"""
if not pred:
return True
# Strip off the [ and ]
pred = pred[1:-1]
if pred.startswith('@'):
# An attribute predicate checks the existence... | def function[_match, parameter[self, pred]]:
constant[
Helper function to determine if this node matches the given predicate.
]
if <ast.UnaryOp object at 0x7da1b004f8e0> begin[:]
return[constant[True]]
variable[pred] assign[=] call[name[pred]][<ast.Slice object at 0x7da1b... | keyword[def] identifier[_match] ( identifier[self] , identifier[pred] ):
literal[string]
keyword[if] keyword[not] identifier[pred] :
keyword[return] keyword[True]
identifier[pred] = identifier[pred] [ literal[int] :- literal[int] ]
keyword[if] identi... | def _match(self, pred):
"""
Helper function to determine if this node matches the given predicate.
"""
if not pred:
return True # depends on [control=['if'], data=[]]
# Strip off the [ and ]
pred = pred[1:-1]
if pred.startswith('@'):
# An attribute predicate checks t... |
def _is_exempt(self, environ):
"""
Returns True if this request's URL starts with one of the
excluded paths.
"""
exemptions = self.exclude_paths
if exemptions:
path = environ.get('PATH_INFO')
for excluded_p in self.exclude_paths:
i... | def function[_is_exempt, parameter[self, environ]]:
constant[
Returns True if this request's URL starts with one of the
excluded paths.
]
variable[exemptions] assign[=] name[self].exclude_paths
if name[exemptions] begin[:]
variable[path] assign[=] call[nam... | keyword[def] identifier[_is_exempt] ( identifier[self] , identifier[environ] ):
literal[string]
identifier[exemptions] = identifier[self] . identifier[exclude_paths]
keyword[if] identifier[exemptions] :
identifier[path] = identifier[environ] . identifier[get] ( literal[stri... | def _is_exempt(self, environ):
"""
Returns True if this request's URL starts with one of the
excluded paths.
"""
exemptions = self.exclude_paths
if exemptions:
path = environ.get('PATH_INFO')
for excluded_p in self.exclude_paths:
if path.startswith(exclude... |
def random_filtered_sources(sources, srcfilter, seed):
"""
:param sources: a list of sources
:param srcfilte: a SourceFilter instance
:param seed: a random seed
:returns: an empty list or a list with a single filtered source
"""
random.seed(seed)
while sources:
src = random.choic... | def function[random_filtered_sources, parameter[sources, srcfilter, seed]]:
constant[
:param sources: a list of sources
:param srcfilte: a SourceFilter instance
:param seed: a random seed
:returns: an empty list or a list with a single filtered source
]
call[name[random].seed, parame... | keyword[def] identifier[random_filtered_sources] ( identifier[sources] , identifier[srcfilter] , identifier[seed] ):
literal[string]
identifier[random] . identifier[seed] ( identifier[seed] )
keyword[while] identifier[sources] :
identifier[src] = identifier[random] . identifier[choice] ( ide... | def random_filtered_sources(sources, srcfilter, seed):
"""
:param sources: a list of sources
:param srcfilte: a SourceFilter instance
:param seed: a random seed
:returns: an empty list or a list with a single filtered source
"""
random.seed(seed)
while sources:
src = random.choic... |
def save(self_or_cls, obj, basename, fmt='auto', key={}, info={}, options=None, **kwargs):
"""
Save a HoloViews object to file, either using an explicitly
supplied format or to the appropriate default.
"""
if info or key:
raise Exception('Renderer does not support sav... | def function[save, parameter[self_or_cls, obj, basename, fmt, key, info, options]]:
constant[
Save a HoloViews object to file, either using an explicitly
supplied format or to the appropriate default.
]
if <ast.BoolOp object at 0x7da18f58c820> begin[:]
<ast.Raise object a... | keyword[def] identifier[save] ( identifier[self_or_cls] , identifier[obj] , identifier[basename] , identifier[fmt] = literal[string] , identifier[key] ={}, identifier[info] ={}, identifier[options] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[info] keyword[or] ... | def save(self_or_cls, obj, basename, fmt='auto', key={}, info={}, options=None, **kwargs):
"""
Save a HoloViews object to file, either using an explicitly
supplied format or to the appropriate default.
"""
if info or key:
raise Exception('Renderer does not support saving metadata... |
def _payload_to_dict(self):
"""When an error status the payload is holding an AsyncException that
is converted to a serializable dict.
"""
if self.status != self.ERROR or not self.payload:
return self.payload
import traceback
return {
"error": se... | def function[_payload_to_dict, parameter[self]]:
constant[When an error status the payload is holding an AsyncException that
is converted to a serializable dict.
]
if <ast.BoolOp object at 0x7da18ede6500> begin[:]
return[name[self].payload]
import module[traceback]
return... | keyword[def] identifier[_payload_to_dict] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[status] != identifier[self] . identifier[ERROR] keyword[or] keyword[not] identifier[self] . identifier[payload] :
keyword[return] identifier[self] . identifier... | def _payload_to_dict(self):
"""When an error status the payload is holding an AsyncException that
is converted to a serializable dict.
"""
if self.status != self.ERROR or not self.payload:
return self.payload # depends on [control=['if'], data=[]]
import traceback
return {'error... |
def get_vnetwork_portgroups_input_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_portgroups = ET.Element("get_vnetwork_portgroups")
config = get_vnetwork_portgroups
input = ET.SubElement(get_vnetwork_portgroups, "input")
... | def function[get_vnetwork_portgroups_input_name, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[get_vnetwork_portgroups] assign[=] call[name[ET].Element, parameter[constant[get_vnetwork_portgroups]]... | keyword[def] identifier[get_vnetwork_portgroups_input_name] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[get_vnetwork_portgroups] = identifier[ET] . identifier[Element] ( literal[string... | def get_vnetwork_portgroups_input_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
get_vnetwork_portgroups = ET.Element('get_vnetwork_portgroups')
config = get_vnetwork_portgroups
input = ET.SubElement(get_vnetwork_portgroups, 'input')
name = ET.SubElement(i... |
def update_viewer_state(rec, context):
"""
Given viewer session information, make sure the session information is
compatible with the current version of the viewers, and if not, update
the session information in-place.
"""
if '_protocol' not in rec:
rec.pop('properties')
rec['... | def function[update_viewer_state, parameter[rec, context]]:
constant[
Given viewer session information, make sure the session information is
compatible with the current version of the viewers, and if not, update
the session information in-place.
]
if compare[constant[_protocol] <ast.NotI... | keyword[def] identifier[update_viewer_state] ( identifier[rec] , identifier[context] ):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[rec] :
identifier[rec] . identifier[pop] ( literal[string] )
identifier[rec] [ literal[string] ]={}
ident... | def update_viewer_state(rec, context):
"""
Given viewer session information, make sure the session information is
compatible with the current version of the viewers, and if not, update
the session information in-place.
"""
if '_protocol' not in rec:
rec.pop('properties')
rec['sta... |
def register(self, collector):
""" Registers a collector"""
if not isinstance(collector, Collector):
raise TypeError(
"Can't register instance, not a valid type of collector")
if collector.name in self.collectors:
raise ValueError("Collector already exist... | def function[register, parameter[self, collector]]:
constant[ Registers a collector]
if <ast.UnaryOp object at 0x7da20e9549d0> begin[:]
<ast.Raise object at 0x7da204564e20>
if compare[name[collector].name in name[self].collectors] begin[:]
<ast.Raise object at 0x7da204564c70>
... | keyword[def] identifier[register] ( identifier[self] , identifier[collector] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[collector] , identifier[Collector] ):
keyword[raise] identifier[TypeError] (
literal[string] )
keyword[... | def register(self, collector):
""" Registers a collector"""
if not isinstance(collector, Collector):
raise TypeError("Can't register instance, not a valid type of collector") # depends on [control=['if'], data=[]]
if collector.name in self.collectors:
raise ValueError('Collector already exi... |
def library_supports_api(library_version, api_version, different_major_breaks_support=True):
"""
Returns whether api_version is supported by given library version.
E. g. library_version (1,3,21) returns True for api_version (1,3,21), (1,3,19), (1,3,'x'), (1,2,'x'), (1, 'x')
False for (1,3,24), (... | def function[library_supports_api, parameter[library_version, api_version, different_major_breaks_support]]:
constant[
Returns whether api_version is supported by given library version.
E. g. library_version (1,3,21) returns True for api_version (1,3,21), (1,3,19), (1,3,'x'), (1,2,'x'), (1, 'x')
... | keyword[def] identifier[library_supports_api] ( identifier[library_version] , identifier[api_version] , identifier[different_major_breaks_support] = keyword[True] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[library_version] ,( identifier[tuple] , identifier[list] ))
keyword... | def library_supports_api(library_version, api_version, different_major_breaks_support=True):
"""
Returns whether api_version is supported by given library version.
E. g. library_version (1,3,21) returns True for api_version (1,3,21), (1,3,19), (1,3,'x'), (1,2,'x'), (1, 'x')
False for (1,3,24), (... |
def list_assignments_for_user(self, user_id, course_id):
"""
List assignments for user.
Returns the list of assignments for the specified user if the current user has rights to view.
See {api:AssignmentsApiController#index List assignments} for valid arguments.
"""
... | def function[list_assignments_for_user, parameter[self, user_id, course_id]]:
constant[
List assignments for user.
Returns the list of assignments for the specified user if the current user has rights to view.
See {api:AssignmentsApiController#index List assignments} for valid arguments... | keyword[def] identifier[list_assignments_for_user] ( identifier[self] , identifier[user_id] , identifier[course_id] ):
literal[string]
identifier[path] ={}
identifier[data] ={}
identifier[params] ={}
literal[string]
identifier[path] [ literal[s... | def list_assignments_for_user(self, user_id, course_id):
"""
List assignments for user.
Returns the list of assignments for the specified user if the current user has rights to view.
See {api:AssignmentsApiController#index List assignments} for valid arguments.
"""
path = {}
... |
def create(provider, instances, opts=None, **kwargs):
'''
Create an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt-run cloud.create my-ec2-config myinstance \
image=ami-1624987f size='t1.micro' ssh_username=ec2-user \
securitygroup=default delvol_on_d... | def function[create, parameter[provider, instances, opts]]:
constant[
Create an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt-run cloud.create my-ec2-config myinstance image=ami-1624987f size='t1.micro' ssh_username=ec2-user securitygroup=default... | keyword[def] identifier[create] ( identifier[provider] , identifier[instances] , identifier[opts] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[client] = identifier[_get_client] ()
keyword[if] identifier[isinstance] ( identifier[opts] , identifier[dict] ):
identifier[c... | def create(provider, instances, opts=None, **kwargs):
"""
Create an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt-run cloud.create my-ec2-config myinstance image=ami-1624987f size='t1.micro' ssh_username=ec2-user securitygroup=default delvol_on_destr... |
def is_attribute(tag, kmip_version=None):
"""
A utility function that checks if the tag is a valid attribute tag.
Args:
tag (enum): A Tags enumeration that may or may not correspond to a
KMIP attribute type.
kmip_version (enum): The KMIPVersion enumeration that should be used
... | def function[is_attribute, parameter[tag, kmip_version]]:
constant[
A utility function that checks if the tag is a valid attribute tag.
Args:
tag (enum): A Tags enumeration that may or may not correspond to a
KMIP attribute type.
kmip_version (enum): The KMIPVersion enumerat... | keyword[def] identifier[is_attribute] ( identifier[tag] , identifier[kmip_version] = keyword[None] ):
literal[string]
identifier[kmip_1_0_attribute_tags] =[
identifier[Tags] . identifier[UNIQUE_IDENTIFIER] ,
identifier[Tags] . identifier[NAME] ,
identifier[Tags] . identifier[OBJECT_TYPE] ,
... | def is_attribute(tag, kmip_version=None):
"""
A utility function that checks if the tag is a valid attribute tag.
Args:
tag (enum): A Tags enumeration that may or may not correspond to a
KMIP attribute type.
kmip_version (enum): The KMIPVersion enumeration that should be used
... |
def tempfile(cls, suffix='', prefix=None, dir=None, text=False):
"""Returns a new temporary file.
The return value is a pair (fd, path) where fd is the file descriptor
returned by :func:`os.open`, and path is a :class:`~rpaths.Path` to it.
:param suffix: If specified, the file name wil... | def function[tempfile, parameter[cls, suffix, prefix, dir, text]]:
constant[Returns a new temporary file.
The return value is a pair (fd, path) where fd is the file descriptor
returned by :func:`os.open`, and path is a :class:`~rpaths.Path` to it.
:param suffix: If specified, the file ... | keyword[def] identifier[tempfile] ( identifier[cls] , identifier[suffix] = literal[string] , identifier[prefix] = keyword[None] , identifier[dir] = keyword[None] , identifier[text] = keyword[False] ):
literal[string]
keyword[if] identifier[prefix] keyword[is] keyword[None] :
identif... | def tempfile(cls, suffix='', prefix=None, dir=None, text=False):
"""Returns a new temporary file.
The return value is a pair (fd, path) where fd is the file descriptor
returned by :func:`os.open`, and path is a :class:`~rpaths.Path` to it.
:param suffix: If specified, the file name will en... |
def hypot(x, y, context=None):
"""
Return the Euclidean norm of x and y, i.e., the square root of the sum of
the squares of x and y.
"""
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_hypot,
(
BigFloat._implicit_convert(x),
BigFloat._i... | def function[hypot, parameter[x, y, context]]:
constant[
Return the Euclidean norm of x and y, i.e., the square root of the sum of
the squares of x and y.
]
return[call[name[_apply_function_in_current_context], parameter[name[BigFloat], name[mpfr].mpfr_hypot, tuple[[<ast.Call object at 0x7da20c... | keyword[def] identifier[hypot] ( identifier[x] , identifier[y] , identifier[context] = keyword[None] ):
literal[string]
keyword[return] identifier[_apply_function_in_current_context] (
identifier[BigFloat] ,
identifier[mpfr] . identifier[mpfr_hypot] ,
(
identifier[BigFloat] . identifier... | def hypot(x, y, context=None):
"""
Return the Euclidean norm of x and y, i.e., the square root of the sum of
the squares of x and y.
"""
return _apply_function_in_current_context(BigFloat, mpfr.mpfr_hypot, (BigFloat._implicit_convert(x), BigFloat._implicit_convert(y)), context) |
def B4PB(self):
''' 判斷是否為四大買點 '''
return self.ckMinsGLI and (self.B1 or self.B2 or self.B3 or self.B4) | def function[B4PB, parameter[self]]:
constant[ 判斷是否為四大買點 ]
return[<ast.BoolOp object at 0x7da1b197ca30>] | keyword[def] identifier[B4PB] ( identifier[self] ):
literal[string]
keyword[return] identifier[self] . identifier[ckMinsGLI] keyword[and] ( identifier[self] . identifier[B1] keyword[or] identifier[self] . identifier[B2] keyword[or] identifier[self] . identifier[B3] keyword[or] identifier[self] . id... | def B4PB(self):
""" 判斷是否為四大買點 """
return self.ckMinsGLI and (self.B1 or self.B2 or self.B3 or self.B4) |
def to_polar(xyz):
"""Convert ``[x y z]`` into spherical coordinates ``(r, theta, phi)``.
``r`` - vector length
``theta`` - angle above (+) or below (-) the xy-plane
``phi`` - angle around the z-axis
The meaning and order of the three return values is designed to
match both ISO 31-11 and the t... | def function[to_polar, parameter[xyz]]:
constant[Convert ``[x y z]`` into spherical coordinates ``(r, theta, phi)``.
``r`` - vector length
``theta`` - angle above (+) or below (-) the xy-plane
``phi`` - angle around the z-axis
The meaning and order of the three return values is designed to
... | keyword[def] identifier[to_polar] ( identifier[xyz] ):
literal[string]
identifier[r] = identifier[length_of] ( identifier[xyz] )
identifier[x] , identifier[y] , identifier[z] = identifier[xyz]
identifier[theta] = identifier[arcsin] ( identifier[z] / identifier[r] )
identifier[phi] = identif... | def to_polar(xyz):
"""Convert ``[x y z]`` into spherical coordinates ``(r, theta, phi)``.
``r`` - vector length
``theta`` - angle above (+) or below (-) the xy-plane
``phi`` - angle around the z-axis
The meaning and order of the three return values is designed to
match both ISO 31-11 and the t... |
def _ensure_worker(self):
"""Ensure there are enough workers available"""
while len(self._workers) < self._min_workers or len(self._workers) < self._queue.qsize() < self._max_workers:
worker = threading.Thread(
target=self._execute_futures,
name=self.identifie... | def function[_ensure_worker, parameter[self]]:
constant[Ensure there are enough workers available]
while <ast.BoolOp object at 0x7da18eb55d20> begin[:]
variable[worker] assign[=] call[name[threading].Thread, parameter[]]
name[worker].daemon assign[=] constant[True]
... | keyword[def] identifier[_ensure_worker] ( identifier[self] ):
literal[string]
keyword[while] identifier[len] ( identifier[self] . identifier[_workers] )< identifier[self] . identifier[_min_workers] keyword[or] identifier[len] ( identifier[self] . identifier[_workers] )< identifier[self] . identi... | def _ensure_worker(self):
"""Ensure there are enough workers available"""
while len(self._workers) < self._min_workers or len(self._workers) < self._queue.qsize() < self._max_workers:
worker = threading.Thread(target=self._execute_futures, name=self.identifier + '_%d' % time.time())
worker.daemo... |
def linguist_field_names(self):
"""
Returns linguist field names (example: "title" and "title_fr").
"""
return list(self.model._linguist.fields) + list(
utils.get_language_fields(self.model._linguist.fields)
) | def function[linguist_field_names, parameter[self]]:
constant[
Returns linguist field names (example: "title" and "title_fr").
]
return[binary_operation[call[name[list], parameter[name[self].model._linguist.fields]] + call[name[list], parameter[call[name[utils].get_language_fields, parameter... | keyword[def] identifier[linguist_field_names] ( identifier[self] ):
literal[string]
keyword[return] identifier[list] ( identifier[self] . identifier[model] . identifier[_linguist] . identifier[fields] )+ identifier[list] (
identifier[utils] . identifier[get_language_fields] ( identifier[s... | def linguist_field_names(self):
"""
Returns linguist field names (example: "title" and "title_fr").
"""
return list(self.model._linguist.fields) + list(utils.get_language_fields(self.model._linguist.fields)) |
def get_wsgi_requests(request):
'''
For the given batch request, extract the individual requests and create
WSGIRequest object for each.
'''
valid_http_methods = ["get", "post", "put", "patch", "delete", "head", "options", "connect", "trace"]
requests = json.loads(request.body)
if t... | def function[get_wsgi_requests, parameter[request]]:
constant[
For the given batch request, extract the individual requests and create
WSGIRequest object for each.
]
variable[valid_http_methods] assign[=] list[[<ast.Constant object at 0x7da1b0d067d0>, <ast.Constant object at 0x7da1b0... | keyword[def] identifier[get_wsgi_requests] ( identifier[request] ):
literal[string]
identifier[valid_http_methods] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ]
identifier[requests] =... | def get_wsgi_requests(request):
"""
For the given batch request, extract the individual requests and create
WSGIRequest object for each.
"""
valid_http_methods = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'connect', 'trace']
requests = json.loads(request.body)
if ty... |
def stride(self):
"""Step per axis between neighboring points of a uniform grid.
If the grid contains axes that are not uniform, ``stride`` has
a ``NaN`` entry.
For degenerate (length 1) axes, ``stride`` has value ``0.0``.
Returns
-------
stride : numpy.array
... | def function[stride, parameter[self]]:
constant[Step per axis between neighboring points of a uniform grid.
If the grid contains axes that are not uniform, ``stride`` has
a ``NaN`` entry.
For degenerate (length 1) axes, ``stride`` has value ``0.0``.
Returns
-------
... | keyword[def] identifier[stride] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[__stride] keyword[is] keyword[None] :
identifier[strd] =[]
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[self] . identifie... | def stride(self):
"""Step per axis between neighboring points of a uniform grid.
If the grid contains axes that are not uniform, ``stride`` has
a ``NaN`` entry.
For degenerate (length 1) axes, ``stride`` has value ``0.0``.
Returns
-------
stride : numpy.array
... |
def raise_for_status(self):
'''Raise Postmark-specific HTTP errors. If there isn't one, the
standard HTTP error is raised.
HTTP 401 raises :class:`UnauthorizedError`
HTTP 422 raises :class:`UnprocessableEntityError`
HTTP 500 raises :class:`InternalServerError`
'''
... | def function[raise_for_status, parameter[self]]:
constant[Raise Postmark-specific HTTP errors. If there isn't one, the
standard HTTP error is raised.
HTTP 401 raises :class:`UnauthorizedError`
HTTP 422 raises :class:`UnprocessableEntityError`
HTTP 500 raises :class:`InternalSe... | keyword[def] identifier[raise_for_status] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[status_code] == literal[int] :
keyword[raise] identifier[UnauthorizedError] ( identifier[self] . identifier[_requests_response] )
keyword[elif] identifi... | def raise_for_status(self):
"""Raise Postmark-specific HTTP errors. If there isn't one, the
standard HTTP error is raised.
HTTP 401 raises :class:`UnauthorizedError`
HTTP 422 raises :class:`UnprocessableEntityError`
HTTP 500 raises :class:`InternalServerError`
"""
if s... |
def _finalize(self):
"""Reset the status and tell the database to finalize the traces."""
if self.status in ['running', 'halt']:
if self.verbose > 0:
print_('\nSampling finished normally.')
self.status = 'ready'
self.save_state()
self.db._finalize... | def function[_finalize, parameter[self]]:
constant[Reset the status and tell the database to finalize the traces.]
if compare[name[self].status in list[[<ast.Constant object at 0x7da20eb29630>, <ast.Constant object at 0x7da20eb29cc0>]]] begin[:]
if compare[name[self].verbose greater[>] c... | keyword[def] identifier[_finalize] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[status] keyword[in] [ literal[string] , literal[string] ]:
keyword[if] identifier[self] . identifier[verbose] > literal[int] :
identifier[print_] ( lit... | def _finalize(self):
"""Reset the status and tell the database to finalize the traces."""
if self.status in ['running', 'halt']:
if self.verbose > 0:
print_('\nSampling finished normally.') # depends on [control=['if'], data=[]]
self.status = 'ready' # depends on [control=['if'], d... |
def get_overridden_calculated_entry(self):
"""Gets the calculated entry this entry overrides.
return: (osid.grading.GradeEntry) - the calculated entry
raise: IllegalState - ``overrides_calculated_entry()`` is
``false``
raise: OperationFailed - unable to complete reques... | def function[get_overridden_calculated_entry, parameter[self]]:
constant[Gets the calculated entry this entry overrides.
return: (osid.grading.GradeEntry) - the calculated entry
raise: IllegalState - ``overrides_calculated_entry()`` is
``false``
raise: OperationFailed ... | keyword[def] identifier[get_overridden_calculated_entry] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[bool] ( identifier[self] . identifier[_my_map] [ literal[string] ]):
keyword[raise] identifier[errors] . identifier[IllegalState] ( literal[str... | def get_overridden_calculated_entry(self):
"""Gets the calculated entry this entry overrides.
return: (osid.grading.GradeEntry) - the calculated entry
raise: IllegalState - ``overrides_calculated_entry()`` is
``false``
raise: OperationFailed - unable to complete request
... |
def save_volt(elecs, volt, filename):
"""Save the values in volt-format.
"""
# bring data in shape
content = np.column_stack((elecs, volt, np.zeros(len(volt))))
# save datapoints
with open(filename, 'w') as fid:
fid.write('{0}\n'.format(content.shape[0]))
with open(filename, 'ab') a... | def function[save_volt, parameter[elecs, volt, filename]]:
constant[Save the values in volt-format.
]
variable[content] assign[=] call[name[np].column_stack, parameter[tuple[[<ast.Name object at 0x7da18eb55660>, <ast.Name object at 0x7da18eb56650>, <ast.Call object at 0x7da18eb55840>]]]]
wit... | keyword[def] identifier[save_volt] ( identifier[elecs] , identifier[volt] , identifier[filename] ):
literal[string]
identifier[content] = identifier[np] . identifier[column_stack] (( identifier[elecs] , identifier[volt] , identifier[np] . identifier[zeros] ( identifier[len] ( identifier[volt] ))))
... | def save_volt(elecs, volt, filename):
"""Save the values in volt-format.
"""
# bring data in shape
content = np.column_stack((elecs, volt, np.zeros(len(volt))))
# save datapoints
with open(filename, 'w') as fid:
fid.write('{0}\n'.format(content.shape[0])) # depends on [control=['with'],... |
def access_add(name, event, cid, uid, **kwargs):
"""
Creates a new record with specified cid/uid in the event authorization.
Requests with token that contains such cid/uid will have access to the specified event of a
service.
"""
ctx = Context(**kwargs)
ctx.execute_action('access:add', **{
... | def function[access_add, parameter[name, event, cid, uid]]:
constant[
Creates a new record with specified cid/uid in the event authorization.
Requests with token that contains such cid/uid will have access to the specified event of a
service.
]
variable[ctx] assign[=] call[name[Context]... | keyword[def] identifier[access_add] ( identifier[name] , identifier[event] , identifier[cid] , identifier[uid] ,** identifier[kwargs] ):
literal[string]
identifier[ctx] = identifier[Context] (** identifier[kwargs] )
identifier[ctx] . identifier[execute_action] ( literal[string] ,**{
literal[strin... | def access_add(name, event, cid, uid, **kwargs):
"""
Creates a new record with specified cid/uid in the event authorization.
Requests with token that contains such cid/uid will have access to the specified event of a
service.
"""
ctx = Context(**kwargs)
ctx.execute_action('access:add', **{'... |
def encode_field(self, field, value):
"""Encode a python field value to a JSON value.
Args:
field: A ProtoRPC field instance.
value: A python value supported by field.
Returns:
A JSON serializable value appropriate for field.
"""
# Override the handling of 64-bit integers, so the... | def function[encode_field, parameter[self, field, value]]:
constant[Encode a python field value to a JSON value.
Args:
field: A ProtoRPC field instance.
value: A python value supported by field.
Returns:
A JSON serializable value appropriate for field.
]
if <ast.BoolOp ob... | keyword[def] identifier[encode_field] ( identifier[self] , identifier[field] , identifier[value] ):
literal[string]
keyword[if] ( identifier[isinstance] ( identifier[field] , identifier[messages] . identifier[IntegerField] ) keyword[and]
identifier[field] . identifier[variant] keyword[in] ... | def encode_field(self, field, value):
"""Encode a python field value to a JSON value.
Args:
field: A ProtoRPC field instance.
value: A python value supported by field.
Returns:
A JSON serializable value appropriate for field.
"""
# Override the handling of 64-bit integers, so the... |
def return_real_id_base(dbpath, set_object):
"""
Generic function which returns a list of real_id's
Parameters
----------
dbpath : string, path to SQLite database file
set_object : object (either TestSet or TrainSet) which is stored in the database
Returns
-------
return_list : lis... | def function[return_real_id_base, parameter[dbpath, set_object]]:
constant[
Generic function which returns a list of real_id's
Parameters
----------
dbpath : string, path to SQLite database file
set_object : object (either TestSet or TrainSet) which is stored in the database
Returns
... | keyword[def] identifier[return_real_id_base] ( identifier[dbpath] , identifier[set_object] ):
literal[string]
identifier[engine] = identifier[create_engine] ( literal[string] + identifier[dbpath] )
identifier[session_cl] = identifier[sessionmaker] ( identifier[bind] = identifier[engine] )
identif... | def return_real_id_base(dbpath, set_object):
"""
Generic function which returns a list of real_id's
Parameters
----------
dbpath : string, path to SQLite database file
set_object : object (either TestSet or TrainSet) which is stored in the database
Returns
-------
return_list : lis... |
def tear_down(self):
"""Tear down the instance
"""
import boto.ec2
if not self.browser_config.get('terminate'):
self.warning_log("Skipping terminate")
return
self.info_log("Tearing down...")
ec2 = boto.ec2.connect_to_region(self.browser_config.g... | def function[tear_down, parameter[self]]:
constant[Tear down the instance
]
import module[boto.ec2]
if <ast.UnaryOp object at 0x7da20c990af0> begin[:]
call[name[self].warning_log, parameter[constant[Skipping terminate]]]
return[None]
call[name[self].info_log, ... | keyword[def] identifier[tear_down] ( identifier[self] ):
literal[string]
keyword[import] identifier[boto] . identifier[ec2]
keyword[if] keyword[not] identifier[self] . identifier[browser_config] . identifier[get] ( literal[string] ):
identifier[self] . identifier[warning_... | def tear_down(self):
"""Tear down the instance
"""
import boto.ec2
if not self.browser_config.get('terminate'):
self.warning_log('Skipping terminate')
return # depends on [control=['if'], data=[]]
self.info_log('Tearing down...')
ec2 = boto.ec2.connect_to_region(self.browser... |
def clamped(self, point_or_rect):
"""
Returns the point or rectangle clamped to this rectangle.
"""
if isinstance(point_or_rect, Rect):
return Rect(np.minimum(self.mins, point_or_rect.mins),
np.maximum(self.maxes, point_or_rect.maxes))
return n... | def function[clamped, parameter[self, point_or_rect]]:
constant[
Returns the point or rectangle clamped to this rectangle.
]
if call[name[isinstance], parameter[name[point_or_rect], name[Rect]]] begin[:]
return[call[name[Rect], parameter[call[name[np].minimum, parameter[name[self... | keyword[def] identifier[clamped] ( identifier[self] , identifier[point_or_rect] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[point_or_rect] , identifier[Rect] ):
keyword[return] identifier[Rect] ( identifier[np] . identifier[minimum] ( identifier[self] . identif... | def clamped(self, point_or_rect):
"""
Returns the point or rectangle clamped to this rectangle.
"""
if isinstance(point_or_rect, Rect):
return Rect(np.minimum(self.mins, point_or_rect.mins), np.maximum(self.maxes, point_or_rect.maxes)) # depends on [control=['if'], data=[]]
return n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.