code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def repeat_biweekly(self):
"""
This function is unique b/c it creates an empty defaultdict,
adds in the event occurrences by creating an instance of Repeater,
then returns the defaultdict, likely to be merged into the 'main'
defaultdict (the one holding all event occurrences for ... | def function[repeat_biweekly, parameter[self]]:
constant[
This function is unique b/c it creates an empty defaultdict,
adds in the event occurrences by creating an instance of Repeater,
then returns the defaultdict, likely to be merged into the 'main'
defaultdict (the one holding... | keyword[def] identifier[repeat_biweekly] ( identifier[self] ):
literal[string]
identifier[mycount] = identifier[defaultdict] ( identifier[list] )
identifier[d] = identifier[self] . identifier[event] . identifier[l_start_date]
keyword[while] identifier[d] . identifier[year] != id... | def repeat_biweekly(self):
"""
This function is unique b/c it creates an empty defaultdict,
adds in the event occurrences by creating an instance of Repeater,
then returns the defaultdict, likely to be merged into the 'main'
defaultdict (the one holding all event occurrences for this... |
def add_from_lists(self, data_list=None, fun_list=None, dsp_list=None):
"""
Add multiple function and data nodes to dispatcher.
:param data_list:
It is a list of data node kwargs to be loaded.
:type data_list: list[dict], optional
:param fun_list:
It is ... | def function[add_from_lists, parameter[self, data_list, fun_list, dsp_list]]:
constant[
Add multiple function and data nodes to dispatcher.
:param data_list:
It is a list of data node kwargs to be loaded.
:type data_list: list[dict], optional
:param fun_list:
... | keyword[def] identifier[add_from_lists] ( identifier[self] , identifier[data_list] = keyword[None] , identifier[fun_list] = keyword[None] , identifier[dsp_list] = keyword[None] ):
literal[string]
keyword[if] identifier[data_list] :
identifier[data_ids] =[ identifier[self] . identifie... | def add_from_lists(self, data_list=None, fun_list=None, dsp_list=None):
"""
Add multiple function and data nodes to dispatcher.
:param data_list:
It is a list of data node kwargs to be loaded.
:type data_list: list[dict], optional
:param fun_list:
It is a li... |
def get_comments(self):
"""
:calls: `GET /gists/:gist_id/comments <http://developer.github.com/v3/gists/comments>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.GistComment.GistComment`
"""
return github.PaginatedList.PaginatedList(
github.Gis... | def function[get_comments, parameter[self]]:
constant[
:calls: `GET /gists/:gist_id/comments <http://developer.github.com/v3/gists/comments>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.GistComment.GistComment`
]
return[call[name[github].PaginatedList.Pagin... | keyword[def] identifier[get_comments] ( identifier[self] ):
literal[string]
keyword[return] identifier[github] . identifier[PaginatedList] . identifier[PaginatedList] (
identifier[github] . identifier[GistComment] . identifier[GistComment] ,
identifier[self] . identifier[_request... | def get_comments(self):
"""
:calls: `GET /gists/:gist_id/comments <http://developer.github.com/v3/gists/comments>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.GistComment.GistComment`
"""
return github.PaginatedList.PaginatedList(github.GistComment.GistComment,... |
def add_pool(self, auth, attr):
""" Create a pool according to `attr`.
* `auth` [BaseAuth]
AAA options.
* `attr` [pool_attr]
A dict containing the attributes the new pool should have.
Returns a dict describing the pool which was added.
... | def function[add_pool, parameter[self, auth, attr]]:
constant[ Create a pool according to `attr`.
* `auth` [BaseAuth]
AAA options.
* `attr` [pool_attr]
A dict containing the attributes the new pool should have.
Returns a dict describing the p... | keyword[def] identifier[add_pool] ( identifier[self] , identifier[auth] , identifier[attr] ):
literal[string]
identifier[self] . identifier[_logger] . identifier[debug] ( literal[string] % identifier[unicode] ( identifier[attr] ))
identifier[req_attr] =[ literal[string] , litera... | def add_pool(self, auth, attr):
""" Create a pool according to `attr`.
* `auth` [BaseAuth]
AAA options.
* `attr` [pool_attr]
A dict containing the attributes the new pool should have.
Returns a dict describing the pool which was added.
... |
def rebuild(self):
"""
Rebuilds the scene based on the current settings.
:param start | <QDate>
end | <QDate>
"""
gantt = self.ganttWidget()
scale = gantt.timescale()
rect = self.sceneRect()
header = gantt.tree... | def function[rebuild, parameter[self]]:
constant[
Rebuilds the scene based on the current settings.
:param start | <QDate>
end | <QDate>
]
variable[gantt] assign[=] call[name[self].ganttWidget, parameter[]]
variable[scale] assign[=] cal... | keyword[def] identifier[rebuild] ( identifier[self] ):
literal[string]
identifier[gantt] = identifier[self] . identifier[ganttWidget] ()
identifier[scale] = identifier[gantt] . identifier[timescale] ()
identifier[rect] = identifier[self] . identifier[sceneRect] ()
id... | def rebuild(self):
"""
Rebuilds the scene based on the current settings.
:param start | <QDate>
end | <QDate>
"""
gantt = self.ganttWidget()
scale = gantt.timescale()
rect = self.sceneRect()
header = gantt.treeWidget().header() # define th... |
def _make_value_pb(value):
"""Helper for :func:`_make_list_value_pbs`.
:type value: scalar value
:param value: value to convert
:rtype: :class:`~google.protobuf.struct_pb2.Value`
:returns: value protobufs
:raises ValueError: if value is not of a known scalar type.
"""
if value is None:... | def function[_make_value_pb, parameter[value]]:
constant[Helper for :func:`_make_list_value_pbs`.
:type value: scalar value
:param value: value to convert
:rtype: :class:`~google.protobuf.struct_pb2.Value`
:returns: value protobufs
:raises ValueError: if value is not of a known scalar type... | keyword[def] identifier[_make_value_pb] ( identifier[value] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[None] :
keyword[return] identifier[Value] ( identifier[null_value] = literal[string] )
keyword[if] identifier[isinstance] ( identifier[value] ,( identifier[lis... | def _make_value_pb(value):
"""Helper for :func:`_make_list_value_pbs`.
:type value: scalar value
:param value: value to convert
:rtype: :class:`~google.protobuf.struct_pb2.Value`
:returns: value protobufs
:raises ValueError: if value is not of a known scalar type.
"""
if value is None:... |
def ping_external_urls_handler(sender, **kwargs):
"""
Ping externals URLS when an entry is saved.
"""
entry = kwargs['instance']
if entry.is_visible and settings.SAVE_PING_EXTERNAL_URLS:
ExternalUrlsPinger(entry) | def function[ping_external_urls_handler, parameter[sender]]:
constant[
Ping externals URLS when an entry is saved.
]
variable[entry] assign[=] call[name[kwargs]][constant[instance]]
if <ast.BoolOp object at 0x7da1b222e650> begin[:]
call[name[ExternalUrlsPinger], parameter... | keyword[def] identifier[ping_external_urls_handler] ( identifier[sender] ,** identifier[kwargs] ):
literal[string]
identifier[entry] = identifier[kwargs] [ literal[string] ]
keyword[if] identifier[entry] . identifier[is_visible] keyword[and] identifier[settings] . identifier[SAVE_PING_EXTERNAL_URL... | def ping_external_urls_handler(sender, **kwargs):
"""
Ping externals URLS when an entry is saved.
"""
entry = kwargs['instance']
if entry.is_visible and settings.SAVE_PING_EXTERNAL_URLS:
ExternalUrlsPinger(entry) # depends on [control=['if'], data=[]] |
def _std_tuple_of(var=None, std=None, interval=None):
"""
Convienence function for plotting. Given one of var, standard
deviation, or interval, return the std. Any of the three can be an
iterable list.
Examples
--------
>>>_std_tuple_of(var=[1, 3, 9])
(1, 2, 3)
"""
if std is n... | def function[_std_tuple_of, parameter[var, std, interval]]:
constant[
Convienence function for plotting. Given one of var, standard
deviation, or interval, return the std. Any of the three can be an
iterable list.
Examples
--------
>>>_std_tuple_of(var=[1, 3, 9])
(1, 2, 3)
]
... | keyword[def] identifier[_std_tuple_of] ( identifier[var] = keyword[None] , identifier[std] = keyword[None] , identifier[interval] = keyword[None] ):
literal[string]
keyword[if] identifier[std] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[np] . identifier[isscalar] ( identi... | def _std_tuple_of(var=None, std=None, interval=None):
"""
Convienence function for plotting. Given one of var, standard
deviation, or interval, return the std. Any of the three can be an
iterable list.
Examples
--------
>>>_std_tuple_of(var=[1, 3, 9])
(1, 2, 3)
"""
if std is no... |
def _set_subject(self, subject):
""" sets the subject value for the class instance
Args:
subject(dict, Uri, str): the subject for the class instance
"""
# if not subject:
# self.subject =
def test_uri(value):
""" test to see if the value is a ... | def function[_set_subject, parameter[self, subject]]:
constant[ sets the subject value for the class instance
Args:
subject(dict, Uri, str): the subject for the class instance
]
def function[test_uri, parameter[value]]:
constant[ test to see if the value is a... | keyword[def] identifier[_set_subject] ( identifier[self] , identifier[subject] ):
literal[string]
keyword[def] identifier[test_uri] ( identifier[value] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[value]... | def _set_subject(self, subject):
""" sets the subject value for the class instance
Args:
subject(dict, Uri, str): the subject for the class instance
"""
# if not subject:
# self.subject =
def test_uri(value):
""" test to see if the value is a uri or bnode
... |
def user_name(with_num=False):
"""Return a random user name.
Basically it's lowercased result of
:py:func:`~forgery_py.forgery.name.first_name()` with a number appended
if `with_num`.
"""
result = first_name()
if with_num:
result += str(random.randint(63, 94))
return result.low... | def function[user_name, parameter[with_num]]:
constant[Return a random user name.
Basically it's lowercased result of
:py:func:`~forgery_py.forgery.name.first_name()` with a number appended
if `with_num`.
]
variable[result] assign[=] call[name[first_name], parameter[]]
if name[w... | keyword[def] identifier[user_name] ( identifier[with_num] = keyword[False] ):
literal[string]
identifier[result] = identifier[first_name] ()
keyword[if] identifier[with_num] :
identifier[result] += identifier[str] ( identifier[random] . identifier[randint] ( literal[int] , literal[int] ))
... | def user_name(with_num=False):
"""Return a random user name.
Basically it's lowercased result of
:py:func:`~forgery_py.forgery.name.first_name()` with a number appended
if `with_num`.
"""
result = first_name()
if with_num:
result += str(random.randint(63, 94)) # depends on [control... |
def get_metadata(address=None, tx_hash=None, block_hash=None, api_key=None, private=True, coin_symbol='btc'):
'''
Get metadata using blockcypher's API.
This is data on blockcypher's servers and not embedded into the bitcoin (or other) blockchain.
'''
assert is_valid_coin_symbol(coin_symbol), coin_s... | def function[get_metadata, parameter[address, tx_hash, block_hash, api_key, private, coin_symbol]]:
constant[
Get metadata using blockcypher's API.
This is data on blockcypher's servers and not embedded into the bitcoin (or other) blockchain.
]
assert[call[name[is_valid_coin_symbol], parameter[... | keyword[def] identifier[get_metadata] ( identifier[address] = keyword[None] , identifier[tx_hash] = keyword[None] , identifier[block_hash] = keyword[None] , identifier[api_key] = keyword[None] , identifier[private] = keyword[True] , identifier[coin_symbol] = literal[string] ):
literal[string]
keyword[asser... | def get_metadata(address=None, tx_hash=None, block_hash=None, api_key=None, private=True, coin_symbol='btc'):
"""
Get metadata using blockcypher's API.
This is data on blockcypher's servers and not embedded into the bitcoin (or other) blockchain.
"""
assert is_valid_coin_symbol(coin_symbol), coin_s... |
def relay_events_from(self, originator, event_type, *more_event_types):
"""
Configure this handler to re-dispatch events from another handler.
This method configures this handler dispatch an event of type
*event_type* whenever *originator* dispatches events of the same type
or... | def function[relay_events_from, parameter[self, originator, event_type]]:
constant[
Configure this handler to re-dispatch events from another handler.
This method configures this handler dispatch an event of type
*event_type* whenever *originator* dispatches events of the same type
... | keyword[def] identifier[relay_events_from] ( identifier[self] , identifier[originator] , identifier[event_type] ,* identifier[more_event_types] ):
literal[string]
identifier[handlers] ={
identifier[event_type] : keyword[lambda] * identifier[args] ,** identifier[kwargs] : identifier[self] .... | def relay_events_from(self, originator, event_type, *more_event_types):
"""
Configure this handler to re-dispatch events from another handler.
This method configures this handler dispatch an event of type
*event_type* whenever *originator* dispatches events of the same type
or any... |
def sample_hslice(args):
"""
Return a new live point proposed by "Hamiltonian" Slice Sampling
using a series of random trajectories away from an existing live point.
Each trajectory is based on the provided axes and samples are determined
by moving forwards/backwards in time until the trajectory hit... | def function[sample_hslice, parameter[args]]:
constant[
Return a new live point proposed by "Hamiltonian" Slice Sampling
using a series of random trajectories away from an existing live point.
Each trajectory is based on the provided axes and samples are determined
by moving forwards/backwards i... | keyword[def] identifier[sample_hslice] ( identifier[args] ):
literal[string]
( identifier[u] , identifier[loglstar] , identifier[axes] , identifier[scale] ,
identifier[prior_transform] , identifier[loglikelihood] , identifier[kwargs] )= identifier[args]
identifier[rstate] = identifier[np] .... | def sample_hslice(args):
"""
Return a new live point proposed by "Hamiltonian" Slice Sampling
using a series of random trajectories away from an existing live point.
Each trajectory is based on the provided axes and samples are determined
by moving forwards/backwards in time until the trajectory hit... |
def tail(self, n=10):
"""
Get an SArray that contains the last n elements in the SArray.
Parameters
----------
n : int
The number of elements to fetch
Returns
-------
out : SArray
A new SArray which contains the last n rows of the... | def function[tail, parameter[self, n]]:
constant[
Get an SArray that contains the last n elements in the SArray.
Parameters
----------
n : int
The number of elements to fetch
Returns
-------
out : SArray
A new SArray which contain... | keyword[def] identifier[tail] ( identifier[self] , identifier[n] = literal[int] ):
literal[string]
keyword[with] identifier[cython_context] ():
keyword[return] identifier[SArray] ( identifier[_proxy] = identifier[self] . identifier[__proxy__] . identifier[tail] ( identifier[n] )) | def tail(self, n=10):
"""
Get an SArray that contains the last n elements in the SArray.
Parameters
----------
n : int
The number of elements to fetch
Returns
-------
out : SArray
A new SArray which contains the last n rows of the cur... |
def is_edge_not_excluding_vertices(self, other):
"""Returns False iif any edge excludes all vertices of other."""
c_a = cos(self.angle)
s_a = sin(self.angle)
# Get min and max of other.
other_x_min, other_x_max, other_y_min, other_y_max = other.get_bbox()
self_x_diff ... | def function[is_edge_not_excluding_vertices, parameter[self, other]]:
constant[Returns False iif any edge excludes all vertices of other.]
variable[c_a] assign[=] call[name[cos], parameter[name[self].angle]]
variable[s_a] assign[=] call[name[sin], parameter[name[self].angle]]
<ast.Tuple ... | keyword[def] identifier[is_edge_not_excluding_vertices] ( identifier[self] , identifier[other] ):
literal[string]
identifier[c_a] = identifier[cos] ( identifier[self] . identifier[angle] )
identifier[s_a] = identifier[sin] ( identifier[self] . identifier[angle] )
ident... | def is_edge_not_excluding_vertices(self, other):
"""Returns False iif any edge excludes all vertices of other."""
c_a = cos(self.angle)
s_a = sin(self.angle)
# Get min and max of other.
(other_x_min, other_x_max, other_y_min, other_y_max) = other.get_bbox()
self_x_diff = 0.5 * self.width
sel... |
def get_urlclass_from (scheme, assume_local_file=False):
"""Return checker class for given URL scheme. If the scheme
cannot be matched and assume_local_file is True, assume a local file.
"""
if scheme in ("http", "https"):
klass = httpurl.HttpUrl
elif scheme == "ftp":
klass = ftpurl.... | def function[get_urlclass_from, parameter[scheme, assume_local_file]]:
constant[Return checker class for given URL scheme. If the scheme
cannot be matched and assume_local_file is True, assume a local file.
]
if compare[name[scheme] in tuple[[<ast.Constant object at 0x7da2047eba30>, <ast.Constan... | keyword[def] identifier[get_urlclass_from] ( identifier[scheme] , identifier[assume_local_file] = keyword[False] ):
literal[string]
keyword[if] identifier[scheme] keyword[in] ( literal[string] , literal[string] ):
identifier[klass] = identifier[httpurl] . identifier[HttpUrl]
keyword[elif] ... | def get_urlclass_from(scheme, assume_local_file=False):
"""Return checker class for given URL scheme. If the scheme
cannot be matched and assume_local_file is True, assume a local file.
"""
if scheme in ('http', 'https'):
klass = httpurl.HttpUrl # depends on [control=['if'], data=[]]
elif s... |
def send_message(self,
subject_or_message: Optional[Union[Message, str]] = None,
to: Optional[Union[str, List[str]]] = None,
**kwargs):
"""
Send an email using the send function as configured by
:attr:`~flask_unchained.bundles.mail.c... | def function[send_message, parameter[self, subject_or_message, to]]:
constant[
Send an email using the send function as configured by
:attr:`~flask_unchained.bundles.mail.config.Config.MAIL_SEND_FN`.
:param subject_or_message: The subject line, or an instance of
... | keyword[def] identifier[send_message] ( identifier[self] ,
identifier[subject_or_message] : identifier[Optional] [ identifier[Union] [ identifier[Message] , identifier[str] ]]= keyword[None] ,
identifier[to] : identifier[Optional] [ identifier[Union] [ identifier[str] , identifier[List] [ identifier[str] ]]]= keywo... | def send_message(self, subject_or_message: Optional[Union[Message, str]]=None, to: Optional[Union[str, List[str]]]=None, **kwargs):
"""
Send an email using the send function as configured by
:attr:`~flask_unchained.bundles.mail.config.Config.MAIL_SEND_FN`.
:param subject_or_message: The sub... |
def _init_az_api(self):
"""
Initialise client objects for talking to Azure API.
This is in a separate function so to be called by ``__init__``
and ``__setstate__``.
"""
with self.__lock:
if self._resource_client is None:
log.debug("Making Azur... | def function[_init_az_api, parameter[self]]:
constant[
Initialise client objects for talking to Azure API.
This is in a separate function so to be called by ``__init__``
and ``__setstate__``.
]
with name[self].__lock begin[:]
if compare[name[self]._resour... | keyword[def] identifier[_init_az_api] ( identifier[self] ):
literal[string]
keyword[with] identifier[self] . identifier[__lock] :
keyword[if] identifier[self] . identifier[_resource_client] keyword[is] keyword[None] :
identifier[log] . identifier[debug] ( literal[s... | def _init_az_api(self):
"""
Initialise client objects for talking to Azure API.
This is in a separate function so to be called by ``__init__``
and ``__setstate__``.
"""
with self.__lock:
if self._resource_client is None:
log.debug('Making Azure `ServicePrinci... |
def toggle_fold_trigger(self, block):
"""
Toggle a fold trigger block (expand or collapse it).
:param block: The QTextBlock to expand/collapse
"""
if not TextBlockHelper.is_fold_trigger(block):
return
region = FoldScope(block)
if region.collapsed:
... | def function[toggle_fold_trigger, parameter[self, block]]:
constant[
Toggle a fold trigger block (expand or collapse it).
:param block: The QTextBlock to expand/collapse
]
if <ast.UnaryOp object at 0x7da18dc9be50> begin[:]
return[None]
variable[region] assign[=] ... | keyword[def] identifier[toggle_fold_trigger] ( identifier[self] , identifier[block] ):
literal[string]
keyword[if] keyword[not] identifier[TextBlockHelper] . identifier[is_fold_trigger] ( identifier[block] ):
keyword[return]
identifier[region] = identifier[FoldScope] ( iden... | def toggle_fold_trigger(self, block):
"""
Toggle a fold trigger block (expand or collapse it).
:param block: The QTextBlock to expand/collapse
"""
if not TextBlockHelper.is_fold_trigger(block):
return # depends on [control=['if'], data=[]]
region = FoldScope(block)
if r... |
def reflect_well(value, bounds):
"""Given some boundaries, reflects the value until it falls within both
boundaries. This is done iteratively, reflecting left off of the
`boundaries.max`, then right off of the `boundaries.min`, etc.
Parameters
----------
value : float
The value to apply... | def function[reflect_well, parameter[value, bounds]]:
constant[Given some boundaries, reflects the value until it falls within both
boundaries. This is done iteratively, reflecting left off of the
`boundaries.max`, then right off of the `boundaries.min`, etc.
Parameters
----------
value : f... | keyword[def] identifier[reflect_well] ( identifier[value] , identifier[bounds] ):
literal[string]
keyword[while] identifier[value] keyword[not] keyword[in] identifier[bounds] :
identifier[value] = identifier[bounds] . identifier[_max] . identifier[reflect_left] ( identifier[value] )
i... | def reflect_well(value, bounds):
"""Given some boundaries, reflects the value until it falls within both
boundaries. This is done iteratively, reflecting left off of the
`boundaries.max`, then right off of the `boundaries.min`, etc.
Parameters
----------
value : float
The value to apply... |
def contains(self, rect):
"""
Tests if another rectangle is contained by this one
Arguments:
rect (Rectangle): The other rectangle
Returns:
bool: True if it is container, False otherwise
"""
return (rect.y >= self.y and \
rect.x >... | def function[contains, parameter[self, rect]]:
constant[
Tests if another rectangle is contained by this one
Arguments:
rect (Rectangle): The other rectangle
Returns:
bool: True if it is container, False otherwise
]
return[<ast.BoolOp object at 0x7da... | keyword[def] identifier[contains] ( identifier[self] , identifier[rect] ):
literal[string]
keyword[return] ( identifier[rect] . identifier[y] >= identifier[self] . identifier[y] keyword[and] identifier[rect] . identifier[x] >= identifier[self] . identifier[x] keyword[and] identifier[rect] . ide... | def contains(self, rect):
"""
Tests if another rectangle is contained by this one
Arguments:
rect (Rectangle): The other rectangle
Returns:
bool: True if it is container, False otherwise
"""
return rect.y >= self.y and rect.x >= self.x and (rect.y + rect... |
def create_network_interface(name, subnet_id=None, subnet_name=None,
private_ip_address=None, description=None,
groups=None, region=None, key=None, keyid=None,
profile=None):
'''
Create an Elastic Network Interface.
.. v... | def function[create_network_interface, parameter[name, subnet_id, subnet_name, private_ip_address, description, groups, region, key, keyid, profile]]:
constant[
Create an Elastic Network Interface.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.cr... | keyword[def] identifier[create_network_interface] ( identifier[name] , identifier[subnet_id] = keyword[None] , identifier[subnet_name] = keyword[None] ,
identifier[private_ip_address] = keyword[None] , identifier[description] = keyword[None] ,
identifier[groups] = keyword[None] , identifier[region] = keyword[None] ... | def create_network_interface(name, subnet_id=None, subnet_name=None, private_ip_address=None, description=None, groups=None, region=None, key=None, keyid=None, profile=None):
"""
Create an Elastic Network Interface.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt mymini... |
def POST_AUTH(self, courseid): # pylint: disable=arguments-differ
""" GET request """
course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=False)
user_input = web.input(tasks=[], aggregations=[], users=[])
if "submission" in user_input:
# Replay a unique ... | def function[POST_AUTH, parameter[self, courseid]]:
constant[ GET request ]
<ast.Tuple object at 0x7da18f58ec50> assign[=] call[name[self].get_course_and_check_rights, parameter[name[courseid]]]
variable[user_input] assign[=] call[name[web].input, parameter[]]
if compare[constant[submiss... | keyword[def] identifier[POST_AUTH] ( identifier[self] , identifier[courseid] ):
literal[string]
identifier[course] , identifier[__] = identifier[self] . identifier[get_course_and_check_rights] ( identifier[courseid] , identifier[allow_all_staff] = keyword[False] )
identifier[user_input] = ... | def POST_AUTH(self, courseid): # pylint: disable=arguments-differ
' GET request '
(course, __) = self.get_course_and_check_rights(courseid, allow_all_staff=False)
user_input = web.input(tasks=[], aggregations=[], users=[])
if 'submission' in user_input:
# Replay a unique submission
subm... |
def ghissue_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
"""Link to a GitHub issue.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param name: The role name used in the document.
:p... | def function[ghissue_role, parameter[name, rawtext, text, lineno, inliner, options, content]]:
constant[Link to a GitHub issue.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param name: The role name use... | keyword[def] identifier[ghissue_role] ( identifier[name] , identifier[rawtext] , identifier[text] , identifier[lineno] , identifier[inliner] , identifier[options] ={}, identifier[content] =[]):
literal[string]
keyword[try] :
identifier[issue_num] = identifier[int] ( identifier[text] )
ke... | def ghissue_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
"""Link to a GitHub issue.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param name: The role name used in the document.
:p... |
async def is_try_or_pull_request(context, task):
"""Determine if a task is a try or a pull-request-like task (restricted privs).
Checks are the ones done in ``is_try`` and ``is_pull_request``
Args:
context (scriptworker.context.Context): the scriptworker context.
task (dict): the task defi... | <ast.AsyncFunctionDef object at 0x7da1b0e9f670> | keyword[async] keyword[def] identifier[is_try_or_pull_request] ( identifier[context] , identifier[task] ):
literal[string]
keyword[if] identifier[is_github_task] ( identifier[task] ):
keyword[return] keyword[await] identifier[is_pull_request] ( identifier[context] , identifier[task] )
key... | async def is_try_or_pull_request(context, task):
"""Determine if a task is a try or a pull-request-like task (restricted privs).
Checks are the ones done in ``is_try`` and ``is_pull_request``
Args:
context (scriptworker.context.Context): the scriptworker context.
task (dict): the task defi... |
def get_install_requires():
"""
parse requirements.txt, ignore links, exclude comments
"""
requirements = []
for line in open('requirements.txt').readlines():
# skip to next iteration if comment or empty line
if line.startswith('#') or line == '' or line.startswith('http') or line.st... | def function[get_install_requires, parameter[]]:
constant[
parse requirements.txt, ignore links, exclude comments
]
variable[requirements] assign[=] list[[]]
for taget[name[line]] in starred[call[call[name[open], parameter[constant[requirements.txt]]].readlines, parameter[]]] begin[:]
... | keyword[def] identifier[get_install_requires] ():
literal[string]
identifier[requirements] =[]
keyword[for] identifier[line] keyword[in] identifier[open] ( literal[string] ). identifier[readlines] ():
keyword[if] identifier[line] . identifier[startswith] ( literal[string] ) keyword[o... | def get_install_requires():
"""
parse requirements.txt, ignore links, exclude comments
"""
requirements = []
for line in open('requirements.txt').readlines():
# skip to next iteration if comment or empty line
if line.startswith('#') or line == '' or line.startswith('http') or line.st... |
def _join_path(self, hive, subkey):
"""
Joins the hive and key to make a Registry path.
@type hive: int
@param hive: Registry hive handle.
The hive handle must be one of the following integer constants:
- L{win32.HKEY_CLASSES_ROOT}
- L{win32.HKEY_C... | def function[_join_path, parameter[self, hive, subkey]]:
constant[
Joins the hive and key to make a Registry path.
@type hive: int
@param hive: Registry hive handle.
The hive handle must be one of the following integer constants:
- L{win32.HKEY_CLASSES_ROOT}
... | keyword[def] identifier[_join_path] ( identifier[self] , identifier[hive] , identifier[subkey] ):
literal[string]
identifier[path] = identifier[self] . identifier[_hives_by_value] [ identifier[hive] ]
keyword[if] identifier[subkey] :
identifier[path] = identifier[path] + lite... | def _join_path(self, hive, subkey):
"""
Joins the hive and key to make a Registry path.
@type hive: int
@param hive: Registry hive handle.
The hive handle must be one of the following integer constants:
- L{win32.HKEY_CLASSES_ROOT}
- L{win32.HKEY_CURRE... |
def to_json(self):
"""Converts track to a JSON serializable format
Returns:
Map with the name, and segments of the track.
"""
return {
'name': self.name,
'segments': [segment.to_json() for segment in self.segments],
'meta': self.meta
... | def function[to_json, parameter[self]]:
constant[Converts track to a JSON serializable format
Returns:
Map with the name, and segments of the track.
]
return[dictionary[[<ast.Constant object at 0x7da1b053b310>, <ast.Constant object at 0x7da1b0538130>, <ast.Constant object at 0x7... | keyword[def] identifier[to_json] ( identifier[self] ):
literal[string]
keyword[return] {
literal[string] : identifier[self] . identifier[name] ,
literal[string] :[ identifier[segment] . identifier[to_json] () keyword[for] identifier[segment] keyword[in] identifier[self] . ident... | def to_json(self):
"""Converts track to a JSON serializable format
Returns:
Map with the name, and segments of the track.
"""
return {'name': self.name, 'segments': [segment.to_json() for segment in self.segments], 'meta': self.meta} |
def iter_batches(iterable, batch_size):
'''
Given a sequence or iterable, yield batches from that iterable until it
runs out. Note that this function returns a generator, and also each
batch will be a generator.
:param iterable: The sequence or iterable to split into batches
:param int batch_si... | def function[iter_batches, parameter[iterable, batch_size]]:
constant[
Given a sequence or iterable, yield batches from that iterable until it
runs out. Note that this function returns a generator, and also each
batch will be a generator.
:param iterable: The sequence or iterable to split into ... | keyword[def] identifier[iter_batches] ( identifier[iterable] , identifier[batch_size] ):
literal[string]
identifier[sourceiter] = identifier[iter] ( identifier[iterable] )
keyword[while] keyword[True] :
identifier[batchiter] = identifier[islice] ( identifier[sourceiter] , identifier[bat... | def iter_batches(iterable, batch_size):
"""
Given a sequence or iterable, yield batches from that iterable until it
runs out. Note that this function returns a generator, and also each
batch will be a generator.
:param iterable: The sequence or iterable to split into batches
:param int batch_si... |
def __generate_indexed_requirements(dut_count, basekeys, requirements):
"""
Generate indexed requirements from general requirements.
:param dut_count: Amount of duts
:param basekeys: base keys as dict
:param requirements: requirements
:return: Indexed requirements as dic... | def function[__generate_indexed_requirements, parameter[dut_count, basekeys, requirements]]:
constant[
Generate indexed requirements from general requirements.
:param dut_count: Amount of duts
:param basekeys: base keys as dict
:param requirements: requirements
:return: ... | keyword[def] identifier[__generate_indexed_requirements] ( identifier[dut_count] , identifier[basekeys] , identifier[requirements] ):
literal[string]
identifier[dut_requirements] =[]
keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] , identifier[dut_count] + litera... | def __generate_indexed_requirements(dut_count, basekeys, requirements):
"""
Generate indexed requirements from general requirements.
:param dut_count: Amount of duts
:param basekeys: base keys as dict
:param requirements: requirements
:return: Indexed requirements as dict.
... |
def authenticate(self, personal_number, **kwargs):
"""Request an authentication order. The :py:meth:`collect` method
is used to query the status of the order.
:param personal_number: The Swedish personal number
in format YYYYMMDDXXXX.
:type personal_number: str
:retu... | def function[authenticate, parameter[self, personal_number]]:
constant[Request an authentication order. The :py:meth:`collect` method
is used to query the status of the order.
:param personal_number: The Swedish personal number
in format YYYYMMDDXXXX.
:type personal_number: ... | keyword[def] identifier[authenticate] ( identifier[self] , identifier[personal_number] ,** identifier[kwargs] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[kwargs] :
identifier[warnings] . identifier[warn] (
literal[string] literal[string] , ide... | def authenticate(self, personal_number, **kwargs):
"""Request an authentication order. The :py:meth:`collect` method
is used to query the status of the order.
:param personal_number: The Swedish personal number
in format YYYYMMDDXXXX.
:type personal_number: str
:return: ... |
def datafile_from_hash(hash_, prefix, path):
"""Return pathlib.Path for a data-file with given hash and prefix.
"""
pattern = '%s_%s*.h*' % (prefix, hash_)
datafiles = list(path.glob(pattern))
if len(datafiles) == 0:
raise NoMatchError('No matches for "%s"' % pattern)... | def function[datafile_from_hash, parameter[hash_, prefix, path]]:
constant[Return pathlib.Path for a data-file with given hash and prefix.
]
variable[pattern] assign[=] binary_operation[constant[%s_%s*.h*] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da18f7221a0>, <ast.Name o... | keyword[def] identifier[datafile_from_hash] ( identifier[hash_] , identifier[prefix] , identifier[path] ):
literal[string]
identifier[pattern] = literal[string] %( identifier[prefix] , identifier[hash_] )
identifier[datafiles] = identifier[list] ( identifier[path] . identifier[glob] ( iden... | def datafile_from_hash(hash_, prefix, path):
"""Return pathlib.Path for a data-file with given hash and prefix.
"""
pattern = '%s_%s*.h*' % (prefix, hash_)
datafiles = list(path.glob(pattern))
if len(datafiles) == 0:
raise NoMatchError('No matches for "%s"' % pattern) # depends on [cont... |
def input_file(filename):
"""
Run all checks on a Python source file.
"""
if excluded(filename) or not filename_match(filename):
return {}
if options.verbose:
message('checking ' + filename)
options.counters['files'] = options.counters.get('files', 0) + 1
errors = Checker(fil... | def function[input_file, parameter[filename]]:
constant[
Run all checks on a Python source file.
]
if <ast.BoolOp object at 0x7da1b0a48670> begin[:]
return[dictionary[[], []]]
if name[options].verbose begin[:]
call[name[message], parameter[binary_operation[constan... | keyword[def] identifier[input_file] ( identifier[filename] ):
literal[string]
keyword[if] identifier[excluded] ( identifier[filename] ) keyword[or] keyword[not] identifier[filename_match] ( identifier[filename] ):
keyword[return] {}
keyword[if] identifier[options] . identifier[verbose] :
... | def input_file(filename):
"""
Run all checks on a Python source file.
"""
if excluded(filename) or not filename_match(filename):
return {} # depends on [control=['if'], data=[]]
if options.verbose:
message('checking ' + filename) # depends on [control=['if'], data=[]]
options.c... |
def get_cgi_parameter_file(form: cgi.FieldStorage,
key: str) -> Optional[bytes]:
"""
Extracts a file's contents from a "file" input in a CGI form, or None
if no such file was uploaded.
"""
(filename, filecontents) = get_cgi_parameter_filename_and_file(form, key)
return... | def function[get_cgi_parameter_file, parameter[form, key]]:
constant[
Extracts a file's contents from a "file" input in a CGI form, or None
if no such file was uploaded.
]
<ast.Tuple object at 0x7da18c4cd0f0> assign[=] call[name[get_cgi_parameter_filename_and_file], parameter[name[form], nam... | keyword[def] identifier[get_cgi_parameter_file] ( identifier[form] : identifier[cgi] . identifier[FieldStorage] ,
identifier[key] : identifier[str] )-> identifier[Optional] [ identifier[bytes] ]:
literal[string]
( identifier[filename] , identifier[filecontents] )= identifier[get_cgi_parameter_filename_and_... | def get_cgi_parameter_file(form: cgi.FieldStorage, key: str) -> Optional[bytes]:
"""
Extracts a file's contents from a "file" input in a CGI form, or None
if no such file was uploaded.
"""
(filename, filecontents) = get_cgi_parameter_filename_and_file(form, key)
return filecontents |
def delete_course_completion(self, user_id, payload): # pylint: disable=unused-argument
"""
Delete a completion status previously sent to the Degreed Completion Status endpoint
Args:
user_id: Unused.
payload: JSON encoded object (serialized from DegreedLearnerDataTransm... | def function[delete_course_completion, parameter[self, user_id, payload]]:
constant[
Delete a completion status previously sent to the Degreed Completion Status endpoint
Args:
user_id: Unused.
payload: JSON encoded object (serialized from DegreedLearnerDataTransmissionAu... | keyword[def] identifier[delete_course_completion] ( identifier[self] , identifier[user_id] , identifier[payload] ):
literal[string]
keyword[return] identifier[self] . identifier[_delete] (
identifier[urljoin] (
identifier[self] . identifier[enterprise_configuration] . identifier[... | def delete_course_completion(self, user_id, payload): # pylint: disable=unused-argument
'\n Delete a completion status previously sent to the Degreed Completion Status endpoint\n\n Args:\n user_id: Unused.\n payload: JSON encoded object (serialized from DegreedLearnerDataTransmi... |
def complete(self):
"""
Consider a transcript complete if it has start and stop codons and
a coding sequence whose length is divisible by 3
"""
return (
self.contains_start_codon and
self.contains_stop_codon and
self.coding_sequence is not None... | def function[complete, parameter[self]]:
constant[
Consider a transcript complete if it has start and stop codons and
a coding sequence whose length is divisible by 3
]
return[<ast.BoolOp object at 0x7da1b08e7bb0>] | keyword[def] identifier[complete] ( identifier[self] ):
literal[string]
keyword[return] (
identifier[self] . identifier[contains_start_codon] keyword[and]
identifier[self] . identifier[contains_stop_codon] keyword[and]
identifier[self] . identifier[coding_sequence] k... | def complete(self):
"""
Consider a transcript complete if it has start and stop codons and
a coding sequence whose length is divisible by 3
"""
return self.contains_start_codon and self.contains_stop_codon and (self.coding_sequence is not None) and (len(self.coding_sequence) % 3 == 0) |
def get_comments_for_reference_on_date(self, reference_id, from_, to):
"""Pass through to provider CommentLookupSession.get_comments_for_reference_on_date"""
# Implemented from azosid template for -
# osid.relationship.RelationshipLookupSession.get_relationships_for_source_on_date_template
... | def function[get_comments_for_reference_on_date, parameter[self, reference_id, from_, to]]:
constant[Pass through to provider CommentLookupSession.get_comments_for_reference_on_date]
if call[name[self]._can, parameter[constant[lookup]]] begin[:]
return[call[name[self]._provider_session.get_comme... | keyword[def] identifier[get_comments_for_reference_on_date] ( identifier[self] , identifier[reference_id] , identifier[from_] , identifier[to] ):
literal[string]
keyword[if] identifier[self] . identifier[_can] ( literal[string] ):
keyword[return] identifier[self] . ... | def get_comments_for_reference_on_date(self, reference_id, from_, to):
"""Pass through to provider CommentLookupSession.get_comments_for_reference_on_date"""
# Implemented from azosid template for -
# osid.relationship.RelationshipLookupSession.get_relationships_for_source_on_date_template
if self._can(... |
def render_to_response(self, context, **response_kwargs):
"""
Returns a PDF response with a template rendered with the given context.
"""
filename = response_kwargs.pop('filename', None)
cmd_options = response_kwargs.pop('cmd_options', None)
if issubclass(self.response_c... | def function[render_to_response, parameter[self, context]]:
constant[
Returns a PDF response with a template rendered with the given context.
]
variable[filename] assign[=] call[name[response_kwargs].pop, parameter[constant[filename], constant[None]]]
variable[cmd_options] assign... | keyword[def] identifier[render_to_response] ( identifier[self] , identifier[context] ,** identifier[response_kwargs] ):
literal[string]
identifier[filename] = identifier[response_kwargs] . identifier[pop] ( literal[string] , keyword[None] )
identifier[cmd_options] = identifier[response_kwa... | def render_to_response(self, context, **response_kwargs):
"""
Returns a PDF response with a template rendered with the given context.
"""
filename = response_kwargs.pop('filename', None)
cmd_options = response_kwargs.pop('cmd_options', None)
if issubclass(self.response_class, PDFTemplate... |
def get_items_of_credit_note_per_page(self, credit_note_id, per_page=1000, page=1):
"""
Get items of credit note per page
:param credit_note_id: the credit note id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list... | def function[get_items_of_credit_note_per_page, parameter[self, credit_note_id, per_page, page]]:
constant[
Get items of credit note per page
:param credit_note_id: the credit note id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
... | keyword[def] identifier[get_items_of_credit_note_per_page] ( identifier[self] , identifier[credit_note_id] , identifier[per_page] = literal[int] , identifier[page] = literal[int] ):
literal[string]
keyword[return] identifier[self] . identifier[_get_resource_per_page] (
identifier[resource... | def get_items_of_credit_note_per_page(self, credit_note_id, per_page=1000, page=1):
"""
Get items of credit note per page
:param credit_note_id: the credit note id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list
... |
def _verify_cas1(ticket, service):
"""
Verifies CAS 1.0 authentication ticket.
:param: ticket
:param: service
Returns username on success and None on failure.
"""
params = {'ticket': ticket, 'service': service}
url = (urljoin(settings.CAS_SERVER_URL, 'validate') + '?' +
url... | def function[_verify_cas1, parameter[ticket, service]]:
constant[
Verifies CAS 1.0 authentication ticket.
:param: ticket
:param: service
Returns username on success and None on failure.
]
variable[params] assign[=] dictionary[[<ast.Constant object at 0x7da20e9563e0>, <ast.Constant ... | keyword[def] identifier[_verify_cas1] ( identifier[ticket] , identifier[service] ):
literal[string]
identifier[params] ={ literal[string] : identifier[ticket] , literal[string] : identifier[service] }
identifier[url] =( identifier[urljoin] ( identifier[settings] . identifier[CAS_SERVER_URL] , literal... | def _verify_cas1(ticket, service):
"""
Verifies CAS 1.0 authentication ticket.
:param: ticket
:param: service
Returns username on success and None on failure.
"""
params = {'ticket': ticket, 'service': service}
url = urljoin(settings.CAS_SERVER_URL, 'validate') + '?' + urlencode(params... |
def __focus(self, item):
"""Called when focus item has changed"""
cols = self.__get_display_columns()
for col in cols:
self.__event_info =(col,item)
self.event_generate('<<TreeviewInplaceEdit>>')
if col in self._inplace_widgets:
w = self._inpla... | def function[__focus, parameter[self, item]]:
constant[Called when focus item has changed]
variable[cols] assign[=] call[name[self].__get_display_columns, parameter[]]
for taget[name[col]] in starred[name[cols]] begin[:]
name[self].__event_info assign[=] tuple[[<ast.Name object a... | keyword[def] identifier[__focus] ( identifier[self] , identifier[item] ):
literal[string]
identifier[cols] = identifier[self] . identifier[__get_display_columns] ()
keyword[for] identifier[col] keyword[in] identifier[cols] :
identifier[self] . identifier[__event_info] =( id... | def __focus(self, item):
"""Called when focus item has changed"""
cols = self.__get_display_columns()
for col in cols:
self.__event_info = (col, item)
self.event_generate('<<TreeviewInplaceEdit>>')
if col in self._inplace_widgets:
w = self._inplace_widgets[col]
... |
def cross_origin(app, *args, **kwargs):
"""
This function is the decorator which is used to wrap a Sanic route with.
In the simplest case, simply use the default parameters to allow all
origins in what is the most permissive configuration. If this method
modifies state or performs authentication whi... | def function[cross_origin, parameter[app]]:
constant[
This function is the decorator which is used to wrap a Sanic route with.
In the simplest case, simply use the default parameters to allow all
origins in what is the most permissive configuration. If this method
modifies state or performs auth... | keyword[def] identifier[cross_origin] ( identifier[app] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[_options] = identifier[kwargs]
identifier[_real_decorator] = identifier[cors] . identifier[decorate] ( identifier[app] ,* identifier[args] , identifier[run_middleware] = ke... | def cross_origin(app, *args, **kwargs):
"""
This function is the decorator which is used to wrap a Sanic route with.
In the simplest case, simply use the default parameters to allow all
origins in what is the most permissive configuration. If this method
modifies state or performs authentication whi... |
def get_rand_Japprox(s, params, num_inds=1000, include_cost=False, **kwargs):
"""
Calculates a random approximation to J by returning J only at a
set of random pixel/voxel locations.
Parameters
----------
s : :class:`peri.states.State`
The state to calculate J for.
param... | def function[get_rand_Japprox, parameter[s, params, num_inds, include_cost]]:
constant[
Calculates a random approximation to J by returning J only at a
set of random pixel/voxel locations.
Parameters
----------
s : :class:`peri.states.State`
The state to calculate J for.
... | keyword[def] identifier[get_rand_Japprox] ( identifier[s] , identifier[params] , identifier[num_inds] = literal[int] , identifier[include_cost] = keyword[False] ,** identifier[kwargs] ):
literal[string]
identifier[start_time] = identifier[time] . identifier[time] ()
identifier[tot_pix] = identifier[s]... | def get_rand_Japprox(s, params, num_inds=1000, include_cost=False, **kwargs):
"""
Calculates a random approximation to J by returning J only at a
set of random pixel/voxel locations.
Parameters
----------
s : :class:`peri.states.State`
The state to calculate J for.
param... |
def image(self, name, x=None, y=None, w=0,h=0,type='',link=''):
"Put an image on the page"
if not name in self.images:
#First use of image, get info
if(type==''):
pos=name.rfind('.')
if(not pos):
self.error('image file has no ex... | def function[image, parameter[self, name, x, y, w, h, type, link]]:
constant[Put an image on the page]
if <ast.UnaryOp object at 0x7da1b1de3bb0> begin[:]
if compare[name[type] equal[==] constant[]] begin[:]
variable[pos] assign[=] call[name[name].rfind, parameter[... | keyword[def] identifier[image] ( identifier[self] , identifier[name] , identifier[x] = keyword[None] , identifier[y] = keyword[None] , identifier[w] = literal[int] , identifier[h] = literal[int] , identifier[type] = literal[string] , identifier[link] = literal[string] ):
literal[string]
keyword[if]... | def image(self, name, x=None, y=None, w=0, h=0, type='', link=''):
"""Put an image on the page"""
if not name in self.images:
#First use of image, get info
if type == '':
pos = name.rfind('.')
if not pos:
self.error('image file has no extension and no type... |
def predict_proba(self, data, ntree_limit=None, validate_features=True):
"""
Predict the probability of each `data` example being of a given class.
.. note:: This function is not thread safe
For each booster object, predict can only be called from one thread.
If you wan... | def function[predict_proba, parameter[self, data, ntree_limit, validate_features]]:
constant[
Predict the probability of each `data` example being of a given class.
.. note:: This function is not thread safe
For each booster object, predict can only be called from one thread.
... | keyword[def] identifier[predict_proba] ( identifier[self] , identifier[data] , identifier[ntree_limit] = keyword[None] , identifier[validate_features] = keyword[True] ):
literal[string]
identifier[test_dmatrix] = identifier[DMatrix] ( identifier[data] , identifier[missing] = identifier[self] . iden... | def predict_proba(self, data, ntree_limit=None, validate_features=True):
"""
Predict the probability of each `data` example being of a given class.
.. note:: This function is not thread safe
For each booster object, predict can only be called from one thread.
If you want to... |
def add_months(months, timestamp=datetime.datetime.utcnow()):
"""Add a number of months to a timestamp"""
month = timestamp.month
new_month = month + months
years = 0
while new_month < 1:
new_month += 12
years -= 1
while new_month > 12:
new_month -= 12
y... | def function[add_months, parameter[months, timestamp]]:
constant[Add a number of months to a timestamp]
variable[month] assign[=] name[timestamp].month
variable[new_month] assign[=] binary_operation[name[month] + name[months]]
variable[years] assign[=] constant[0]
while compare[n... | keyword[def] identifier[add_months] ( identifier[months] , identifier[timestamp] = identifier[datetime] . identifier[datetime] . identifier[utcnow] ()):
literal[string]
identifier[month] = identifier[timestamp] . identifier[month]
identifier[new_month] = identifier[month] + identifier[months]
i... | def add_months(months, timestamp=datetime.datetime.utcnow()):
"""Add a number of months to a timestamp"""
month = timestamp.month
new_month = month + months
years = 0
while new_month < 1:
new_month += 12
years -= 1 # depends on [control=['while'], data=['new_month']]
while new_m... |
def get_wegsegment_by_id(self, id):
'''
Retrieve a `wegsegment` by the Id.
:param integer id: the Id of the `wegsegment`
:rtype: :class:`Wegsegment`
'''
def creator():
res = crab_gateway_request(
self.client,
'GetWegsegmentById... | def function[get_wegsegment_by_id, parameter[self, id]]:
constant[
Retrieve a `wegsegment` by the Id.
:param integer id: the Id of the `wegsegment`
:rtype: :class:`Wegsegment`
]
def function[creator, parameter[]]:
variable[res] assign[=] call[name[crab_ga... | keyword[def] identifier[get_wegsegment_by_id] ( identifier[self] , identifier[id] ):
literal[string]
keyword[def] identifier[creator] ():
identifier[res] = identifier[crab_gateway_request] (
identifier[self] . identifier[client] ,
literal[string] , identifier... | def get_wegsegment_by_id(self, id):
"""
Retrieve a `wegsegment` by the Id.
:param integer id: the Id of the `wegsegment`
:rtype: :class:`Wegsegment`
"""
def creator():
res = crab_gateway_request(self.client, 'GetWegsegmentByIdentificatorWegsegment', id)
if res =... |
def rebuild( self ):
"""
Rebuilds the user interface buttons for this widget.
"""
self.setUpdatesEnabled(False)
# sync up the toolbuttons with our actions
actions = self._actionGroup.actions()
btns = self.findChildren(QToolButton)
hori... | def function[rebuild, parameter[self]]:
constant[
Rebuilds the user interface buttons for this widget.
]
call[name[self].setUpdatesEnabled, parameter[constant[False]]]
variable[actions] assign[=] call[name[self]._actionGroup.actions, parameter[]]
variable[btns] assign[=] ... | keyword[def] identifier[rebuild] ( identifier[self] ):
literal[string]
identifier[self] . identifier[setUpdatesEnabled] ( keyword[False] )
identifier[actions] = identifier[self] . identifier[_actionGroup] . identifier[actions] ()
identifier[btns] = identifier[self]... | def rebuild(self):
"""
Rebuilds the user interface buttons for this widget.
"""
self.setUpdatesEnabled(False) # sync up the toolbuttons with our actions
actions = self._actionGroup.actions()
btns = self.findChildren(QToolButton)
horiz = self.direction() in (QBoxLayout.LeftToRight, Q... |
def _dpi(self, resolution_tag):
"""
Return the dpi value calculated for *resolution_tag*, which can be
either TIFF_TAG.X_RESOLUTION or TIFF_TAG.Y_RESOLUTION. The
calculation is based on the values of both that tag and the
TIFF_TAG.RESOLUTION_UNIT tag in this parser's |_IfdEntries... | def function[_dpi, parameter[self, resolution_tag]]:
constant[
Return the dpi value calculated for *resolution_tag*, which can be
either TIFF_TAG.X_RESOLUTION or TIFF_TAG.Y_RESOLUTION. The
calculation is based on the values of both that tag and the
TIFF_TAG.RESOLUTION_UNIT tag in... | keyword[def] identifier[_dpi] ( identifier[self] , identifier[resolution_tag] ):
literal[string]
identifier[ifd_entries] = identifier[self] . identifier[_ifd_entries]
keyword[if] identifier[resolution_tag] keyword[not] keyword[in] identifier[ifd_entries] :
keyword[return... | def _dpi(self, resolution_tag):
"""
Return the dpi value calculated for *resolution_tag*, which can be
either TIFF_TAG.X_RESOLUTION or TIFF_TAG.Y_RESOLUTION. The
calculation is based on the values of both that tag and the
TIFF_TAG.RESOLUTION_UNIT tag in this parser's |_IfdEntries| in... |
def read(path, encoding="UTF-8"):
"""Read and return content from file *path*"""
with OPEN_FUNC(path, 'rb') as _file:
cont = _file.read()
return cont.decode(encoding) | def function[read, parameter[path, encoding]]:
constant[Read and return content from file *path*]
with call[name[OPEN_FUNC], parameter[name[path], constant[rb]]] begin[:]
variable[cont] assign[=] call[name[_file].read, parameter[]]
return[call[name[cont].decode, parameter[name[en... | keyword[def] identifier[read] ( identifier[path] , identifier[encoding] = literal[string] ):
literal[string]
keyword[with] identifier[OPEN_FUNC] ( identifier[path] , literal[string] ) keyword[as] identifier[_file] :
identifier[cont] = identifier[_file] . identifier[read] ()
keyword[retu... | def read(path, encoding='UTF-8'):
"""Read and return content from file *path*"""
with OPEN_FUNC(path, 'rb') as _file:
cont = _file.read()
return cont.decode(encoding) # depends on [control=['with'], data=['_file']] |
def start_view_change(self, proposed_view_no: int, continue_vc=False):
"""
Trigger the view change process.
:param proposed_view_no: the new view number after view change.
"""
# TODO: consider moving this to pool manager
# TODO: view change is a special case, which can h... | def function[start_view_change, parameter[self, proposed_view_no, continue_vc]]:
constant[
Trigger the view change process.
:param proposed_view_no: the new view number after view change.
]
if <ast.BoolOp object at 0x7da2047e97b0> begin[:]
name[self].pre_view_cha... | keyword[def] identifier[start_view_change] ( identifier[self] , identifier[proposed_view_no] : identifier[int] , identifier[continue_vc] = keyword[False] ):
literal[string]
keyword[if] identifier[self] . identifier[pre_vc_strategy] keyword[and] ( keyword[not] identifi... | def start_view_change(self, proposed_view_no: int, continue_vc=False):
"""
Trigger the view change process.
:param proposed_view_no: the new view number after view change.
"""
# TODO: consider moving this to pool manager
# TODO: view change is a special case, which can have differen... |
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: ... | def function[_ensure_running, parameter[name, no_start, path]]:
constant[
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
... | keyword[def] identifier[_ensure_running] ( identifier[name] , identifier[no_start] = keyword[False] , identifier[path] = keyword[None] ):
literal[string]
identifier[_ensure_exists] ( identifier[name] , identifier[path] = identifier[path] )
identifier[pre] = identifier[state] ( identifier[name] , ident... | def _ensure_running(name, no_start=False, path=None):
"""
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: ... |
def convert_images_to_pil(self, images, dither, nq=0, images_info=None):
""" convert_images_to_pil(images, nq=0)
Convert images to Paletted PIL images, which can then be
written to a single animaged GIF.
"""
# Convert to PIL images
images2 = []
for im in images... | def function[convert_images_to_pil, parameter[self, images, dither, nq, images_info]]:
constant[ convert_images_to_pil(images, nq=0)
Convert images to Paletted PIL images, which can then be
written to a single animaged GIF.
]
variable[images2] assign[=] list[[]]
for tag... | keyword[def] identifier[convert_images_to_pil] ( identifier[self] , identifier[images] , identifier[dither] , identifier[nq] = literal[int] , identifier[images_info] = keyword[None] ):
literal[string]
identifier[images2] =[]
keyword[for] identifier[im] keyword[in] identifier[i... | def convert_images_to_pil(self, images, dither, nq=0, images_info=None):
""" convert_images_to_pil(images, nq=0)
Convert images to Paletted PIL images, which can then be
written to a single animaged GIF.
"""
# Convert to PIL images
images2 = []
for im in images:
if isin... |
def clean(inst):
"""Routine to return FPMU data cleaned to the specified level
Parameters
-----------
inst : (pysat.Instrument)
Instrument class object, whose attribute clean_level is used to return
the desired level of data selectivity.
Returns
--------
Void : (NoneType)
... | def function[clean, parameter[inst]]:
constant[Routine to return FPMU data cleaned to the specified level
Parameters
-----------
inst : (pysat.Instrument)
Instrument class object, whose attribute clean_level is used to return
the desired level of data selectivity.
Returns
-... | keyword[def] identifier[clean] ( identifier[inst] ):
literal[string]
identifier[inst] . identifier[data] . identifier[replace] (- literal[int] , identifier[np] . identifier[nan] , identifier[inplace] = keyword[True] )
identifier[inst] . identifier[data] . identifier[replace] (- literal[int] , identif... | def clean(inst):
"""Routine to return FPMU data cleaned to the specified level
Parameters
-----------
inst : (pysat.Instrument)
Instrument class object, whose attribute clean_level is used to return
the desired level of data selectivity.
Returns
--------
Void : (NoneType)
... |
def _serialize(self, value, ct):
"""Auto-serialization of the value based upon the content-type value.
:param any value: The value to serialize
:param ietfparse.: The content type to serialize
:rtype: str
:raises: ValueError
"""
key = '{}/{}'.format(ct.content_t... | def function[_serialize, parameter[self, value, ct]]:
constant[Auto-serialization of the value based upon the content-type value.
:param any value: The value to serialize
:param ietfparse.: The content type to serialize
:rtype: str
:raises: ValueError
]
variable... | keyword[def] identifier[_serialize] ( identifier[self] , identifier[value] , identifier[ct] ):
literal[string]
identifier[key] = literal[string] . identifier[format] ( identifier[ct] . identifier[content_type] , identifier[ct] . identifier[content_subtype] )
keyword[if] identifier[key] k... | def _serialize(self, value, ct):
"""Auto-serialization of the value based upon the content-type value.
:param any value: The value to serialize
:param ietfparse.: The content type to serialize
:rtype: str
:raises: ValueError
"""
key = '{}/{}'.format(ct.content_type, ct.... |
def generate_docker_bashscript_file(temp_dir, docker_dir, globs, cmd, job_name):
'''
Creates a bashscript to inject into a docker container for the job.
This script wraps the job command(s) given in a bash script, hard links the
outputs and returns an "rc" file containing the exit code. All of this is... | def function[generate_docker_bashscript_file, parameter[temp_dir, docker_dir, globs, cmd, job_name]]:
constant[
Creates a bashscript to inject into a docker container for the job.
This script wraps the job command(s) given in a bash script, hard links the
outputs and returns an "rc" file containing... | keyword[def] identifier[generate_docker_bashscript_file] ( identifier[temp_dir] , identifier[docker_dir] , identifier[globs] , identifier[cmd] , identifier[job_name] ):
literal[string]
identifier[wdl_copyright] = identifier[heredoc_wdl] ( literal[string] )
identifier[prefix_dict] ={ literal[string] : ... | def generate_docker_bashscript_file(temp_dir, docker_dir, globs, cmd, job_name):
"""
Creates a bashscript to inject into a docker container for the job.
This script wraps the job command(s) given in a bash script, hard links the
outputs and returns an "rc" file containing the exit code. All of this is... |
def _page_to_text(page):
"""Extract the text from a page.
Args:
page: a unicode string
Returns:
a unicode string
"""
# text start tag looks like "<text ..otherstuff>"
start_pos = page.find(u"<text")
assert start_pos != -1
end_tag_pos = page.find(u">", start_pos)
assert end_tag_pos != -1
end... | def function[_page_to_text, parameter[page]]:
constant[Extract the text from a page.
Args:
page: a unicode string
Returns:
a unicode string
]
variable[start_pos] assign[=] call[name[page].find, parameter[constant[<text]]]
assert[compare[name[start_pos] not_equal[!=] <ast.UnaryOp objec... | keyword[def] identifier[_page_to_text] ( identifier[page] ):
literal[string]
identifier[start_pos] = identifier[page] . identifier[find] ( literal[string] )
keyword[assert] identifier[start_pos] !=- literal[int]
identifier[end_tag_pos] = identifier[page] . identifier[find] ( literal[string] , identi... | def _page_to_text(page):
"""Extract the text from a page.
Args:
page: a unicode string
Returns:
a unicode string
"""
# text start tag looks like "<text ..otherstuff>"
start_pos = page.find(u'<text')
assert start_pos != -1
end_tag_pos = page.find(u'>', start_pos)
assert end_tag_pos... |
def _register_bench_extension(self, plugin_name, plugin_instance):
"""
Register a bench extension.
:param plugin_name: Plugin name
:param plugin_instance: PluginBase
:return: Nothing
"""
for attr in plugin_instance.get_bench_api().keys():
if hasattr(s... | def function[_register_bench_extension, parameter[self, plugin_name, plugin_instance]]:
constant[
Register a bench extension.
:param plugin_name: Plugin name
:param plugin_instance: PluginBase
:return: Nothing
]
for taget[name[attr]] in starred[call[call[name[plu... | keyword[def] identifier[_register_bench_extension] ( identifier[self] , identifier[plugin_name] , identifier[plugin_instance] ):
literal[string]
keyword[for] identifier[attr] keyword[in] identifier[plugin_instance] . identifier[get_bench_api] (). identifier[keys] ():
keyword[if] id... | def _register_bench_extension(self, plugin_name, plugin_instance):
"""
Register a bench extension.
:param plugin_name: Plugin name
:param plugin_instance: PluginBase
:return: Nothing
"""
for attr in plugin_instance.get_bench_api().keys():
if hasattr(self.bench, a... |
def shear(cls, x_angle=0, y_angle=0):
"""Create a shear transform along one or both axes.
:param x_angle: Angle in degrees to shear along the x-axis.
:type x_angle: float
:param y_angle: Angle in degrees to shear along the y-axis.
:type y_angle: float
:rtype: Affine
... | def function[shear, parameter[cls, x_angle, y_angle]]:
constant[Create a shear transform along one or both axes.
:param x_angle: Angle in degrees to shear along the x-axis.
:type x_angle: float
:param y_angle: Angle in degrees to shear along the y-axis.
:type y_angle: float
... | keyword[def] identifier[shear] ( identifier[cls] , identifier[x_angle] = literal[int] , identifier[y_angle] = literal[int] ):
literal[string]
identifier[sx] = identifier[math] . identifier[tan] ( identifier[math] . identifier[radians] ( identifier[x_angle] ))
identifier[sy] = identifier[ma... | def shear(cls, x_angle=0, y_angle=0):
"""Create a shear transform along one or both axes.
:param x_angle: Angle in degrees to shear along the x-axis.
:type x_angle: float
:param y_angle: Angle in degrees to shear along the y-axis.
:type y_angle: float
:rtype: Affine
... |
def get_hex(self, signed=True):
"""
Given all the data the user has given so far, make the hex using pybitcointools
"""
total_ins_satoshi = self.total_input_satoshis()
if total_ins_satoshi == 0:
raise ValueError("Can't make transaction, there are zero inputs")
... | def function[get_hex, parameter[self, signed]]:
constant[
Given all the data the user has given so far, make the hex using pybitcointools
]
variable[total_ins_satoshi] assign[=] call[name[self].total_input_satoshis, parameter[]]
if compare[name[total_ins_satoshi] equal[==] consta... | keyword[def] identifier[get_hex] ( identifier[self] , identifier[signed] = keyword[True] ):
literal[string]
identifier[total_ins_satoshi] = identifier[self] . identifier[total_input_satoshis] ()
keyword[if] identifier[total_ins_satoshi] == literal[int] :
keyword[raise] ident... | def get_hex(self, signed=True):
"""
Given all the data the user has given so far, make the hex using pybitcointools
"""
total_ins_satoshi = self.total_input_satoshis()
if total_ins_satoshi == 0:
raise ValueError("Can't make transaction, there are zero inputs") # depends on [control=... |
def ajax_only(view_func):
"""Required the view is only accessed via AJAX."""
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if request.is_ajax():
return view_func(request, *args, **kwargs)
else:
return http.HttpRes... | def function[ajax_only, parameter[view_func]]:
constant[Required the view is only accessed via AJAX.]
def function[_wrapped_view, parameter[request]]:
if call[name[request].is_ajax, parameter[]] begin[:]
return[call[name[view_func], parameter[name[request], <ast.Starred objec... | keyword[def] identifier[ajax_only] ( identifier[view_func] ):
literal[string]
@ identifier[wraps] ( identifier[view_func] , identifier[assigned] = identifier[available_attrs] ( identifier[view_func] ))
keyword[def] identifier[_wrapped_view] ( identifier[request] ,* identifier[args] ,** identifier[kwa... | def ajax_only(view_func):
"""Required the view is only accessed via AJAX."""
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if request.is_ajax():
return view_func(request, *args, **kwargs) # depends on [control=['if'], data=[]]
... |
def heuristic_crossover(random, candidates, args):
"""Return the offspring of heuristic crossover on the candidates.
It performs heuristic crossover (HX), which is similar to the
update rule used in particle swarm optimization. This function
also makes use of the bounder function as specified in the ... | def function[heuristic_crossover, parameter[random, candidates, args]]:
constant[Return the offspring of heuristic crossover on the candidates.
It performs heuristic crossover (HX), which is similar to the
update rule used in particle swarm optimization. This function
also makes use of the bounde... | keyword[def] identifier[heuristic_crossover] ( identifier[random] , identifier[candidates] , identifier[args] ):
literal[string]
identifier[crossover_rate] = identifier[args] . identifier[setdefault] ( literal[string] , literal[int] )
identifier[bounder] = identifier[args] [ literal[string] ]. identif... | def heuristic_crossover(random, candidates, args):
"""Return the offspring of heuristic crossover on the candidates.
It performs heuristic crossover (HX), which is similar to the
update rule used in particle swarm optimization. This function
also makes use of the bounder function as specified in the ... |
def _loadServices(self):
"""
Load module services.
:return: <void>
"""
servicesPath = os.path.join(self.path, "service")
if not os.path.isdir(servicesPath):
return
self._scanDirectoryForServices(servicesPath) | def function[_loadServices, parameter[self]]:
constant[
Load module services.
:return: <void>
]
variable[servicesPath] assign[=] call[name[os].path.join, parameter[name[self].path, constant[service]]]
if <ast.UnaryOp object at 0x7da18bc701c0> begin[:]
return[None... | keyword[def] identifier[_loadServices] ( identifier[self] ):
literal[string]
identifier[servicesPath] = identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[path] , literal[string] )
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[i... | def _loadServices(self):
"""
Load module services.
:return: <void>
"""
servicesPath = os.path.join(self.path, 'service')
if not os.path.isdir(servicesPath):
return # depends on [control=['if'], data=[]]
self._scanDirectoryForServices(servicesPath) |
def stop_ppp_link(self):
'''stop the link'''
if self.ppp_fd == -1:
return
try:
self.mpself.select_extra.pop(self.ppp_fd)
os.close(self.ppp_fd)
os.waitpid(self.pid, 0)
except Exception:
pass
self.pid = -1
self.ppp... | def function[stop_ppp_link, parameter[self]]:
constant[stop the link]
if compare[name[self].ppp_fd equal[==] <ast.UnaryOp object at 0x7da18ede4730>] begin[:]
return[None]
<ast.Try object at 0x7da18ede4f70>
name[self].pid assign[=] <ast.UnaryOp object at 0x7da18ede6920>
name[s... | keyword[def] identifier[stop_ppp_link] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[ppp_fd] ==- literal[int] :
keyword[return]
keyword[try] :
identifier[self] . identifier[mpself] . identifier[select_extra] . identifier[pop] ( ... | def stop_ppp_link(self):
"""stop the link"""
if self.ppp_fd == -1:
return # depends on [control=['if'], data=[]]
try:
self.mpself.select_extra.pop(self.ppp_fd)
os.close(self.ppp_fd)
os.waitpid(self.pid, 0) # depends on [control=['try'], data=[]]
except Exception:
... |
def from_inline(cls: Type[RevocationType], version: int, currency: str, inline: str) -> RevocationType:
"""
Return Revocation document instance from inline string
Only self.pubkey is populated.
You must populate self.identity with an Identity instance to use raw/sign/signed_raw methods
... | def function[from_inline, parameter[cls, version, currency, inline]]:
constant[
Return Revocation document instance from inline string
Only self.pubkey is populated.
You must populate self.identity with an Identity instance to use raw/sign/signed_raw methods
:param version: Ver... | keyword[def] identifier[from_inline] ( identifier[cls] : identifier[Type] [ identifier[RevocationType] ], identifier[version] : identifier[int] , identifier[currency] : identifier[str] , identifier[inline] : identifier[str] )-> identifier[RevocationType] :
literal[string]
identifier[cert_data] = id... | def from_inline(cls: Type[RevocationType], version: int, currency: str, inline: str) -> RevocationType:
"""
Return Revocation document instance from inline string
Only self.pubkey is populated.
You must populate self.identity with an Identity instance to use raw/sign/signed_raw methods
... |
def require_oauth(self, realm=None, require_resource_owner=True,
require_verifier=False, require_realm=False):
"""Mark the view function f as a protected resource"""
def decorator(f):
@wraps(f)
def verify_request(*args, **kwargs):
"""Verify OAuth para... | def function[require_oauth, parameter[self, realm, require_resource_owner, require_verifier, require_realm]]:
constant[Mark the view function f as a protected resource]
def function[decorator, parameter[f]]:
def function[verify_request, parameter[]]:
constant[Veri... | keyword[def] identifier[require_oauth] ( identifier[self] , identifier[realm] = keyword[None] , identifier[require_resource_owner] = keyword[True] ,
identifier[require_verifier] = keyword[False] , identifier[require_realm] = keyword[False] ):
literal[string]
keyword[def] identifier[decorator] ( ... | def require_oauth(self, realm=None, require_resource_owner=True, require_verifier=False, require_realm=False):
"""Mark the view function f as a protected resource"""
def decorator(f):
@wraps(f)
def verify_request(*args, **kwargs):
"""Verify OAuth params before running view function... |
def sep_dist_floc(ConcAluminum, ConcClay, coag, material,
DIM_FRACTAL, DiamTarget):
"""Return separation distance as a function of floc size."""
return (material.Diameter
* (np.pi/(6
* frac_vol_floc_initial(ConcAluminum, ConcClay,
... | def function[sep_dist_floc, parameter[ConcAluminum, ConcClay, coag, material, DIM_FRACTAL, DiamTarget]]:
constant[Return separation distance as a function of floc size.]
return[binary_operation[binary_operation[name[material].Diameter * binary_operation[binary_operation[name[np].pi / binary_operation[consta... | keyword[def] identifier[sep_dist_floc] ( identifier[ConcAluminum] , identifier[ConcClay] , identifier[coag] , identifier[material] ,
identifier[DIM_FRACTAL] , identifier[DiamTarget] ):
literal[string]
keyword[return] ( identifier[material] . identifier[Diameter]
*( identifier[np] . identifier[pi] /( ... | def sep_dist_floc(ConcAluminum, ConcClay, coag, material, DIM_FRACTAL, DiamTarget):
"""Return separation distance as a function of floc size."""
return material.Diameter * (np.pi / (6 * frac_vol_floc_initial(ConcAluminum, ConcClay, coag, material))) ** (1 / 3) * (DiamTarget / material.Diameter) ** (DIM_FRACTAL ... |
def _MI_setitem(self, args, value):
'Separate __setitem__ function of MIMapping'
indices = self.indices
N = len(indices)
empty = N == 0
if empty: # init the dict
index1, key, index2, index1_last = MI_parse_args(self, args, allow_new=True)
exist_names = [index1]
item = [key]
... | def function[_MI_setitem, parameter[self, args, value]]:
constant[Separate __setitem__ function of MIMapping]
variable[indices] assign[=] name[self].indices
variable[N] assign[=] call[name[len], parameter[name[indices]]]
variable[empty] assign[=] compare[name[N] equal[==] constant[0]]
... | keyword[def] identifier[_MI_setitem] ( identifier[self] , identifier[args] , identifier[value] ):
literal[string]
identifier[indices] = identifier[self] . identifier[indices]
identifier[N] = identifier[len] ( identifier[indices] )
identifier[empty] = identifier[N] == literal[int]
keyword[i... | def _MI_setitem(self, args, value):
"""Separate __setitem__ function of MIMapping"""
indices = self.indices
N = len(indices)
empty = N == 0
if empty: # init the dict
(index1, key, index2, index1_last) = MI_parse_args(self, args, allow_new=True)
exist_names = [index1]
item = ... |
def pyramid_synthesis(Gs, cap, pe, order=30, **kwargs):
r"""Synthesize a signal from its pyramid coefficients.
Parameters
----------
Gs : Array of Graphs
A multiresolution sequence of graph structures.
cap : ndarray
Coarsest approximation of the original signal.
pe : ndarray
... | def function[pyramid_synthesis, parameter[Gs, cap, pe, order]]:
constant[Synthesize a signal from its pyramid coefficients.
Parameters
----------
Gs : Array of Graphs
A multiresolution sequence of graph structures.
cap : ndarray
Coarsest approximation of the original signal.
... | keyword[def] identifier[pyramid_synthesis] ( identifier[Gs] , identifier[cap] , identifier[pe] , identifier[order] = literal[int] ,** identifier[kwargs] ):
literal[string]
identifier[least_squares] = identifier[bool] ( identifier[kwargs] . identifier[pop] ( literal[string] , keyword[False] ))
identifi... | def pyramid_synthesis(Gs, cap, pe, order=30, **kwargs):
"""Synthesize a signal from its pyramid coefficients.
Parameters
----------
Gs : Array of Graphs
A multiresolution sequence of graph structures.
cap : ndarray
Coarsest approximation of the original signal.
pe : ndarray
... |
def render_to_response(self, context, indent=None):
"Returns a JSON response containing 'context' as payload"
return self.get_json_response(self.convert_context_to_json(context, indent=indent)) | def function[render_to_response, parameter[self, context, indent]]:
constant[Returns a JSON response containing 'context' as payload]
return[call[name[self].get_json_response, parameter[call[name[self].convert_context_to_json, parameter[name[context]]]]]] | keyword[def] identifier[render_to_response] ( identifier[self] , identifier[context] , identifier[indent] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[get_json_response] ( identifier[self] . identifier[convert_context_to_json] ( identifier[context] , identifier[... | def render_to_response(self, context, indent=None):
"""Returns a JSON response containing 'context' as payload"""
return self.get_json_response(self.convert_context_to_json(context, indent=indent)) |
def format_message(self, evr_hist_data):
''' Format EVR message with EVR data
Given a byte array of EVR data, format the EVR's message attribute
printf format strings and split the byte array into appropriately
sized chunks. Supports most format strings containing length and type
... | def function[format_message, parameter[self, evr_hist_data]]:
constant[ Format EVR message with EVR data
Given a byte array of EVR data, format the EVR's message attribute
printf format strings and split the byte array into appropriately
sized chunks. Supports most format strings contai... | keyword[def] identifier[format_message] ( identifier[self] , identifier[evr_hist_data] ):
literal[string]
identifier[size_formatter_info] ={
literal[string] :- literal[int] ,
literal[string] : literal[int] ,
literal[string] : literal[int] ,
literal[string] : lite... | def format_message(self, evr_hist_data):
""" Format EVR message with EVR data
Given a byte array of EVR data, format the EVR's message attribute
printf format strings and split the byte array into appropriately
sized chunks. Supports most format strings containing length and type
fi... |
def dump(self):
"""Return the object itself."""
return {
'title': self.title,
'issue_id': self.issue_id,
'reporter': self.reporter,
'assignee': self.assignee,
'status': self.status,
'product': self.product,
'component':... | def function[dump, parameter[self]]:
constant[Return the object itself.]
return[dictionary[[<ast.Constant object at 0x7da1b0fc78b0>, <ast.Constant object at 0x7da1b0fc6890>, <ast.Constant object at 0x7da1b0d3e1d0>, <ast.Constant object at 0x7da1b0d3ea40>, <ast.Constant object at 0x7da1b0d3c8b0>, <ast.Consta... | keyword[def] identifier[dump] ( identifier[self] ):
literal[string]
keyword[return] {
literal[string] : identifier[self] . identifier[title] ,
literal[string] : identifier[self] . identifier[issue_id] ,
literal[string] : identifier[self] . identifier[reporter] ,
... | def dump(self):
"""Return the object itself."""
return {'title': self.title, 'issue_id': self.issue_id, 'reporter': self.reporter, 'assignee': self.assignee, 'status': self.status, 'product': self.product, 'component': self.component, 'created_at': self.created_at, 'updated_at': self.updated_at, 'closed_at': se... |
def global_position_int_cov_encode(self, time_boot_ms, time_utc, estimator_type, lat, lon, alt, relative_alt, vx, vy, vz, covariance):
'''
The filtered global position (e.g. fused GPS and accelerometers). The
position is in GPS-frame (right-handed, Z-up). It is
... | def function[global_position_int_cov_encode, parameter[self, time_boot_ms, time_utc, estimator_type, lat, lon, alt, relative_alt, vx, vy, vz, covariance]]:
constant[
The filtered global position (e.g. fused GPS and accelerometers). The
position is in GPS-frame (right-handed, Z-up... | keyword[def] identifier[global_position_int_cov_encode] ( identifier[self] , identifier[time_boot_ms] , identifier[time_utc] , identifier[estimator_type] , identifier[lat] , identifier[lon] , identifier[alt] , identifier[relative_alt] , identifier[vx] , identifier[vy] , identifier[vz] , identifier[covariance] ):
... | def global_position_int_cov_encode(self, time_boot_ms, time_utc, estimator_type, lat, lon, alt, relative_alt, vx, vy, vz, covariance):
"""
The filtered global position (e.g. fused GPS and accelerometers). The
position is in GPS-frame (right-handed, Z-up). It is
desig... |
def shards(self, add_shard=False):
"""Get a list of shards belonging to this instance.
:param bool add_shard: A boolean indicating whether to add a new shard to the specified
instance.
"""
url = self._service_url + 'shards/'
if add_shard:
response = reque... | def function[shards, parameter[self, add_shard]]:
constant[Get a list of shards belonging to this instance.
:param bool add_shard: A boolean indicating whether to add a new shard to the specified
instance.
]
variable[url] assign[=] binary_operation[name[self]._service_url + ... | keyword[def] identifier[shards] ( identifier[self] , identifier[add_shard] = keyword[False] ):
literal[string]
identifier[url] = identifier[self] . identifier[_service_url] + literal[string]
keyword[if] identifier[add_shard] :
identifier[response] = identifier[requests] . id... | def shards(self, add_shard=False):
"""Get a list of shards belonging to this instance.
:param bool add_shard: A boolean indicating whether to add a new shard to the specified
instance.
"""
url = self._service_url + 'shards/'
if add_shard:
response = requests.post(url, **... |
def get_SCAT_box(slope, x_mean, y_mean, beta_threshold = .1):
"""
takes in data and returns information about SCAT box:
the largest possible x_value, the largest possible y_value,
and functions for the two bounding lines of the box
"""
# if beta_threshold is -999, that means null
if beta_thr... | def function[get_SCAT_box, parameter[slope, x_mean, y_mean, beta_threshold]]:
constant[
takes in data and returns information about SCAT box:
the largest possible x_value, the largest possible y_value,
and functions for the two bounding lines of the box
]
if compare[name[beta_threshold] ... | keyword[def] identifier[get_SCAT_box] ( identifier[slope] , identifier[x_mean] , identifier[y_mean] , identifier[beta_threshold] = literal[int] ):
literal[string]
keyword[if] identifier[beta_threshold] ==- literal[int] :
identifier[beta_threshold] = literal[int]
identifier[slope_err_th... | def get_SCAT_box(slope, x_mean, y_mean, beta_threshold=0.1):
"""
takes in data and returns information about SCAT box:
the largest possible x_value, the largest possible y_value,
and functions for the two bounding lines of the box
"""
# if beta_threshold is -999, that means null
if beta_thre... |
def urljoin(*fragments):
"""Concatenate multi part strings into urls."""
# Strip possible already existent final slashes of fragments except for the last one
parts = [fragment.rstrip('/') for fragment in fragments[:len(fragments) - 1]]
parts.append(fragments[-1])
return '/'.join(parts) | def function[urljoin, parameter[]]:
constant[Concatenate multi part strings into urls.]
variable[parts] assign[=] <ast.ListComp object at 0x7da1b1218f10>
call[name[parts].append, parameter[call[name[fragments]][<ast.UnaryOp object at 0x7da1b121a140>]]]
return[call[constant[/].join, parameter... | keyword[def] identifier[urljoin] (* identifier[fragments] ):
literal[string]
identifier[parts] =[ identifier[fragment] . identifier[rstrip] ( literal[string] ) keyword[for] identifier[fragment] keyword[in] identifier[fragments] [: identifier[len] ( identifier[fragments] )- literal[int] ]]
iden... | def urljoin(*fragments):
"""Concatenate multi part strings into urls."""
# Strip possible already existent final slashes of fragments except for the last one
parts = [fragment.rstrip('/') for fragment in fragments[:len(fragments) - 1]]
parts.append(fragments[-1])
return '/'.join(parts) |
def gain_to_loss_ratio(self):
"""Gain-to-loss ratio, ratio of positive to negative returns.
Formula:
(n pos. / n neg.) * (avg. up-month return / avg. down-month return)
[Source: CFA Institute]
Returns
-------
float
"""
gt = self > 0
lt =... | def function[gain_to_loss_ratio, parameter[self]]:
constant[Gain-to-loss ratio, ratio of positive to negative returns.
Formula:
(n pos. / n neg.) * (avg. up-month return / avg. down-month return)
[Source: CFA Institute]
Returns
-------
float
]
va... | keyword[def] identifier[gain_to_loss_ratio] ( identifier[self] ):
literal[string]
identifier[gt] = identifier[self] > literal[int]
identifier[lt] = identifier[self] < literal[int]
keyword[return] ( identifier[nansum] ( identifier[gt] )/ identifier[nansum] ( identifier[lt] ))*( ... | def gain_to_loss_ratio(self):
"""Gain-to-loss ratio, ratio of positive to negative returns.
Formula:
(n pos. / n neg.) * (avg. up-month return / avg. down-month return)
[Source: CFA Institute]
Returns
-------
float
"""
gt = self > 0
lt = self < 0
... |
def get_path_attribute(obj, path):
"""Given a path like `related_record.related_record2.id`, this method
will be able to pull the value of ID from that object, returning None
if it doesn't exist.
Args:
obj (fleaker.db.Model):
The object to attempt to pull the... | def function[get_path_attribute, parameter[obj, path]]:
constant[Given a path like `related_record.related_record2.id`, this method
will be able to pull the value of ID from that object, returning None
if it doesn't exist.
Args:
obj (fleaker.db.Model):
The ob... | keyword[def] identifier[get_path_attribute] ( identifier[obj] , identifier[path] ):
literal[string]
identifier[path] = identifier[path] . identifier[replace] ( literal[string] , literal[string] ). identifier[replace] ( literal[string] , literal[string] )
identifier[attr_parts] = ... | def get_path_attribute(obj, path):
"""Given a path like `related_record.related_record2.id`, this method
will be able to pull the value of ID from that object, returning None
if it doesn't exist.
Args:
obj (fleaker.db.Model):
The object to attempt to pull the val... |
def initialize_dag(self,
targets: Optional[List[str]] = [],
nested: bool = False) -> SoS_DAG:
'''Create a DAG by analyzing sections statically.'''
self.reset_dict()
dag = SoS_DAG(name=self.md5)
targets = sos_targets(targets)
self.ad... | def function[initialize_dag, parameter[self, targets, nested]]:
constant[Create a DAG by analyzing sections statically.]
call[name[self].reset_dict, parameter[]]
variable[dag] assign[=] call[name[SoS_DAG], parameter[]]
variable[targets] assign[=] call[name[sos_targets], parameter[name[ta... | keyword[def] identifier[initialize_dag] ( identifier[self] ,
identifier[targets] : identifier[Optional] [ identifier[List] [ identifier[str] ]]=[],
identifier[nested] : identifier[bool] = keyword[False] )-> identifier[SoS_DAG] :
literal[string]
identifier[self] . identifier[reset_dict] ()
... | def initialize_dag(self, targets: Optional[List[str]]=[], nested: bool=False) -> SoS_DAG:
"""Create a DAG by analyzing sections statically."""
self.reset_dict()
dag = SoS_DAG(name=self.md5)
targets = sos_targets(targets)
self.add_forward_workflow(dag, self.workflow.sections)
#
if self.resolv... |
def last(conf):
"""How long you have kept signing in."""
try:
v2ex = V2ex(conf.config)
v2ex.login()
last_date = v2ex.get_last()
click.echo(last_date)
except KeyError:
click.echo('Keyerror, please check your config file.')
except IndexError:
click.echo('Ple... | def function[last, parameter[conf]]:
constant[How long you have kept signing in.]
<ast.Try object at 0x7da1b2662f20> | keyword[def] identifier[last] ( identifier[conf] ):
literal[string]
keyword[try] :
identifier[v2ex] = identifier[V2ex] ( identifier[conf] . identifier[config] )
identifier[v2ex] . identifier[login] ()
identifier[last_date] = identifier[v2ex] . identifier[get_last] ()
ide... | def last(conf):
"""How long you have kept signing in."""
try:
v2ex = V2ex(conf.config)
v2ex.login()
last_date = v2ex.get_last()
click.echo(last_date) # depends on [control=['try'], data=[]]
except KeyError:
click.echo('Keyerror, please check your config file.') # de... |
def _add_cli_param(params, key, value):
'''
Adds key and value as a command line parameter to params.
'''
if value is not None:
params.append('--{0}={1}'.format(key, value)) | def function[_add_cli_param, parameter[params, key, value]]:
constant[
Adds key and value as a command line parameter to params.
]
if compare[name[value] is_not constant[None]] begin[:]
call[name[params].append, parameter[call[constant[--{0}={1}].format, parameter[name[key], name... | keyword[def] identifier[_add_cli_param] ( identifier[params] , identifier[key] , identifier[value] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[not] keyword[None] :
identifier[params] . identifier[append] ( literal[string] . identifier[format] ( identifier[key] , identi... | def _add_cli_param(params, key, value):
"""
Adds key and value as a command line parameter to params.
"""
if value is not None:
params.append('--{0}={1}'.format(key, value)) # depends on [control=['if'], data=['value']] |
def usb(
ctx, enable, disable, list, enable_all, touch_eject, no_touch_eject,
autoeject_timeout, chalresp_timeout, lock_code, force):
"""
Enable or disable applications over USB.
"""
def ensure_not_all_disabled(ctx, usb_enabled):
for app in APPLICATION:
if app & usb_... | def function[usb, parameter[ctx, enable, disable, list, enable_all, touch_eject, no_touch_eject, autoeject_timeout, chalresp_timeout, lock_code, force]]:
constant[
Enable or disable applications over USB.
]
def function[ensure_not_all_disabled, parameter[ctx, usb_enabled]]:
for t... | keyword[def] identifier[usb] (
identifier[ctx] , identifier[enable] , identifier[disable] , identifier[list] , identifier[enable_all] , identifier[touch_eject] , identifier[no_touch_eject] ,
identifier[autoeject_timeout] , identifier[chalresp_timeout] , identifier[lock_code] , identifier[force] ):
literal[stri... | def usb(ctx, enable, disable, list, enable_all, touch_eject, no_touch_eject, autoeject_timeout, chalresp_timeout, lock_code, force):
"""
Enable or disable applications over USB.
"""
def ensure_not_all_disabled(ctx, usb_enabled):
for app in APPLICATION:
if app & usb_enabled:
... |
def post(self, request):
"""
Retrieve video IDs that are missing HLS profiles. This endpoint supports 2 types of input data:
1. If we want a batch of video ids which are missing HLS profile irrespective of their courses, the request
data should be in following format:
... | def function[post, parameter[self, request]]:
constant[
Retrieve video IDs that are missing HLS profiles. This endpoint supports 2 types of input data:
1. If we want a batch of video ids which are missing HLS profile irrespective of their courses, the request
data should be in follow... | keyword[def] identifier[post] ( identifier[self] , identifier[request] ):
literal[string]
identifier[courses] = identifier[request] . identifier[data] . identifier[get] ( literal[string] )
identifier[batch_size] = identifier[request] . identifier[data] . identifier[get] ( literal[string] ,... | def post(self, request):
"""
Retrieve video IDs that are missing HLS profiles. This endpoint supports 2 types of input data:
1. If we want a batch of video ids which are missing HLS profile irrespective of their courses, the request
data should be in following format:
{
... |
def is_visible(self, x, y):
"""
Return whether the specified location is on the visible screen.
:param x: The column (x coord) for the location to check.
:param y: The line (y coord) for the location to check.
"""
return ((x >= 0) and
(x <= self.width) an... | def function[is_visible, parameter[self, x, y]]:
constant[
Return whether the specified location is on the visible screen.
:param x: The column (x coord) for the location to check.
:param y: The line (y coord) for the location to check.
]
return[<ast.BoolOp object at 0x7da1b... | keyword[def] identifier[is_visible] ( identifier[self] , identifier[x] , identifier[y] ):
literal[string]
keyword[return] (( identifier[x] >= literal[int] ) keyword[and]
( identifier[x] <= identifier[self] . identifier[width] ) keyword[and]
( identifier[y] >= identifier[self] . id... | def is_visible(self, x, y):
"""
Return whether the specified location is on the visible screen.
:param x: The column (x coord) for the location to check.
:param y: The line (y coord) for the location to check.
"""
return x >= 0 and x <= self.width and (y >= self._start_line) and... |
def _diff_cache_cluster(current, desired):
'''
If you need to enhance what modify_cache_cluster() considers when deciding what is to be
(or can be) updated, add it to 'modifiable' below. It's a dict mapping the param as used
in modify_cache_cluster() to that in describe_cache_clusters(). Any data fidd... | def function[_diff_cache_cluster, parameter[current, desired]]:
constant[
If you need to enhance what modify_cache_cluster() considers when deciding what is to be
(or can be) updated, add it to 'modifiable' below. It's a dict mapping the param as used
in modify_cache_cluster() to that in describe_c... | keyword[def] identifier[_diff_cache_cluster] ( identifier[current] , identifier[desired] ):
literal[string]
keyword[if] identifier[current] . identifier[get] ( literal[string] ) keyword[is] keyword[not] keyword[None] :
identifier[current] [ literal[string] ]=[ identifier[s] [ literal[... | def _diff_cache_cluster(current, desired):
"""
If you need to enhance what modify_cache_cluster() considers when deciding what is to be
(or can be) updated, add it to 'modifiable' below. It's a dict mapping the param as used
in modify_cache_cluster() to that in describe_cache_clusters(). Any data fidd... |
def batchcancel_openOrders(self, acc_id, symbol=None, side=None, size=None, _async=False):
"""
批量撤销未成交订单
:param acc_id: 帐号ID
:param symbol: 交易对
:param side: 方向
:param size:
:param _async:
:return:
"""
params = {}
path = '/v1/order/... | def function[batchcancel_openOrders, parameter[self, acc_id, symbol, side, size, _async]]:
constant[
批量撤销未成交订单
:param acc_id: 帐号ID
:param symbol: 交易对
:param side: 方向
:param size:
:param _async:
:return:
]
variable[params] assign[=] dictiona... | keyword[def] identifier[batchcancel_openOrders] ( identifier[self] , identifier[acc_id] , identifier[symbol] = keyword[None] , identifier[side] = keyword[None] , identifier[size] = keyword[None] , identifier[_async] = keyword[False] ):
literal[string]
identifier[params] ={}
identifier[pat... | def batchcancel_openOrders(self, acc_id, symbol=None, side=None, size=None, _async=False):
"""
批量撤销未成交订单
:param acc_id: 帐号ID
:param symbol: 交易对
:param side: 方向
:param size:
:param _async:
:return:
"""
params = {}
path = '/v1/order/batchCancelOp... |
def get_identity(user):
"""Create an identity for a given user instance.
Primarily useful for testing.
"""
identity = Identity(user.id)
if hasattr(user, 'id'):
identity.provides.add(UserNeed(user.id))
for role in getattr(user, 'roles', []):
identity.provides.add(RoleNeed(role.... | def function[get_identity, parameter[user]]:
constant[Create an identity for a given user instance.
Primarily useful for testing.
]
variable[identity] assign[=] call[name[Identity], parameter[name[user].id]]
if call[name[hasattr], parameter[name[user], constant[id]]] begin[:]
... | keyword[def] identifier[get_identity] ( identifier[user] ):
literal[string]
identifier[identity] = identifier[Identity] ( identifier[user] . identifier[id] )
keyword[if] identifier[hasattr] ( identifier[user] , literal[string] ):
identifier[identity] . identifier[provides] . identifier[add]... | def get_identity(user):
"""Create an identity for a given user instance.
Primarily useful for testing.
"""
identity = Identity(user.id)
if hasattr(user, 'id'):
identity.provides.add(UserNeed(user.id)) # depends on [control=['if'], data=[]]
for role in getattr(user, 'roles', []):
... |
def samblaster_dedup_sort(data, tx_out_file, tx_sr_file, tx_disc_file):
"""Deduplicate and sort with samblaster, produces split read and discordant pair files.
"""
samblaster = config_utils.get_program("samblaster", data["config"])
samtools = config_utils.get_program("samtools", data["config"])
tmp_... | def function[samblaster_dedup_sort, parameter[data, tx_out_file, tx_sr_file, tx_disc_file]]:
constant[Deduplicate and sort with samblaster, produces split read and discordant pair files.
]
variable[samblaster] assign[=] call[name[config_utils].get_program, parameter[constant[samblaster], call[name[d... | keyword[def] identifier[samblaster_dedup_sort] ( identifier[data] , identifier[tx_out_file] , identifier[tx_sr_file] , identifier[tx_disc_file] ):
literal[string]
identifier[samblaster] = identifier[config_utils] . identifier[get_program] ( literal[string] , identifier[data] [ literal[string] ])
ident... | def samblaster_dedup_sort(data, tx_out_file, tx_sr_file, tx_disc_file):
"""Deduplicate and sort with samblaster, produces split read and discordant pair files.
"""
samblaster = config_utils.get_program('samblaster', data['config'])
samtools = config_utils.get_program('samtools', data['config'])
tmp_... |
def with_setup(setup=None, teardown=None):
"""Decorator to add setup and/or teardown methods to a test function::
@with_setup(setup, teardown)
def test_something():
" ... "
Note that `with_setup` is useful *only* for test functions, not for test
methods or inside of TestCase subclass... | def function[with_setup, parameter[setup, teardown]]:
constant[Decorator to add setup and/or teardown methods to a test function::
@with_setup(setup, teardown)
def test_something():
" ... "
Note that `with_setup` is useful *only* for test functions, not for test
methods or inside... | keyword[def] identifier[with_setup] ( identifier[setup] = keyword[None] , identifier[teardown] = keyword[None] ):
literal[string]
keyword[def] identifier[decorate] ( identifier[func] , identifier[setup] = identifier[setup] , identifier[teardown] = identifier[teardown] ):
keyword[if] identifier[s... | def with_setup(setup=None, teardown=None):
"""Decorator to add setup and/or teardown methods to a test function::
@with_setup(setup, teardown)
def test_something():
" ... "
Note that `with_setup` is useful *only* for test functions, not for test
methods or inside of TestCase subclass... |
def clear_threads(self):
"""
Clears the threads snapshot.
"""
for aThread in compat.itervalues(self.__threadDict):
aThread.clear()
self.__threadDict = dict() | def function[clear_threads, parameter[self]]:
constant[
Clears the threads snapshot.
]
for taget[name[aThread]] in starred[call[name[compat].itervalues, parameter[name[self].__threadDict]]] begin[:]
call[name[aThread].clear, parameter[]]
name[self].__threadDict as... | keyword[def] identifier[clear_threads] ( identifier[self] ):
literal[string]
keyword[for] identifier[aThread] keyword[in] identifier[compat] . identifier[itervalues] ( identifier[self] . identifier[__threadDict] ):
identifier[aThread] . identifier[clear] ()
identifier[self]... | def clear_threads(self):
"""
Clears the threads snapshot.
"""
for aThread in compat.itervalues(self.__threadDict):
aThread.clear() # depends on [control=['for'], data=['aThread']]
self.__threadDict = dict() |
def create_or_update_detail(self, request):
"""
Implements Create/Update an object completely given an id
maps to PUT /api/object/:id in rest semantics
:param request: rip.Request
:return: rip.Response
"""
pipeline = crud_pipeline_factory.create_or_update_detail_pipe... | def function[create_or_update_detail, parameter[self, request]]:
constant[
Implements Create/Update an object completely given an id
maps to PUT /api/object/:id in rest semantics
:param request: rip.Request
:return: rip.Response
]
variable[pipeline] assign[=] call[nam... | keyword[def] identifier[create_or_update_detail] ( identifier[self] , identifier[request] ):
literal[string]
identifier[pipeline] = identifier[crud_pipeline_factory] . identifier[create_or_update_detail_pipeline] (
identifier[configuration] = identifier[self] . identifier[configuration] )... | def create_or_update_detail(self, request):
"""
Implements Create/Update an object completely given an id
maps to PUT /api/object/:id in rest semantics
:param request: rip.Request
:return: rip.Response
"""
pipeline = crud_pipeline_factory.create_or_update_detail_pipeline(conf... |
def render(self, size, frame, drawqueue):
'''
Calls implmentation to get a render context,
passes it to the drawqueues render function
then calls self.rendering_finished
'''
r_context = self.create_rcontext(size, frame)
drawqueue.render(r_context)
self.ren... | def function[render, parameter[self, size, frame, drawqueue]]:
constant[
Calls implmentation to get a render context,
passes it to the drawqueues render function
then calls self.rendering_finished
]
variable[r_context] assign[=] call[name[self].create_rcontext, parameter[... | keyword[def] identifier[render] ( identifier[self] , identifier[size] , identifier[frame] , identifier[drawqueue] ):
literal[string]
identifier[r_context] = identifier[self] . identifier[create_rcontext] ( identifier[size] , identifier[frame] )
identifier[drawqueue] . identifier[render] ( ... | def render(self, size, frame, drawqueue):
"""
Calls implmentation to get a render context,
passes it to the drawqueues render function
then calls self.rendering_finished
"""
r_context = self.create_rcontext(size, frame)
drawqueue.render(r_context)
self.rendering_finished(... |
def degree(self, kind='out', weighted=True):
'''Returns an array of vertex degrees.
kind : either 'in' or 'out', useful for directed graphs
weighted : controls whether to count edges or sum their weights
'''
if kind == 'out':
axis = 1
adj = self.matrix('dense', 'csc')
else:
axi... | def function[degree, parameter[self, kind, weighted]]:
constant[Returns an array of vertex degrees.
kind : either 'in' or 'out', useful for directed graphs
weighted : controls whether to count edges or sum their weights
]
if compare[name[kind] equal[==] constant[out]] begin[:]
... | keyword[def] identifier[degree] ( identifier[self] , identifier[kind] = literal[string] , identifier[weighted] = keyword[True] ):
literal[string]
keyword[if] identifier[kind] == literal[string] :
identifier[axis] = literal[int]
identifier[adj] = identifier[self] . identifier[matrix] ( liter... | def degree(self, kind='out', weighted=True):
"""Returns an array of vertex degrees.
kind : either 'in' or 'out', useful for directed graphs
weighted : controls whether to count edges or sum their weights
"""
if kind == 'out':
axis = 1
adj = self.matrix('dense', 'csc') # depends on [... |
def check_sparsity(x, fraction=0.6):
'''
check_sparsity(x) yields either x or an array equivalent to x with a different sparsity based on
a heuristic: if x is a sparse array with more than 60% of its elements specified, it is made
dense; otherwise, it is left alone.
The optional argument fracti... | def function[check_sparsity, parameter[x, fraction]]:
constant[
check_sparsity(x) yields either x or an array equivalent to x with a different sparsity based on
a heuristic: if x is a sparse array with more than 60% of its elements specified, it is made
dense; otherwise, it is left alone.
T... | keyword[def] identifier[check_sparsity] ( identifier[x] , identifier[fraction] = literal[int] ):
literal[string]
keyword[if] keyword[not] identifier[sps] . identifier[issparse] ( identifier[x] ): keyword[return] identifier[x]
identifier[n] = identifier[numel] ( identifier[x] )
keyword[if] id... | def check_sparsity(x, fraction=0.6):
"""
check_sparsity(x) yields either x or an array equivalent to x with a different sparsity based on
a heuristic: if x is a sparse array with more than 60% of its elements specified, it is made
dense; otherwise, it is left alone.
The optional argument fracti... |
def get_members_of_group(self, gname):
"""Get all members of a group which name is given in parameter
:param gname: name of the group
:type gname: str
:return: list of contacts in the group
:rtype: list[alignak.objects.contact.Contact]
"""
contactgroup = self.fin... | def function[get_members_of_group, parameter[self, gname]]:
constant[Get all members of a group which name is given in parameter
:param gname: name of the group
:type gname: str
:return: list of contacts in the group
:rtype: list[alignak.objects.contact.Contact]
]
... | keyword[def] identifier[get_members_of_group] ( identifier[self] , identifier[gname] ):
literal[string]
identifier[contactgroup] = identifier[self] . identifier[find_by_name] ( identifier[gname] )
keyword[if] identifier[contactgroup] :
keyword[return] identifier[contactgroup... | def get_members_of_group(self, gname):
"""Get all members of a group which name is given in parameter
:param gname: name of the group
:type gname: str
:return: list of contacts in the group
:rtype: list[alignak.objects.contact.Contact]
"""
contactgroup = self.find_by_nam... |
def launch_modules_with_names(modules_with_names, module_args={}, kill_before_launch=True):
'''launch module.main functions in another process'''
processes = []
if kill_before_launch:
for module_name, name in modules_with_names:
kill_module(name)
for module_name, name in modules_with... | def function[launch_modules_with_names, parameter[modules_with_names, module_args, kill_before_launch]]:
constant[launch module.main functions in another process]
variable[processes] assign[=] list[[]]
if name[kill_before_launch] begin[:]
for taget[tuple[[<ast.Name object at 0x7d... | keyword[def] identifier[launch_modules_with_names] ( identifier[modules_with_names] , identifier[module_args] ={}, identifier[kill_before_launch] = keyword[True] ):
literal[string]
identifier[processes] =[]
keyword[if] identifier[kill_before_launch] :
keyword[for] identifier[module_name] , ... | def launch_modules_with_names(modules_with_names, module_args={}, kill_before_launch=True):
"""launch module.main functions in another process"""
processes = []
if kill_before_launch:
for (module_name, name) in modules_with_names:
kill_module(name) # depends on [control=['for'], data=[]... |
def reference_creator_surnames(self, index):
"""Return as a list the surnames of the reference creators (locally defined)."""
# TODO Not true, ex: ISBN 978-1-4398-3778-8. Return all creator types?
# Academic books published as a collection of chapters contributed by
# different authors h... | def function[reference_creator_surnames, parameter[self, index]]:
constant[Return as a list the surnames of the reference creators (locally defined).]
variable[creators] assign[=] call[call[name[self].reference_data, parameter[name[index]]]][constant[creators]]
variable[creator_types] assign[=] ... | keyword[def] identifier[reference_creator_surnames] ( identifier[self] , identifier[index] ):
literal[string]
identifier[creators] = identifier[self] . identifier[reference_data] ( identifier[index] )[ literal[string] ]
identifier[creator_types] =[ ident... | def reference_creator_surnames(self, index):
"""Return as a list the surnames of the reference creators (locally defined)."""
# TODO Not true, ex: ISBN 978-1-4398-3778-8. Return all creator types?
# Academic books published as a collection of chapters contributed by
# different authors have editors but ... |
def polygon(self, done=None):
'''return a polygon for the waypoints'''
indexes = self.view_indexes(done)
points = []
for idx in indexes:
w = self.wp(idx)
points.append((w.x, w.y))
return points | def function[polygon, parameter[self, done]]:
constant[return a polygon for the waypoints]
variable[indexes] assign[=] call[name[self].view_indexes, parameter[name[done]]]
variable[points] assign[=] list[[]]
for taget[name[idx]] in starred[name[indexes]] begin[:]
variable... | keyword[def] identifier[polygon] ( identifier[self] , identifier[done] = keyword[None] ):
literal[string]
identifier[indexes] = identifier[self] . identifier[view_indexes] ( identifier[done] )
identifier[points] =[]
keyword[for] identifier[idx] keyword[in] identifier[indexes] :... | def polygon(self, done=None):
"""return a polygon for the waypoints"""
indexes = self.view_indexes(done)
points = []
for idx in indexes:
w = self.wp(idx)
points.append((w.x, w.y)) # depends on [control=['for'], data=['idx']]
return points |
def _collect_tfa_stats(task):
'''
This is a parallel worker to gather LC stats.
task[0] = lcfile
task[1] = lcformat
task[2] = lcformatdir
task[3] = timecols
task[4] = magcols
task[5] = errcols
task[6] = custom_bandpasses
'''
try:
(lcfile, lcformat, lcformatdir,
... | def function[_collect_tfa_stats, parameter[task]]:
constant[
This is a parallel worker to gather LC stats.
task[0] = lcfile
task[1] = lcformat
task[2] = lcformatdir
task[3] = timecols
task[4] = magcols
task[5] = errcols
task[6] = custom_bandpasses
]
<ast.Try object at 0... | keyword[def] identifier[_collect_tfa_stats] ( identifier[task] ):
literal[string]
keyword[try] :
( identifier[lcfile] , identifier[lcformat] , identifier[lcformatdir] ,
identifier[timecols] , identifier[magcols] , identifier[errcols] ,
identifier[custom_bandpasses] )= identifier... | def _collect_tfa_stats(task):
"""
This is a parallel worker to gather LC stats.
task[0] = lcfile
task[1] = lcformat
task[2] = lcformatdir
task[3] = timecols
task[4] = magcols
task[5] = errcols
task[6] = custom_bandpasses
"""
try:
(lcfile, lcformat, lcformatdir, time... |
def ppj(json_data):
"""ppj
:param json_data: dictionary to print
"""
return str(json.dumps(
json_data,
sort_keys=True,
indent=4,
separators=(',', ': '))) | def function[ppj, parameter[json_data]]:
constant[ppj
:param json_data: dictionary to print
]
return[call[name[str], parameter[call[name[json].dumps, parameter[name[json_data]]]]]] | keyword[def] identifier[ppj] ( identifier[json_data] ):
literal[string]
keyword[return] identifier[str] ( identifier[json] . identifier[dumps] (
identifier[json_data] ,
identifier[sort_keys] = keyword[True] ,
identifier[indent] = literal[int] ,
identifier[separators] =( literal[string]... | def ppj(json_data):
"""ppj
:param json_data: dictionary to print
"""
return str(json.dumps(json_data, sort_keys=True, indent=4, separators=(',', ': '))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.