code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def delete_map(self, url, map=None, auth_map=None):
"""Gera um XML a partir dos dados do dicionário e o envia através de uma requisição DELETE.
:param url: URL para enviar a requisição HTTP.
:param map: Dicionário com os dados do corpo da requisição HTTP.
:param auth_map: Dicionário com... | def function[delete_map, parameter[self, url, map, auth_map]]:
constant[Gera um XML a partir dos dados do dicionário e o envia através de uma requisição DELETE.
:param url: URL para enviar a requisição HTTP.
:param map: Dicionário com os dados do corpo da requisição HTTP.
:param auth_ma... | keyword[def] identifier[delete_map] ( identifier[self] , identifier[url] , identifier[map] = keyword[None] , identifier[auth_map] = keyword[None] ):
literal[string]
identifier[xml] = keyword[None]
keyword[if] identifier[map] keyword[is] keyword[not] keyword[None] :
identi... | def delete_map(self, url, map=None, auth_map=None):
"""Gera um XML a partir dos dados do dicionário e o envia através de uma requisição DELETE.
:param url: URL para enviar a requisição HTTP.
:param map: Dicionário com os dados do corpo da requisição HTTP.
:param auth_map: Dicionário com as ... |
def inverse(self):
"""
Retrieves the inverse of a G1 element.
"""
result = G2Element()
librelic.g2_neg_abi(byref(result), byref(self))
return result | def function[inverse, parameter[self]]:
constant[
Retrieves the inverse of a G1 element.
]
variable[result] assign[=] call[name[G2Element], parameter[]]
call[name[librelic].g2_neg_abi, parameter[call[name[byref], parameter[name[result]]], call[name[byref], parameter[name[self]]]]... | keyword[def] identifier[inverse] ( identifier[self] ):
literal[string]
identifier[result] = identifier[G2Element] ()
identifier[librelic] . identifier[g2_neg_abi] ( identifier[byref] ( identifier[result] ), identifier[byref] ( identifier[self] ))
keyword[return] identifier[result... | def inverse(self):
"""
Retrieves the inverse of a G1 element.
"""
result = G2Element()
librelic.g2_neg_abi(byref(result), byref(self))
return result |
def tsv_escape(x: Any) -> str:
"""
Escape data for tab-separated value (TSV) format.
"""
if x is None:
return ""
x = str(x)
return x.replace("\t", "\\t").replace("\n", "\\n") | def function[tsv_escape, parameter[x]]:
constant[
Escape data for tab-separated value (TSV) format.
]
if compare[name[x] is constant[None]] begin[:]
return[constant[]]
variable[x] assign[=] call[name[str], parameter[name[x]]]
return[call[call[name[x].replace, parameter[consta... | keyword[def] identifier[tsv_escape] ( identifier[x] : identifier[Any] )-> identifier[str] :
literal[string]
keyword[if] identifier[x] keyword[is] keyword[None] :
keyword[return] literal[string]
identifier[x] = identifier[str] ( identifier[x] )
keyword[return] identifier[x] . identi... | def tsv_escape(x: Any) -> str:
"""
Escape data for tab-separated value (TSV) format.
"""
if x is None:
return '' # depends on [control=['if'], data=[]]
x = str(x)
return x.replace('\t', '\\t').replace('\n', '\\n') |
async def initialize_stores_async(self):
"""
Intializes the partition checkpoint and lease store ensures that a checkpoint
exists for all partitions. Note in this case checkpoint and lease stores are
the same storage manager construct.
:return: Returns the number of partitions.
... | <ast.AsyncFunctionDef object at 0x7da2046215d0> | keyword[async] keyword[def] identifier[initialize_stores_async] ( identifier[self] ):
literal[string]
keyword[await] identifier[self] . identifier[host] . identifier[storage_manager] . identifier[create_checkpoint_store_if_not_exists_async] ()
identifier[partition_ids] = keyword[await] ... | async def initialize_stores_async(self):
"""
Intializes the partition checkpoint and lease store ensures that a checkpoint
exists for all partitions. Note in this case checkpoint and lease stores are
the same storage manager construct.
:return: Returns the number of partitions.
... |
def _get_items(self):
"""Get multiple items from a Queue.
Gets at least one (blocking) and at most ``max_batch_size`` items
(non-blocking) from a given Queue. Does not mark the items as done.
:rtype: Sequence
:returns: A sequence of items retrieved from the queue.
"""
... | def function[_get_items, parameter[self]]:
constant[Get multiple items from a Queue.
Gets at least one (blocking) and at most ``max_batch_size`` items
(non-blocking) from a given Queue. Does not mark the items as done.
:rtype: Sequence
:returns: A sequence of items retrieved fr... | keyword[def] identifier[_get_items] ( identifier[self] ):
literal[string]
identifier[items] =[ identifier[self] . identifier[_queue] . identifier[get] ()]
keyword[while] identifier[len] ( identifier[items] )< identifier[self] . identifier[_max_batch_size] :
keyword[try] :
... | def _get_items(self):
"""Get multiple items from a Queue.
Gets at least one (blocking) and at most ``max_batch_size`` items
(non-blocking) from a given Queue. Does not mark the items as done.
:rtype: Sequence
:returns: A sequence of items retrieved from the queue.
"""
i... |
def drawGrid(self, painter, rect, showGrid, showColumns, showRows):
"""
Draws the grid on the inputed painter
:param painter | <QPainter>
rect | <QRect>
showGrid | <bool>
showColumns | <bool>
... | def function[drawGrid, parameter[self, painter, rect, showGrid, showColumns, showRows]]:
constant[
Draws the grid on the inputed painter
:param painter | <QPainter>
rect | <QRect>
showGrid | <bool>
showColumn... | keyword[def] identifier[drawGrid] ( identifier[self] , identifier[painter] , identifier[rect] , identifier[showGrid] , identifier[showColumns] , identifier[showRows] ):
literal[string]
keyword[if] keyword[not] ( identifier[self] . identifier[showGrid] () keyword[and] identifier[showGrid] ):
... | def drawGrid(self, painter, rect, showGrid, showColumns, showRows):
"""
Draws the grid on the inputed painter
:param painter | <QPainter>
rect | <QRect>
showGrid | <bool>
showColumns | <bool>
... |
def loop(self, value):
""" Indicates whether the playback should loop.
Parameters
----------
value : bool
True if playback should loop, False if not.
"""
if not type(value) == bool:
raise TypeError("can only be True or False")
self._loop = value | def function[loop, parameter[self, value]]:
constant[ Indicates whether the playback should loop.
Parameters
----------
value : bool
True if playback should loop, False if not.
]
if <ast.UnaryOp object at 0x7da1b253d210> begin[:]
<ast.Raise object at 0x7da1b253ec80>
name[se... | keyword[def] identifier[loop] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] keyword[not] identifier[type] ( identifier[value] )== identifier[bool] :
keyword[raise] identifier[TypeError] ( literal[string] )
identifier[self] . identifier[_loop] = identifier[value] | def loop(self, value):
""" Indicates whether the playback should loop.
Parameters
----------
value : bool
True if playback should loop, False if not.
"""
if not type(value) == bool:
raise TypeError('can only be True or False') # depends on [control=['if'], data=[]]
self._loop = value |
def to_distance_maps(self, inverted=False):
"""
Generates a ``(H,W,K)`` output containing ``K`` distance maps for ``K`` keypoints.
The k-th distance map contains at every location ``(y, x)`` the euclidean distance to the k-th keypoint.
This function can be used as a helper when augment... | def function[to_distance_maps, parameter[self, inverted]]:
constant[
Generates a ``(H,W,K)`` output containing ``K`` distance maps for ``K`` keypoints.
The k-th distance map contains at every location ``(y, x)`` the euclidean distance to the k-th keypoint.
This function can be used as ... | keyword[def] identifier[to_distance_maps] ( identifier[self] , identifier[inverted] = keyword[False] ):
literal[string]
identifier[ia] . identifier[do_assert] ( identifier[len] ( identifier[self] . identifier[keypoints] )> literal[int] )
identifier[height] , identifier[width] = identifier[... | def to_distance_maps(self, inverted=False):
"""
Generates a ``(H,W,K)`` output containing ``K`` distance maps for ``K`` keypoints.
The k-th distance map contains at every location ``(y, x)`` the euclidean distance to the k-th keypoint.
This function can be used as a helper when augmenting ... |
def load_from_file(module_path):
"""
Load a python module from its absolute filesystem path
Borrowed from django-cms
"""
from imp import load_module, PY_SOURCE
imported = None
if module_path:
with open(module_path, 'r') as openfile:
imported = load_module('mod', openfil... | def function[load_from_file, parameter[module_path]]:
constant[
Load a python module from its absolute filesystem path
Borrowed from django-cms
]
from relative_module[imp] import module[load_module], module[PY_SOURCE]
variable[imported] assign[=] constant[None]
if name[module_pa... | keyword[def] identifier[load_from_file] ( identifier[module_path] ):
literal[string]
keyword[from] identifier[imp] keyword[import] identifier[load_module] , identifier[PY_SOURCE]
identifier[imported] = keyword[None]
keyword[if] identifier[module_path] :
keyword[with] identifier[o... | def load_from_file(module_path):
"""
Load a python module from its absolute filesystem path
Borrowed from django-cms
"""
from imp import load_module, PY_SOURCE
imported = None
if module_path:
with open(module_path, 'r') as openfile:
imported = load_module('mod', openfile... |
def render(self, name=None, value=None, attrs=None):
"""Outputs a <ul> for this set of choice fields.
If an id was given to the field, it is applied to the <ul> (each
item in the list will get an id of `$id_$i`).
"""
attrs = {} or attrs
self.attrs = attrs
self.na... | def function[render, parameter[self, name, value, attrs]]:
constant[Outputs a <ul> for this set of choice fields.
If an id was given to the field, it is applied to the <ul> (each
item in the list will get an id of `$id_$i`).
]
variable[attrs] assign[=] <ast.BoolOp object at 0x7d... | keyword[def] identifier[render] ( identifier[self] , identifier[name] = keyword[None] , identifier[value] = keyword[None] , identifier[attrs] = keyword[None] ):
literal[string]
identifier[attrs] ={} keyword[or] identifier[attrs]
identifier[self] . identifier[attrs] = identifier[attrs]
... | def render(self, name=None, value=None, attrs=None):
"""Outputs a <ul> for this set of choice fields.
If an id was given to the field, it is applied to the <ul> (each
item in the list will get an id of `$id_$i`).
"""
attrs = {} or attrs
self.attrs = attrs
self.name = name
se... |
def get_subtree(self, name): # noqa: D302
r"""
Get all node names in a sub-tree.
:param name: Sub-tree root node name
:type name: :ref:`NodeName`
:rtype: list of :ref:`NodeName`
:raises:
* RuntimeError (Argument \`name\` is not valid)
* RuntimeErro... | def function[get_subtree, parameter[self, name]]:
constant[
Get all node names in a sub-tree.
:param name: Sub-tree root node name
:type name: :ref:`NodeName`
:rtype: list of :ref:`NodeName`
:raises:
* RuntimeError (Argument \`name\` is not valid)
*... | keyword[def] identifier[get_subtree] ( identifier[self] , identifier[name] ):
literal[string]
keyword[if] identifier[self] . identifier[_validate_node_name] ( identifier[name] ):
keyword[raise] identifier[RuntimeError] ( literal[string] )
identifier[self] . identifier[_node_... | def get_subtree(self, name): # noqa: D302
"\n Get all node names in a sub-tree.\n\n :param name: Sub-tree root node name\n :type name: :ref:`NodeName`\n\n :rtype: list of :ref:`NodeName`\n\n :raises:\n * RuntimeError (Argument \\`name\\` is not valid)\n\n * Runti... |
def close(self):
"""Close the stream."""
self.current = Token(self.current.lineno, TOKEN_EOF, '')
self._next = None
self.closed = True | def function[close, parameter[self]]:
constant[Close the stream.]
name[self].current assign[=] call[name[Token], parameter[name[self].current.lineno, name[TOKEN_EOF], constant[]]]
name[self]._next assign[=] constant[None]
name[self].closed assign[=] constant[True] | keyword[def] identifier[close] ( identifier[self] ):
literal[string]
identifier[self] . identifier[current] = identifier[Token] ( identifier[self] . identifier[current] . identifier[lineno] , identifier[TOKEN_EOF] , literal[string] )
identifier[self] . identifier[_next] = keyword[None]
... | def close(self):
"""Close the stream."""
self.current = Token(self.current.lineno, TOKEN_EOF, '')
self._next = None
self.closed = True |
def readObject(self):
"""read object"""
try:
_, res = self._read_and_exec_opcode(ident=0)
position_bak = self.object_stream.tell()
the_rest = self.object_stream.read()
if len(the_rest):
log_error("Warning!!!!: Stream still has %s bytes left.\
Enable debug mode of logging to see ... | def function[readObject, parameter[self]]:
constant[read object]
<ast.Try object at 0x7da2054a69b0> | keyword[def] identifier[readObject] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[_] , identifier[res] = identifier[self] . identifier[_read_and_exec_opcode] ( identifier[ident] = literal[int] )
identifier[position_bak] = identifier[self] . identifier[object_stream] . ident... | def readObject(self):
"""read object"""
try:
(_, res) = self._read_and_exec_opcode(ident=0)
position_bak = self.object_stream.tell()
the_rest = self.object_stream.read()
if len(the_rest):
log_error('Warning!!!!: Stream still has %s bytes left.Enable debug mode of logg... |
def stream(queryset_or_adapter, basename=None):
"""Stream a csv file from an object list,
a queryset or an instanciated adapter.
"""
if isinstance(queryset_or_adapter, Adapter):
adapter = queryset_or_adapter
elif isinstance(queryset_or_adapter, (list, tuple)):
if not queryset_or_ada... | def function[stream, parameter[queryset_or_adapter, basename]]:
constant[Stream a csv file from an object list,
a queryset or an instanciated adapter.
]
if call[name[isinstance], parameter[name[queryset_or_adapter], name[Adapter]]] begin[:]
variable[adapter] assign[=] name[query... | keyword[def] identifier[stream] ( identifier[queryset_or_adapter] , identifier[basename] = keyword[None] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[queryset_or_adapter] , identifier[Adapter] ):
identifier[adapter] = identifier[queryset_or_adapter]
keyword[elif] iden... | def stream(queryset_or_adapter, basename=None):
"""Stream a csv file from an object list,
a queryset or an instanciated adapter.
"""
if isinstance(queryset_or_adapter, Adapter):
adapter = queryset_or_adapter # depends on [control=['if'], data=[]]
elif isinstance(queryset_or_adapter, (list,... |
def get_rows(self, startrow=3, worksheet=None):
"""Returns a generator for all rows in a sheet.
Each row contains a dictionary where the key is the value of the
first row of the sheet for each column.
The data values are returned in utf-8 format.
Starts to consume dat... | def function[get_rows, parameter[self, startrow, worksheet]]:
constant[Returns a generator for all rows in a sheet.
Each row contains a dictionary where the key is the value of the
first row of the sheet for each column.
The data values are returned in utf-8 format.
S... | keyword[def] identifier[get_rows] ( identifier[self] , identifier[startrow] = literal[int] , identifier[worksheet] = keyword[None] ):
literal[string]
identifier[headers] =[]
identifier[row_nr] = literal[int]
identifier[worksheet] = identifier[worksheet] keyword[if] identifier[... | def get_rows(self, startrow=3, worksheet=None):
"""Returns a generator for all rows in a sheet.
Each row contains a dictionary where the key is the value of the
first row of the sheet for each column.
The data values are returned in utf-8 format.
Starts to consume data fr... |
def sixteensreporter(self, analysistype='sixteens_full'):
"""
Creates a report of the results
:param analysistype: The variable to use when accessing attributes in the metadata object
"""
# Create the path in which the reports are stored
make_path(self.reportpath)
... | def function[sixteensreporter, parameter[self, analysistype]]:
constant[
Creates a report of the results
:param analysistype: The variable to use when accessing attributes in the metadata object
]
call[name[make_path], parameter[name[self].reportpath]]
variable[header] as... | keyword[def] identifier[sixteensreporter] ( identifier[self] , identifier[analysistype] = literal[string] ):
literal[string]
identifier[make_path] ( identifier[self] . identifier[reportpath] )
identifier[header] = literal[string]
identifier[data] = literal[strin... | def sixteensreporter(self, analysistype='sixteens_full'):
"""
Creates a report of the results
:param analysistype: The variable to use when accessing attributes in the metadata object
"""
# Create the path in which the reports are stored
make_path(self.reportpath)
# Initialise th... |
def create_proteinquant_lookup(fns, pqdb, poolnames, protacc_colnr,
ms1_qcolpattern=None, isobqcolpattern=None,
psmnrpattern=None, probcolpattern=None,
fdrcolpattern=None, pepcolpattern=None):
"""Calls lower level function ... | def function[create_proteinquant_lookup, parameter[fns, pqdb, poolnames, protacc_colnr, ms1_qcolpattern, isobqcolpattern, psmnrpattern, probcolpattern, fdrcolpattern, pepcolpattern]]:
constant[Calls lower level function to create a protein quant lookup]
variable[patterns] assign[=] list[[<ast.Name objec... | keyword[def] identifier[create_proteinquant_lookup] ( identifier[fns] , identifier[pqdb] , identifier[poolnames] , identifier[protacc_colnr] ,
identifier[ms1_qcolpattern] = keyword[None] , identifier[isobqcolpattern] = keyword[None] ,
identifier[psmnrpattern] = keyword[None] , identifier[probcolpattern] = keyword[N... | def create_proteinquant_lookup(fns, pqdb, poolnames, protacc_colnr, ms1_qcolpattern=None, isobqcolpattern=None, psmnrpattern=None, probcolpattern=None, fdrcolpattern=None, pepcolpattern=None):
"""Calls lower level function to create a protein quant lookup"""
patterns = [ms1_qcolpattern, probcolpattern, fdrcolpa... |
def _update(self):
"""Update status text."""
typing_users = [self._conversation.get_user(user_id)
for user_id, status in self._typing_statuses.items()
if status == hangups.TYPING_TYPE_STARTED]
displayed_names = [user.first_name for user in typing_u... | def function[_update, parameter[self]]:
constant[Update status text.]
variable[typing_users] assign[=] <ast.ListComp object at 0x7da2047e8400>
variable[displayed_names] assign[=] <ast.ListComp object at 0x7da2047eb7f0>
if name[displayed_names] begin[:]
variable[typing_mes... | keyword[def] identifier[_update] ( identifier[self] ):
literal[string]
identifier[typing_users] =[ identifier[self] . identifier[_conversation] . identifier[get_user] ( identifier[user_id] )
keyword[for] identifier[user_id] , identifier[status] keyword[in] identifier[self] . identifier[... | def _update(self):
"""Update status text."""
typing_users = [self._conversation.get_user(user_id) for (user_id, status) in self._typing_statuses.items() if status == hangups.TYPING_TYPE_STARTED]
displayed_names = [user.first_name for user in typing_users if not user.is_self]
if displayed_names:
... |
def perform_permissions_check(self, user, obj, perms):
""" Performs the permissions check. """
return self.request.forum_permission_handler.can_update_topics_to_sticky_topics(obj, user) | def function[perform_permissions_check, parameter[self, user, obj, perms]]:
constant[ Performs the permissions check. ]
return[call[name[self].request.forum_permission_handler.can_update_topics_to_sticky_topics, parameter[name[obj], name[user]]]] | keyword[def] identifier[perform_permissions_check] ( identifier[self] , identifier[user] , identifier[obj] , identifier[perms] ):
literal[string]
keyword[return] identifier[self] . identifier[request] . identifier[forum_permission_handler] . identifier[can_update_topics_to_sticky_topics] ( identif... | def perform_permissions_check(self, user, obj, perms):
""" Performs the permissions check. """
return self.request.forum_permission_handler.can_update_topics_to_sticky_topics(obj, user) |
def get_typename(x):
'''Returns the name of the type of x, if x is an object. Otherwise, returns the name of x.
'''
if isinstance(x, type):
ret = x.__name__
else:
ret = x.__class__.__name__
return ret | def function[get_typename, parameter[x]]:
constant[Returns the name of the type of x, if x is an object. Otherwise, returns the name of x.
]
if call[name[isinstance], parameter[name[x], name[type]]] begin[:]
variable[ret] assign[=] name[x].__name__
return[name[ret]] | keyword[def] identifier[get_typename] ( identifier[x] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[x] , identifier[type] ):
identifier[ret] = identifier[x] . identifier[__name__]
keyword[else] :
identifier[ret] = identifier[x] . identifier[__class__] . identif... | def get_typename(x):
"""Returns the name of the type of x, if x is an object. Otherwise, returns the name of x.
"""
if isinstance(x, type):
ret = x.__name__ # depends on [control=['if'], data=[]]
else:
ret = x.__class__.__name__
return ret |
def read_value(self):
"""Read the value of this descriptor."""
pass
# Kick off a query to read the value of the descriptor, then wait
# for the result to return asyncronously.
self._value_read.clear()
self._device._peripheral.readValueForDescriptor(self._descriptor)
... | def function[read_value, parameter[self]]:
constant[Read the value of this descriptor.]
pass
call[name[self]._value_read.clear, parameter[]]
call[name[self]._device._peripheral.readValueForDescriptor, parameter[name[self]._descriptor]]
if <ast.UnaryOp object at 0x7da204962bc0> begin[... | keyword[def] identifier[read_value] ( identifier[self] ):
literal[string]
keyword[pass]
identifier[self] . identifier[_value_read] . identifier[clear] ()
identifier[self] . identifier[_device] . identifier[_peripheral] . identifier[readValueForDescriptor] ( iden... | def read_value(self):
"""Read the value of this descriptor."""
pass
# Kick off a query to read the value of the descriptor, then wait
# for the result to return asyncronously.
self._value_read.clear()
self._device._peripheral.readValueForDescriptor(self._descriptor)
if not self._value_read.w... |
def refresh_styles(self):
"""Load all available styles"""
import matplotlib.pyplot as plt
self.colours = {}
for style in plt.style.available:
try:
style_colours = plt.style.library[style]['axes.prop_cycle']
self.colours[style] = [c['color'] fo... | def function[refresh_styles, parameter[self]]:
constant[Load all available styles]
import module[matplotlib.pyplot] as alias[plt]
name[self].colours assign[=] dictionary[[], []]
for taget[name[style]] in starred[name[plt].style.available] begin[:]
<ast.Try object at 0x7da1b26ad570>
... | keyword[def] identifier[refresh_styles] ( identifier[self] ):
literal[string]
keyword[import] identifier[matplotlib] . identifier[pyplot] keyword[as] identifier[plt]
identifier[self] . identifier[colours] ={}
keyword[for] identifier[style] keyword[in] identifier[plt] . ide... | def refresh_styles(self):
"""Load all available styles"""
import matplotlib.pyplot as plt
self.colours = {}
for style in plt.style.available:
try:
style_colours = plt.style.library[style]['axes.prop_cycle']
self.colours[style] = [c['color'] for c in list(style_colours)] ... |
def findvalue(array, value, compare = lambda x, y: x == y):
"A function that uses the compare function to return a value from the list."
try:
return next(x for x in array if compare(x, value))
except StopIteration:
raise ValueError('%r not in array'%value) | def function[findvalue, parameter[array, value, compare]]:
constant[A function that uses the compare function to return a value from the list.]
<ast.Try object at 0x7da20c7c9300> | keyword[def] identifier[findvalue] ( identifier[array] , identifier[value] , identifier[compare] = keyword[lambda] identifier[x] , identifier[y] : identifier[x] == identifier[y] ):
literal[string]
keyword[try] :
keyword[return] identifier[next] ( identifier[x] keyword[for] identifier[x] keywo... | def findvalue(array, value, compare=lambda x, y: x == y):
"""A function that uses the compare function to return a value from the list."""
try:
return next((x for x in array if compare(x, value))) # depends on [control=['try'], data=[]]
except StopIteration:
raise ValueError('%r not in arra... |
def map(self, f):
"""
Maps this Pair with *f*'; see :meth:`vanilla.core.Recver.map`
Returns a new Pair of our current Sender and the mapped target's
Recver.
"""
return self._replace(recver=self.recver.map(f)) | def function[map, parameter[self, f]]:
constant[
Maps this Pair with *f*'; see :meth:`vanilla.core.Recver.map`
Returns a new Pair of our current Sender and the mapped target's
Recver.
]
return[call[name[self]._replace, parameter[]]] | keyword[def] identifier[map] ( identifier[self] , identifier[f] ):
literal[string]
keyword[return] identifier[self] . identifier[_replace] ( identifier[recver] = identifier[self] . identifier[recver] . identifier[map] ( identifier[f] )) | def map(self, f):
"""
Maps this Pair with *f*'; see :meth:`vanilla.core.Recver.map`
Returns a new Pair of our current Sender and the mapped target's
Recver.
"""
return self._replace(recver=self.recver.map(f)) |
def get(self, name, template_path):
'''
Returns the renderer object.
:param name: name of the requested renderer
:param template_path: path to the template
'''
if name not in self._renderers:
cls = self._renderer_classes.get(name)
if cls is None:
... | def function[get, parameter[self, name, template_path]]:
constant[
Returns the renderer object.
:param name: name of the requested renderer
:param template_path: path to the template
]
if compare[name[name] <ast.NotIn object at 0x7da2590d7190> name[self]._renderers] begi... | keyword[def] identifier[get] ( identifier[self] , identifier[name] , identifier[template_path] ):
literal[string]
keyword[if] identifier[name] keyword[not] keyword[in] identifier[self] . identifier[_renderers] :
identifier[cls] = identifier[self] . identifier[_renderer_classes] . i... | def get(self, name, template_path):
"""
Returns the renderer object.
:param name: name of the requested renderer
:param template_path: path to the template
"""
if name not in self._renderers:
cls = self._renderer_classes.get(name)
if cls is None:
retu... |
def convert_concat(net, node, module, builder):
"""Convert concat layer from mxnet to coreml.
Parameters
----------
network: net
A mxnet network object.
layer: node
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
A neural ... | def function[convert_concat, parameter[net, node, module, builder]]:
constant[Convert concat layer from mxnet to coreml.
Parameters
----------
network: net
A mxnet network object.
layer: node
Node to convert.
module: module
An module for MXNet
builder: NeuralN... | keyword[def] identifier[convert_concat] ( identifier[net] , identifier[node] , identifier[module] , identifier[builder] ):
literal[string]
identifier[input_names] , identifier[output_name] = identifier[_get_input_output_name] ( identifier[net] , identifier[node] , literal[string] )
identifier[nam... | def convert_concat(net, node, module, builder):
"""Convert concat layer from mxnet to coreml.
Parameters
----------
network: net
A mxnet network object.
layer: node
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
A neural ... |
def add_movie(self, movie_file, left, top, width, height,
poster_frame_image=None, mime_type=CT.VIDEO):
"""Return newly added movie shape displaying video in *movie_file*.
**EXPERIMENTAL.** This method has important limitations:
* The size must be specified; no auto-scaling s... | def function[add_movie, parameter[self, movie_file, left, top, width, height, poster_frame_image, mime_type]]:
constant[Return newly added movie shape displaying video in *movie_file*.
**EXPERIMENTAL.** This method has important limitations:
* The size must be specified; no auto-scaling such a... | keyword[def] identifier[add_movie] ( identifier[self] , identifier[movie_file] , identifier[left] , identifier[top] , identifier[width] , identifier[height] ,
identifier[poster_frame_image] = keyword[None] , identifier[mime_type] = identifier[CT] . identifier[VIDEO] ):
literal[string]
identifier[m... | def add_movie(self, movie_file, left, top, width, height, poster_frame_image=None, mime_type=CT.VIDEO):
"""Return newly added movie shape displaying video in *movie_file*.
**EXPERIMENTAL.** This method has important limitations:
* The size must be specified; no auto-scaling such as that provided
... |
def write_version_info(conn, version_table, version_value):
"""
Inserts the version value in to the version table.
Parameters
----------
conn : sa.Connection
The connection to use to execute the insert.
version_table : sa.Table
The version table of the asset database
version... | def function[write_version_info, parameter[conn, version_table, version_value]]:
constant[
Inserts the version value in to the version table.
Parameters
----------
conn : sa.Connection
The connection to use to execute the insert.
version_table : sa.Table
The version table of... | keyword[def] identifier[write_version_info] ( identifier[conn] , identifier[version_table] , identifier[version_value] ):
literal[string]
identifier[conn] . identifier[execute] ( identifier[sa] . identifier[insert] ( identifier[version_table] , identifier[values] ={ literal[string] : identifier[version_val... | def write_version_info(conn, version_table, version_value):
"""
Inserts the version value in to the version table.
Parameters
----------
conn : sa.Connection
The connection to use to execute the insert.
version_table : sa.Table
The version table of the asset database
version... |
def _TrimNode(node, index, depth, flags):
"""
Internal helper method to trim a node.
Args:
node (MerkleTreeNode):
index (int): flag index.
depth (int): node tree depth to start trim from.
flags (bytearray): of left/right pairs. 1 byte for the left... | def function[_TrimNode, parameter[node, index, depth, flags]]:
constant[
Internal helper method to trim a node.
Args:
node (MerkleTreeNode):
index (int): flag index.
depth (int): node tree depth to start trim from.
flags (bytearray): of left/right... | keyword[def] identifier[_TrimNode] ( identifier[node] , identifier[index] , identifier[depth] , identifier[flags] ):
literal[string]
keyword[if] identifier[depth] == literal[int] keyword[or] identifier[node] . identifier[LeftChild] keyword[is] keyword[None] :
keyword[return]
... | def _TrimNode(node, index, depth, flags):
"""
Internal helper method to trim a node.
Args:
node (MerkleTreeNode):
index (int): flag index.
depth (int): node tree depth to start trim from.
flags (bytearray): of left/right pairs. 1 byte for the left nod... |
def players(game_id):
"""Gets player/coach/umpire information for the game with matching id."""
# get data
data = mlbgame.data.get_players(game_id)
# parse data
parsed = etree.parse(data)
root = parsed.getroot()
output = {}
output['game_id'] = game_id
# get player/coach data
fo... | def function[players, parameter[game_id]]:
constant[Gets player/coach/umpire information for the game with matching id.]
variable[data] assign[=] call[name[mlbgame].data.get_players, parameter[name[game_id]]]
variable[parsed] assign[=] call[name[etree].parse, parameter[name[data]]]
varia... | keyword[def] identifier[players] ( identifier[game_id] ):
literal[string]
identifier[data] = identifier[mlbgame] . identifier[data] . identifier[get_players] ( identifier[game_id] )
identifier[parsed] = identifier[etree] . identifier[parse] ( identifier[data] )
identifier[root] = identi... | def players(game_id):
"""Gets player/coach/umpire information for the game with matching id."""
# get data
data = mlbgame.data.get_players(game_id)
# parse data
parsed = etree.parse(data)
root = parsed.getroot()
output = {}
output['game_id'] = game_id
# get player/coach data
for ... |
def to_dict(self):
"""Useful for providing arguments to templates.
:API: public
"""
ret = {}
for key in ['name', 'cmd', 'id', 'start_time', 'end_time',
'outcome', 'start_time_string', 'start_delta_string']:
val = getattr(self, key)
ret[key] = val() if hasattr(val, '__cal... | def function[to_dict, parameter[self]]:
constant[Useful for providing arguments to templates.
:API: public
]
variable[ret] assign[=] dictionary[[], []]
for taget[name[key]] in starred[list[[<ast.Constant object at 0x7da1b2279480>, <ast.Constant object at 0x7da1b227a740>, <ast.Constant o... | keyword[def] identifier[to_dict] ( identifier[self] ):
literal[string]
identifier[ret] ={}
keyword[for] identifier[key] keyword[in] [ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ,
literal[string] , literal[string] , literal[string] ]:
identifie... | def to_dict(self):
"""Useful for providing arguments to templates.
:API: public
"""
ret = {}
for key in ['name', 'cmd', 'id', 'start_time', 'end_time', 'outcome', 'start_time_string', 'start_delta_string']:
val = getattr(self, key)
ret[key] = val() if hasattr(val, '__call__') else v... |
def _mysql_aes_unpad(val):
"""Reverse padding."""
val = _to_string(val)
pad_value = ord(val[-1])
return val[:-pad_value] | def function[_mysql_aes_unpad, parameter[val]]:
constant[Reverse padding.]
variable[val] assign[=] call[name[_to_string], parameter[name[val]]]
variable[pad_value] assign[=] call[name[ord], parameter[call[name[val]][<ast.UnaryOp object at 0x7da2044c25f0>]]]
return[call[name[val]][<ast.Slice ... | keyword[def] identifier[_mysql_aes_unpad] ( identifier[val] ):
literal[string]
identifier[val] = identifier[_to_string] ( identifier[val] )
identifier[pad_value] = identifier[ord] ( identifier[val] [- literal[int] ])
keyword[return] identifier[val] [:- identifier[pad_value] ] | def _mysql_aes_unpad(val):
"""Reverse padding."""
val = _to_string(val)
pad_value = ord(val[-1])
return val[:-pad_value] |
def get_labels(self, depth=None):
"""
Returns a list of labels created by this reference.
Parameters
----------
depth : integer or ``None``
If not ``None``, defines from how many reference levels to
retrieve labels from.
Returns
-------
... | def function[get_labels, parameter[self, depth]]:
constant[
Returns a list of labels created by this reference.
Parameters
----------
depth : integer or ``None``
If not ``None``, defines from how many reference levels to
retrieve labels from.
Ret... | keyword[def] identifier[get_labels] ( identifier[self] , identifier[depth] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[self] . identifier[ref_cell] , identifier[Cell] ):
keyword[return] []
keyword[if] identifier[self] . id... | def get_labels(self, depth=None):
"""
Returns a list of labels created by this reference.
Parameters
----------
depth : integer or ``None``
If not ``None``, defines from how many reference levels to
retrieve labels from.
Returns
-------
... |
def fetch(self, card_id, data={}, **kwargs):
""""
Fetch Card for given Id
Args:
card_id : Id for which card object has to be retrieved
Returns:
Card dict for given card Id
"""
return super(Card, self).fetch(card_id, data, **kwargs) | def function[fetch, parameter[self, card_id, data]]:
constant["
Fetch Card for given Id
Args:
card_id : Id for which card object has to be retrieved
Returns:
Card dict for given card Id
]
return[call[call[name[super], parameter[name[Card], name[self]... | keyword[def] identifier[fetch] ( identifier[self] , identifier[card_id] , identifier[data] ={},** identifier[kwargs] ):
literal[string]
keyword[return] identifier[super] ( identifier[Card] , identifier[self] ). identifier[fetch] ( identifier[card_id] , identifier[data] ,** identifier[kwargs] ) | def fetch(self, card_id, data={}, **kwargs):
""""
Fetch Card for given Id
Args:
card_id : Id for which card object has to be retrieved
Returns:
Card dict for given card Id
"""
return super(Card, self).fetch(card_id, data, **kwargs) |
def getWorksheetServices(self):
"""get list of analysis services present on this worksheet
"""
services = []
for analysis in self.getAnalyses():
service = analysis.getAnalysisService()
if service and service not in services:
services.append(service... | def function[getWorksheetServices, parameter[self]]:
constant[get list of analysis services present on this worksheet
]
variable[services] assign[=] list[[]]
for taget[name[analysis]] in starred[call[name[self].getAnalyses, parameter[]]] begin[:]
variable[service] assign[... | keyword[def] identifier[getWorksheetServices] ( identifier[self] ):
literal[string]
identifier[services] =[]
keyword[for] identifier[analysis] keyword[in] identifier[self] . identifier[getAnalyses] ():
identifier[service] = identifier[analysis] . identifier[getAnalysisServi... | def getWorksheetServices(self):
"""get list of analysis services present on this worksheet
"""
services = []
for analysis in self.getAnalyses():
service = analysis.getAnalysisService()
if service and service not in services:
services.append(service) # depends on [control... |
def getHelpFileAsString(taskname,taskpath):
"""
This functions will return useful help as a string read from a file
in the task's installed directory called "<module>.help".
If no such file can be found, it will simply return an empty string.
Notes
-----
The location of the actual help fil... | def function[getHelpFileAsString, parameter[taskname, taskpath]]:
constant[
This functions will return useful help as a string read from a file
in the task's installed directory called "<module>.help".
If no such file can be found, it will simply return an empty string.
Notes
-----
The... | keyword[def] identifier[getHelpFileAsString] ( identifier[taskname] , identifier[taskpath] ):
literal[string]
identifier[pathsplit] = identifier[os] . identifier[path] . identifier[split] ( identifier[taskpath] )
keyword[if] identifier[taskname] . identifier[find] ( literal[string] )>- literal[i... | def getHelpFileAsString(taskname, taskpath):
"""
This functions will return useful help as a string read from a file
in the task's installed directory called "<module>.help".
If no such file can be found, it will simply return an empty string.
Notes
-----
The location of the actual help fi... |
def ELBND(w, e, function="max"):
"""
This function estimates Error and Learning Based Novelty Detection measure
from given data.
**Args:**
* `w` : history of adaptive parameters of an adaptive model (2d array),
every row represents parameters in given time index.
* `e` : error of adapti... | def function[ELBND, parameter[w, e, function]]:
constant[
This function estimates Error and Learning Based Novelty Detection measure
from given data.
**Args:**
* `w` : history of adaptive parameters of an adaptive model (2d array),
every row represents parameters in given time index.
... | keyword[def] identifier[ELBND] ( identifier[w] , identifier[e] , identifier[function] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[function] keyword[in] [ literal[string] , literal[string] ]:
keyword[raise] identifier[ValueError] ( literal[string] )
... | def ELBND(w, e, function='max'):
"""
This function estimates Error and Learning Based Novelty Detection measure
from given data.
**Args:**
* `w` : history of adaptive parameters of an adaptive model (2d array),
every row represents parameters in given time index.
* `e` : error of adapti... |
def _accept_as_blank(self, url_info: URLInfo):
'''Mark the URL as OK in the pool.'''
_logger.debug(__('Got empty robots.txt for {0}.', url_info.url))
self._robots_txt_pool.load_robots_txt(url_info, '') | def function[_accept_as_blank, parameter[self, url_info]]:
constant[Mark the URL as OK in the pool.]
call[name[_logger].debug, parameter[call[name[__], parameter[constant[Got empty robots.txt for {0}.], name[url_info].url]]]]
call[name[self]._robots_txt_pool.load_robots_txt, parameter[name[url_i... | keyword[def] identifier[_accept_as_blank] ( identifier[self] , identifier[url_info] : identifier[URLInfo] ):
literal[string]
identifier[_logger] . identifier[debug] ( identifier[__] ( literal[string] , identifier[url_info] . identifier[url] ))
identifier[self] . identifier[_robots_txt_pool... | def _accept_as_blank(self, url_info: URLInfo):
"""Mark the URL as OK in the pool."""
_logger.debug(__('Got empty robots.txt for {0}.', url_info.url))
self._robots_txt_pool.load_robots_txt(url_info, '') |
def append_formula(self, formula, no_return=True):
"""
Appends list of clauses to solver's internal formula.
"""
if self.maplesat:
res = None
for clause in formula:
res = self.add_clause(clause, no_return)
if not no_return:
... | def function[append_formula, parameter[self, formula, no_return]]:
constant[
Appends list of clauses to solver's internal formula.
]
if name[self].maplesat begin[:]
variable[res] assign[=] constant[None]
for taget[name[clause]] in starred[name[formula]... | keyword[def] identifier[append_formula] ( identifier[self] , identifier[formula] , identifier[no_return] = keyword[True] ):
literal[string]
keyword[if] identifier[self] . identifier[maplesat] :
identifier[res] = keyword[None]
keyword[for] identifier[clause] keyword[in... | def append_formula(self, formula, no_return=True):
"""
Appends list of clauses to solver's internal formula.
"""
if self.maplesat:
res = None
for clause in formula:
res = self.add_clause(clause, no_return) # depends on [control=['for'], data=['clause']]
i... |
def _make_completed_functions(self):
"""
Fill in self._completed_functions list and clean up job manager.
:return: None
"""
finished = self._get_finished_functions()
for func_addr in finished:
self._completed_functions.add(func_addr)
self._cleanup_an... | def function[_make_completed_functions, parameter[self]]:
constant[
Fill in self._completed_functions list and clean up job manager.
:return: None
]
variable[finished] assign[=] call[name[self]._get_finished_functions, parameter[]]
for taget[name[func_addr]] in starred[n... | keyword[def] identifier[_make_completed_functions] ( identifier[self] ):
literal[string]
identifier[finished] = identifier[self] . identifier[_get_finished_functions] ()
keyword[for] identifier[func_addr] keyword[in] identifier[finished] :
identifier[self] . identifier[_co... | def _make_completed_functions(self):
"""
Fill in self._completed_functions list and clean up job manager.
:return: None
"""
finished = self._get_finished_functions()
for func_addr in finished:
self._completed_functions.add(func_addr) # depends on [control=['for'], data=['fu... |
def hash_args(*args, **kwargs):
"""Define a unique string for any set of representable args."""
arg_string = '_'.join([str(arg) for arg in args])
kwarg_string = '_'.join([str(key) + '=' + str(value)
for key, value in iteritems(kwargs)])
combined = ':'.join([arg_string, kwarg... | def function[hash_args, parameter[]]:
constant[Define a unique string for any set of representable args.]
variable[arg_string] assign[=] call[constant[_].join, parameter[<ast.ListComp object at 0x7da1b1eba050>]]
variable[kwarg_string] assign[=] call[constant[_].join, parameter[<ast.ListComp obje... | keyword[def] identifier[hash_args] (* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[arg_string] = literal[string] . identifier[join] ([ identifier[str] ( identifier[arg] ) keyword[for] identifier[arg] keyword[in] identifier[args] ])
identifier[kwarg_string] = literal[string]... | def hash_args(*args, **kwargs):
"""Define a unique string for any set of representable args."""
arg_string = '_'.join([str(arg) for arg in args])
kwarg_string = '_'.join([str(key) + '=' + str(value) for (key, value) in iteritems(kwargs)])
combined = ':'.join([arg_string, kwarg_string])
hasher = md5(... |
def get_plugins(namespace, interface=None, check_extras=True, load_now=False):
"""
helper to get a direct interface to _Plugins
"""
return _DB.add_namespace(namespace, interface, check_extras, load_now) | def function[get_plugins, parameter[namespace, interface, check_extras, load_now]]:
constant[
helper to get a direct interface to _Plugins
]
return[call[name[_DB].add_namespace, parameter[name[namespace], name[interface], name[check_extras], name[load_now]]]] | keyword[def] identifier[get_plugins] ( identifier[namespace] , identifier[interface] = keyword[None] , identifier[check_extras] = keyword[True] , identifier[load_now] = keyword[False] ):
literal[string]
keyword[return] identifier[_DB] . identifier[add_namespace] ( identifier[namespace] , identifier[interf... | def get_plugins(namespace, interface=None, check_extras=True, load_now=False):
"""
helper to get a direct interface to _Plugins
"""
return _DB.add_namespace(namespace, interface, check_extras, load_now) |
def post(self, request, format=None):
""" validate password change operation and return result """
serializer_class = self.get_serializer_class()
serializer = serializer_class(data=request.data, instance=request.user)
if serializer.is_valid():
serializer.save()
r... | def function[post, parameter[self, request, format]]:
constant[ validate password change operation and return result ]
variable[serializer_class] assign[=] call[name[self].get_serializer_class, parameter[]]
variable[serializer] assign[=] call[name[serializer_class], parameter[]]
if call[... | keyword[def] identifier[post] ( identifier[self] , identifier[request] , identifier[format] = keyword[None] ):
literal[string]
identifier[serializer_class] = identifier[self] . identifier[get_serializer_class] ()
identifier[serializer] = identifier[serializer_class] ( identifier[data] = id... | def post(self, request, format=None):
""" validate password change operation and return result """
serializer_class = self.get_serializer_class()
serializer = serializer_class(data=request.data, instance=request.user)
if serializer.is_valid():
serializer.save()
return Response({'detail':... |
def _BuildPluginRequest(self, app_id, challenge_data, origin):
"""Builds a JSON request in the form that the plugin expects."""
client_data_map = {}
encoded_challenges = []
app_id_hash_encoded = self._Base64Encode(self._SHA256(app_id))
for challenge_item in challenge_data:
key = challenge_item... | def function[_BuildPluginRequest, parameter[self, app_id, challenge_data, origin]]:
constant[Builds a JSON request in the form that the plugin expects.]
variable[client_data_map] assign[=] dictionary[[], []]
variable[encoded_challenges] assign[=] list[[]]
variable[app_id_hash_encoded] as... | keyword[def] identifier[_BuildPluginRequest] ( identifier[self] , identifier[app_id] , identifier[challenge_data] , identifier[origin] ):
literal[string]
identifier[client_data_map] ={}
identifier[encoded_challenges] =[]
identifier[app_id_hash_encoded] = identifier[self] . identifier[_Base64Encod... | def _BuildPluginRequest(self, app_id, challenge_data, origin):
"""Builds a JSON request in the form that the plugin expects."""
client_data_map = {}
encoded_challenges = []
app_id_hash_encoded = self._Base64Encode(self._SHA256(app_id))
for challenge_item in challenge_data:
key = challenge_it... |
def fromxlsx(filename, sheet=None, range_string=None, row_offset=0,
column_offset=0, **kwargs):
"""
Extract a table from a sheet in an Excel .xlsx file.
N.B., the sheet name is case sensitive.
The `sheet` argument can be omitted, in which case the first sheet in
the workbook is used b... | def function[fromxlsx, parameter[filename, sheet, range_string, row_offset, column_offset]]:
constant[
Extract a table from a sheet in an Excel .xlsx file.
N.B., the sheet name is case sensitive.
The `sheet` argument can be omitted, in which case the first sheet in
the workbook is used by defa... | keyword[def] identifier[fromxlsx] ( identifier[filename] , identifier[sheet] = keyword[None] , identifier[range_string] = keyword[None] , identifier[row_offset] = literal[int] ,
identifier[column_offset] = literal[int] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[XLSXView] ( iden... | def fromxlsx(filename, sheet=None, range_string=None, row_offset=0, column_offset=0, **kwargs):
"""
Extract a table from a sheet in an Excel .xlsx file.
N.B., the sheet name is case sensitive.
The `sheet` argument can be omitted, in which case the first sheet in
the workbook is used by default.
... |
def _setFlag(self, name, val, defVal):
"""set the objects property propName if the dictKey key exists in dict and it is not the same as default value defVal"""
if not hasattr(self, "flags"):
self.flags = {}
if val != defVal:
self.flags[name] = val | def function[_setFlag, parameter[self, name, val, defVal]]:
constant[set the objects property propName if the dictKey key exists in dict and it is not the same as default value defVal]
if <ast.UnaryOp object at 0x7da1b26ac8b0> begin[:]
name[self].flags assign[=] dictionary[[], []]
... | keyword[def] identifier[_setFlag] ( identifier[self] , identifier[name] , identifier[val] , identifier[defVal] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[self] , literal[string] ):
identifier[self] . identifier[flags] ={}
keyword[if] identi... | def _setFlag(self, name, val, defVal):
"""set the objects property propName if the dictKey key exists in dict and it is not the same as default value defVal"""
if not hasattr(self, 'flags'):
self.flags = {} # depends on [control=['if'], data=[]]
if val != defVal:
self.flags[name] = val # d... |
def load_transform_parameters(self):
"Cache the parameters necessary to transform x & y coordinates"
x_min, x_max, x_div = self.x_range()
y_min, y_max, y_div = self.y_range()
x_step = (float(self.graph_width) - self.font_size * 2) / \
(x_max - x_min)
y_step = (float(self.graph_height) - self.font_size * 2)... | def function[load_transform_parameters, parameter[self]]:
constant[Cache the parameters necessary to transform x & y coordinates]
<ast.Tuple object at 0x7da1b0217040> assign[=] call[name[self].x_range, parameter[]]
<ast.Tuple object at 0x7da1b0215cf0> assign[=] call[name[self].y_range, parameter... | keyword[def] identifier[load_transform_parameters] ( identifier[self] ):
literal[string]
identifier[x_min] , identifier[x_max] , identifier[x_div] = identifier[self] . identifier[x_range] ()
identifier[y_min] , identifier[y_max] , identifier[y_div] = identifier[self] . identifier[y_range] ()
identifier[x... | def load_transform_parameters(self):
"""Cache the parameters necessary to transform x & y coordinates"""
(x_min, x_max, x_div) = self.x_range()
(y_min, y_max, y_div) = self.y_range()
x_step = (float(self.graph_width) - self.font_size * 2) / (x_max - x_min)
y_step = (float(self.graph_height) - self.f... |
def get_file_info(self, relativePath, name=None):
"""
get file information dict from the repository given its relative path and name.
:Parameters:
#. relativePath (string): The relative to the repository path of the directory where the file is.
#. name (string): The file... | def function[get_file_info, parameter[self, relativePath, name]]:
constant[
get file information dict from the repository given its relative path and name.
:Parameters:
#. relativePath (string): The relative to the repository path of the directory where the file is.
#. n... | keyword[def] identifier[get_file_info] ( identifier[self] , identifier[relativePath] , identifier[name] = keyword[None] ):
literal[string]
identifier[relativePath] = identifier[os] . identifier[path] . identifier[normpath] ( identifier[relativePath] )
keyword[if] identifier[relat... | def get_file_info(self, relativePath, name=None):
"""
get file information dict from the repository given its relative path and name.
:Parameters:
#. relativePath (string): The relative to the repository path of the directory where the file is.
#. name (string): The file nam... |
def create_table(self):
'''
Hook point for overriding how the CounterPool creates a new table
in DynamooDB
'''
table = self.conn.create_table(
name=self.get_table_name(),
schema=self.get_schema(),
read_units=self.get_read_units(),
w... | def function[create_table, parameter[self]]:
constant[
Hook point for overriding how the CounterPool creates a new table
in DynamooDB
]
variable[table] assign[=] call[name[self].conn.create_table, parameter[]]
if compare[name[table].status not_equal[!=] constant[ACTIVE]] ... | keyword[def] identifier[create_table] ( identifier[self] ):
literal[string]
identifier[table] = identifier[self] . identifier[conn] . identifier[create_table] (
identifier[name] = identifier[self] . identifier[get_table_name] (),
identifier[schema] = identifier[self] . identifier[... | def create_table(self):
"""
Hook point for overriding how the CounterPool creates a new table
in DynamooDB
"""
table = self.conn.create_table(name=self.get_table_name(), schema=self.get_schema(), read_units=self.get_read_units(), write_units=self.get_write_units())
if table.status !=... |
def get(key, **kwargs):
'''
Gets details for a single, interpreted occurrence
:param key: [int] A GBIF occurrence key
:return: A dictionary, of results
Usage::
from pygbif import occurrences
occurrences.get(key = 1258202889)
occurrences.get(key = 1227768771)
occur... | def function[get, parameter[key]]:
constant[
Gets details for a single, interpreted occurrence
:param key: [int] A GBIF occurrence key
:return: A dictionary, of results
Usage::
from pygbif import occurrences
occurrences.get(key = 1258202889)
occurrences.get(key = 1227... | keyword[def] identifier[get] ( identifier[key] ,** identifier[kwargs] ):
literal[string]
identifier[url] = identifier[gbif_baseurl] + literal[string] + identifier[str] ( identifier[key] )
identifier[out] = identifier[gbif_GET] ( identifier[url] ,{},** identifier[kwargs] )
keyword[return] identif... | def get(key, **kwargs):
"""
Gets details for a single, interpreted occurrence
:param key: [int] A GBIF occurrence key
:return: A dictionary, of results
Usage::
from pygbif import occurrences
occurrences.get(key = 1258202889)
occurrences.get(key = 1227768771)
occur... |
def weighted_random_choice(items):
"""
Returns a weighted random choice from a list of items.
:param items: A list of tuples (object, weight)
:return: A random object, whose likelihood is proportional to its weight.
"""
l = list(items)
r = random.random() * sum([i[1] for i in l])
for x, ... | def function[weighted_random_choice, parameter[items]]:
constant[
Returns a weighted random choice from a list of items.
:param items: A list of tuples (object, weight)
:return: A random object, whose likelihood is proportional to its weight.
]
variable[l] assign[=] call[name[list], para... | keyword[def] identifier[weighted_random_choice] ( identifier[items] ):
literal[string]
identifier[l] = identifier[list] ( identifier[items] )
identifier[r] = identifier[random] . identifier[random] ()* identifier[sum] ([ identifier[i] [ literal[int] ] keyword[for] identifier[i] keyword[in] identifi... | def weighted_random_choice(items):
"""
Returns a weighted random choice from a list of items.
:param items: A list of tuples (object, weight)
:return: A random object, whose likelihood is proportional to its weight.
"""
l = list(items)
r = random.random() * sum([i[1] for i in l])
for (x,... |
def is_equal(self, other):
"""Equality checker with message
:param other: Other Impact Function to be compared.
:type other: ImpactFunction
:returns: True if both are the same IF, other wise False and the
message.
:rtype: bool, str
"""
properties = [... | def function[is_equal, parameter[self, other]]:
constant[Equality checker with message
:param other: Other Impact Function to be compared.
:type other: ImpactFunction
:returns: True if both are the same IF, other wise False and the
message.
:rtype: bool, str
... | keyword[def] identifier[is_equal] ( identifier[self] , identifier[other] ):
literal[string]
identifier[properties] =[
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
literal[st... | def is_equal(self, other):
"""Equality checker with message
:param other: Other Impact Function to be compared.
:type other: ImpactFunction
:returns: True if both are the same IF, other wise False and the
message.
:rtype: bool, str
"""
# 'performance_log', ... |
def trigger_event(self, source, event, args):
"""
Trigger an event on the Entity
* \a source: The source of the event
* \a event: The event being triggered
* \a args: A list of arguments to pass to the callback
"""
actions = []
for action in event.actions:
if callable(action):
ac = action(self, *... | def function[trigger_event, parameter[self, source, event, args]]:
constant[
Trigger an event on the Entity
* source: The source of the event
* event: The event being triggered
* args: A list of arguments to pass to the callback
]
variable[actions] assign[=] list[[]]
for taget[na... | keyword[def] identifier[trigger_event] ( identifier[self] , identifier[source] , identifier[event] , identifier[args] ):
literal[string]
identifier[actions] =[]
keyword[for] identifier[action] keyword[in] identifier[event] . identifier[actions] :
keyword[if] identifier[callable] ( identifier[action]... | def trigger_event(self, source, event, args):
"""
Trigger an event on the Entity
* \x07 source: The source of the event
* \x07 event: The event being triggered
* \x07 args: A list of arguments to pass to the callback
"""
actions = []
for action in event.actions:
if callable(action):
... |
def _out(ins):
""" Translates OUT to asm.
"""
output = _8bit_oper(ins.quad[2])
output.extend(_16bit_oper(ins.quad[1]))
output.append('ld b, h')
output.append('ld c, l')
output.append('out (c), a')
return output | def function[_out, parameter[ins]]:
constant[ Translates OUT to asm.
]
variable[output] assign[=] call[name[_8bit_oper], parameter[call[name[ins].quad][constant[2]]]]
call[name[output].extend, parameter[call[name[_16bit_oper], parameter[call[name[ins].quad][constant[1]]]]]]
call[name... | keyword[def] identifier[_out] ( identifier[ins] ):
literal[string]
identifier[output] = identifier[_8bit_oper] ( identifier[ins] . identifier[quad] [ literal[int] ])
identifier[output] . identifier[extend] ( identifier[_16bit_oper] ( identifier[ins] . identifier[quad] [ literal[int] ]))
identifie... | def _out(ins):
""" Translates OUT to asm.
"""
output = _8bit_oper(ins.quad[2])
output.extend(_16bit_oper(ins.quad[1]))
output.append('ld b, h')
output.append('ld c, l')
output.append('out (c), a')
return output |
def element_wise_op(array, other, op, ty):
"""
Operation of series and other, element-wise (binary operator add)
Args:
array (WeldObject / Numpy.ndarray): Input array
other (WeldObject / Numpy.ndarray): Second Input array
op (str): Op string used to compute element-wise operation (+... | def function[element_wise_op, parameter[array, other, op, ty]]:
constant[
Operation of series and other, element-wise (binary operator add)
Args:
array (WeldObject / Numpy.ndarray): Input array
other (WeldObject / Numpy.ndarray): Second Input array
op (str): Op string used to co... | keyword[def] identifier[element_wise_op] ( identifier[array] , identifier[other] , identifier[op] , identifier[ty] ):
literal[string]
identifier[weld_obj] = identifier[WeldObject] ( identifier[encoder_] , identifier[decoder_] )
identifier[array_var] = identifier[weld_obj] . identifier[update] ( ident... | def element_wise_op(array, other, op, ty):
"""
Operation of series and other, element-wise (binary operator add)
Args:
array (WeldObject / Numpy.ndarray): Input array
other (WeldObject / Numpy.ndarray): Second Input array
op (str): Op string used to compute element-wise operation (+... |
def _normalize_string(raw_str):
"""Normalizes the string using tokenizer.encode.
Args:
raw_str: the input string
Returns:
A string which is ready to be tokenized using split()
"""
return " ".join(
token.strip()
for token in tokenizer.encode(text_encoder.native_to_unicode(raw_str))) | def function[_normalize_string, parameter[raw_str]]:
constant[Normalizes the string using tokenizer.encode.
Args:
raw_str: the input string
Returns:
A string which is ready to be tokenized using split()
]
return[call[constant[ ].join, parameter[<ast.GeneratorExp object at 0x7da20cabd8a0>]]] | keyword[def] identifier[_normalize_string] ( identifier[raw_str] ):
literal[string]
keyword[return] literal[string] . identifier[join] (
identifier[token] . identifier[strip] ()
keyword[for] identifier[token] keyword[in] identifier[tokenizer] . identifier[encode] ( identifier[text_encoder] . identifi... | def _normalize_string(raw_str):
"""Normalizes the string using tokenizer.encode.
Args:
raw_str: the input string
Returns:
A string which is ready to be tokenized using split()
"""
return ' '.join((token.strip() for token in tokenizer.encode(text_encoder.native_to_unicode(raw_str)))) |
def delete(self, source):
'''Thread worker for download operation.'''
s3url = S3URL(source)
message('Delete %s', source)
if not self.opt.dry_run:
self.s3.delete_object(Bucket=s3url.bucket, Key=s3url.path) | def function[delete, parameter[self, source]]:
constant[Thread worker for download operation.]
variable[s3url] assign[=] call[name[S3URL], parameter[name[source]]]
call[name[message], parameter[constant[Delete %s], name[source]]]
if <ast.UnaryOp object at 0x7da1b0247b50> begin[:]
... | keyword[def] identifier[delete] ( identifier[self] , identifier[source] ):
literal[string]
identifier[s3url] = identifier[S3URL] ( identifier[source] )
identifier[message] ( literal[string] , identifier[source] )
keyword[if] keyword[not] identifier[self] . identifier[opt] . identifier[dry_run]... | def delete(self, source):
"""Thread worker for download operation."""
s3url = S3URL(source)
message('Delete %s', source)
if not self.opt.dry_run:
self.s3.delete_object(Bucket=s3url.bucket, Key=s3url.path) # depends on [control=['if'], data=[]] |
def map(self, path):
"""Map `path` through the aliases.
`path` is checked against all of the patterns. The first pattern to
match is used to replace the root of the path with the result root.
Only one pattern is ever used. If no patterns match, `path` is
returned unchanged.
... | def function[map, parameter[self, path]]:
constant[Map `path` through the aliases.
`path` is checked against all of the patterns. The first pattern to
match is used to replace the root of the path with the result root.
Only one pattern is ever used. If no patterns match, `path` is
... | keyword[def] identifier[map] ( identifier[self] , identifier[path] ):
literal[string]
keyword[for] identifier[regex] , identifier[result] , identifier[pattern_sep] , identifier[result_sep] keyword[in] identifier[self] . identifier[aliases] :
identifier[m] = identifier[regex] . ident... | def map(self, path):
"""Map `path` through the aliases.
`path` is checked against all of the patterns. The first pattern to
match is used to replace the root of the path with the result root.
Only one pattern is ever used. If no patterns match, `path` is
returned unchanged.
... |
def infer(self, x, **fit_params):
"""Perform a single inference step on a batch of data.
Parameters
----------
x : input data
A batch of the input data.
**fit_params : dict
Additional parameters passed to the ``forward`` method of
the module and to... | def function[infer, parameter[self, x]]:
constant[Perform a single inference step on a batch of data.
Parameters
----------
x : input data
A batch of the input data.
**fit_params : dict
Additional parameters passed to the ``forward`` method of
the ... | keyword[def] identifier[infer] ( identifier[self] , identifier[x] ,** identifier[fit_params] ):
literal[string]
identifier[x] = identifier[to_tensor] ( identifier[x] , identifier[device] = identifier[self] . identifier[device] )
keyword[if] identifier[isinstance] ( identifier[x] , identif... | def infer(self, x, **fit_params):
"""Perform a single inference step on a batch of data.
Parameters
----------
x : input data
A batch of the input data.
**fit_params : dict
Additional parameters passed to the ``forward`` method of
the module and to the... |
def PTEST(cpu, dest, src):
""" PTEST
PTEST set the ZF flag if all bits in the result are 0 of the bitwise AND
of the first source operand (first operand) and the second source operand
(second operand). Also this sets the CF flag if all bits in the result
are 0 of the bitwise ... | def function[PTEST, parameter[cpu, dest, src]]:
constant[ PTEST
PTEST set the ZF flag if all bits in the result are 0 of the bitwise AND
of the first source operand (first operand) and the second source operand
(second operand). Also this sets the CF flag if all bits in the result
... | keyword[def] identifier[PTEST] ( identifier[cpu] , identifier[dest] , identifier[src] ):
literal[string]
identifier[cpu] . identifier[OF] = keyword[False]
identifier[cpu] . identifier[AF] = keyword[False]
identifier[cpu] . identifier[PF] = keyword[False]
identifier[cpu... | def PTEST(cpu, dest, src):
""" PTEST
PTEST set the ZF flag if all bits in the result are 0 of the bitwise AND
of the first source operand (first operand) and the second source operand
(second operand). Also this sets the CF flag if all bits in the result
are 0 of the bitwise AND ... |
def expire(self, time=None):
"""Remove expired items from the cache."""
if time is None:
time = self.__timer()
root = self.__root
curr = root.next
links = self.__links
cache_delitem = Cache.__delitem__
while curr is not root and curr.expire < time:
... | def function[expire, parameter[self, time]]:
constant[Remove expired items from the cache.]
if compare[name[time] is constant[None]] begin[:]
variable[time] assign[=] call[name[self].__timer, parameter[]]
variable[root] assign[=] name[self].__root
variable[curr] assign[=]... | keyword[def] identifier[expire] ( identifier[self] , identifier[time] = keyword[None] ):
literal[string]
keyword[if] identifier[time] keyword[is] keyword[None] :
identifier[time] = identifier[self] . identifier[__timer] ()
identifier[root] = identifier[self] . identifier[__... | def expire(self, time=None):
"""Remove expired items from the cache."""
if time is None:
time = self.__timer() # depends on [control=['if'], data=['time']]
root = self.__root
curr = root.next
links = self.__links
cache_delitem = Cache.__delitem__
while curr is not root and curr.expi... |
def _unique_by_email(users_and_watches):
"""Given a sequence of (User/EmailUser, [Watch, ...]) pairs
clustered by email address (which is never ''), yield from each
cluster a single pair like this::
(User/EmailUser, [Watch, Watch, ...]).
The User/Email is that of...
(1) the first incoming pa... | def function[_unique_by_email, parameter[users_and_watches]]:
constant[Given a sequence of (User/EmailUser, [Watch, ...]) pairs
clustered by email address (which is never ''), yield from each
cluster a single pair like this::
(User/EmailUser, [Watch, Watch, ...]).
The User/Email is that of..... | keyword[def] identifier[_unique_by_email] ( identifier[users_and_watches] ):
literal[string]
keyword[def] identifier[ensure_user_has_email] ( identifier[user] , identifier[cluster_email] ):
literal[string]
keyword[if] keyword[not] identifier[getattr] ( identifier[user] , lite... | def _unique_by_email(users_and_watches):
"""Given a sequence of (User/EmailUser, [Watch, ...]) pairs
clustered by email address (which is never ''), yield from each
cluster a single pair like this::
(User/EmailUser, [Watch, Watch, ...]).
The User/Email is that of...
(1) the first incoming pa... |
def connect(components, connections, force_SLH=False, expand_simplify=True):
"""Connect a list of components according to a list of connections.
Args:
components (list): List of Circuit instances
connections (list): List of pairs ``((c1, port1), (c2, port2))`` where
``c1`` and ``c2`... | def function[connect, parameter[components, connections, force_SLH, expand_simplify]]:
constant[Connect a list of components according to a list of connections.
Args:
components (list): List of Circuit instances
connections (list): List of pairs ``((c1, port1), (c2, port2))`` where
... | keyword[def] identifier[connect] ( identifier[components] , identifier[connections] , identifier[force_SLH] = keyword[False] , identifier[expand_simplify] = keyword[True] ):
literal[string]
identifier[combined] = identifier[Concatenation] . identifier[create] (* identifier[components] )
identifier[cdi... | def connect(components, connections, force_SLH=False, expand_simplify=True):
"""Connect a list of components according to a list of connections.
Args:
components (list): List of Circuit instances
connections (list): List of pairs ``((c1, port1), (c2, port2))`` where
``c1`` and ``c2`... |
def _expand(template, seq):
"""
seq IS TUPLE OF OBJECTS IN PATH ORDER INTO THE DATA TREE
"""
if is_text(template):
return _simple_expand(template, seq)
elif is_data(template):
# EXPAND LISTS OF ITEMS USING THIS FORM
# {"from":from, "template":template, "separator":separator}
... | def function[_expand, parameter[template, seq]]:
constant[
seq IS TUPLE OF OBJECTS IN PATH ORDER INTO THE DATA TREE
]
if call[name[is_text], parameter[name[template]]] begin[:]
return[call[name[_simple_expand], parameter[name[template], name[seq]]]] | keyword[def] identifier[_expand] ( identifier[template] , identifier[seq] ):
literal[string]
keyword[if] identifier[is_text] ( identifier[template] ):
keyword[return] identifier[_simple_expand] ( identifier[template] , identifier[seq] )
keyword[elif] identifier[is_data] ( identifier[templa... | def _expand(template, seq):
"""
seq IS TUPLE OF OBJECTS IN PATH ORDER INTO THE DATA TREE
"""
if is_text(template):
return _simple_expand(template, seq) # depends on [control=['if'], data=[]]
elif is_data(template):
# EXPAND LISTS OF ITEMS USING THIS FORM
# {"from":from, "tem... |
def get_instance(self, payload):
"""
Build an instance of DailyInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.usage.record.daily.DailyInstance
:rtype: twilio.rest.api.v2010.account.usage.record.daily.DailyInstance
"""... | def function[get_instance, parameter[self, payload]]:
constant[
Build an instance of DailyInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.usage.record.daily.DailyInstance
:rtype: twilio.rest.api.v2010.account.usage.record.dail... | keyword[def] identifier[get_instance] ( identifier[self] , identifier[payload] ):
literal[string]
keyword[return] identifier[DailyInstance] ( identifier[self] . identifier[_version] , identifier[payload] , identifier[account_sid] = identifier[self] . identifier[_solution] [ literal[string] ],) | def get_instance(self, payload):
"""
Build an instance of DailyInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.usage.record.daily.DailyInstance
:rtype: twilio.rest.api.v2010.account.usage.record.daily.DailyInstance
"""
... |
def forward(self, # pylint: disable=arguments-differ
inputs: torch.Tensor,
mask: torch.LongTensor) -> torch.Tensor:
"""
Parameters
----------
inputs : ``torch.Tensor``, required.
A Tensor of shape ``(batch_size, sequence_length, hidden_size)``... | def function[forward, parameter[self, inputs, mask]]:
constant[
Parameters
----------
inputs : ``torch.Tensor``, required.
A Tensor of shape ``(batch_size, sequence_length, hidden_size)``.
mask : ``torch.LongTensor``, required.
A binary mask of shape ``(ba... | keyword[def] identifier[forward] ( identifier[self] ,
identifier[inputs] : identifier[torch] . identifier[Tensor] ,
identifier[mask] : identifier[torch] . identifier[LongTensor] )-> identifier[torch] . identifier[Tensor] :
literal[string]
identifier[batch_size] , identifier[total_sequence_length]... | def forward(self, inputs: torch.Tensor, mask: torch.LongTensor) -> torch.Tensor: # pylint: disable=arguments-differ
'\n Parameters\n ----------\n inputs : ``torch.Tensor``, required.\n A Tensor of shape ``(batch_size, sequence_length, hidden_size)``.\n mask : ``torch.LongTens... |
def range_difference(data, ground_truth, mask=None, normalized=False,
force_lower_is_better=True):
r"""Return dynamic range difference between ``data`` and ``ground_truth``.
Evaluates difference in range between input (``data``) and reference
data (``ground_truth``). Allows for normali... | def function[range_difference, parameter[data, ground_truth, mask, normalized, force_lower_is_better]]:
constant[Return dynamic range difference between ``data`` and ``ground_truth``.
Evaluates difference in range between input (``data``) and reference
data (``ground_truth``). Allows for normalization ... | keyword[def] identifier[range_difference] ( identifier[data] , identifier[ground_truth] , identifier[mask] = keyword[None] , identifier[normalized] = keyword[False] ,
identifier[force_lower_is_better] = keyword[True] ):
literal[string]
identifier[data] = identifier[np] . identifier[asarray] ( identifier[d... | def range_difference(data, ground_truth, mask=None, normalized=False, force_lower_is_better=True):
"""Return dynamic range difference between ``data`` and ``ground_truth``.
Evaluates difference in range between input (``data``) and reference
data (``ground_truth``). Allows for normalization (``normalized``... |
def main():
"""
This is a Toil pipeline to transfer TCGA data into an S3 Bucket
Data is pulled down with Genetorrent and transferred to S3 via S3AM.
"""
# Define Parser object and add to toil
parser = build_parser()
Job.Runner.addToilOptions(parser)
args = parser.parse_args()
# Stor... | def function[main, parameter[]]:
constant[
This is a Toil pipeline to transfer TCGA data into an S3 Bucket
Data is pulled down with Genetorrent and transferred to S3 via S3AM.
]
variable[parser] assign[=] call[name[build_parser], parameter[]]
call[name[Job].Runner.addToilOptions, pa... | keyword[def] identifier[main] ():
literal[string]
identifier[parser] = identifier[build_parser] ()
identifier[Job] . identifier[Runner] . identifier[addToilOptions] ( identifier[parser] )
identifier[args] = identifier[parser] . identifier[parse_args] ()
identifier[inputs] ={ litera... | def main():
"""
This is a Toil pipeline to transfer TCGA data into an S3 Bucket
Data is pulled down with Genetorrent and transferred to S3 via S3AM.
"""
# Define Parser object and add to toil
parser = build_parser()
Job.Runner.addToilOptions(parser)
args = parser.parse_args()
# Stor... |
def random_split(self, fraction, seed=None, exact=False):
"""
Randomly split the rows of an SFrame into two SFrames. The first SFrame
contains *M* rows, sampled uniformly (without replacement) from the
original SFrame. *M* is approximately the fraction times the original
number o... | def function[random_split, parameter[self, fraction, seed, exact]]:
constant[
Randomly split the rows of an SFrame into two SFrames. The first SFrame
contains *M* rows, sampled uniformly (without replacement) from the
original SFrame. *M* is approximately the fraction times the original
... | keyword[def] identifier[random_split] ( identifier[self] , identifier[fraction] , identifier[seed] = keyword[None] , identifier[exact] = keyword[False] ):
literal[string]
keyword[if] ( identifier[fraction] > literal[int] keyword[or] identifier[fraction] < literal[int] ):
keyword[rais... | def random_split(self, fraction, seed=None, exact=False):
"""
Randomly split the rows of an SFrame into two SFrames. The first SFrame
contains *M* rows, sampled uniformly (without replacement) from the
original SFrame. *M* is approximately the fraction times the original
number of ro... |
def decompile(input_, file_, output, format_, jar, limit, decompiler):
"""
Decompile an APK and create Control Flow Graphs.
Example:
\b
$ androguard resources.arsc
"""
from androguard import session
if file_ and input_:
print("Can not give --input and positional argument! "... | def function[decompile, parameter[input_, file_, output, format_, jar, limit, decompiler]]:
constant[
Decompile an APK and create Control Flow Graphs.
Example:
$ androguard resources.arsc
]
from relative_module[androguard] import module[session]
if <ast.BoolOp object at 0... | keyword[def] identifier[decompile] ( identifier[input_] , identifier[file_] , identifier[output] , identifier[format_] , identifier[jar] , identifier[limit] , identifier[decompiler] ):
literal[string]
keyword[from] identifier[androguard] keyword[import] identifier[session]
keyword[if] identifier[... | def decompile(input_, file_, output, format_, jar, limit, decompiler):
"""
Decompile an APK and create Control Flow Graphs.
Example:
\x08
$ androguard resources.arsc
"""
from androguard import session
if file_ and input_:
print('Can not give --input and positional argument!... |
def cget(self, item):
"""Return the value of an option"""
return getattr(self, "_" + item) if item in self.options else ttk.Frame.cget(self, item) | def function[cget, parameter[self, item]]:
constant[Return the value of an option]
return[<ast.IfExp object at 0x7da1b2345330>] | keyword[def] identifier[cget] ( identifier[self] , identifier[item] ):
literal[string]
keyword[return] identifier[getattr] ( identifier[self] , literal[string] + identifier[item] ) keyword[if] identifier[item] keyword[in] identifier[self] . identifier[options] keyword[else] identifier[ttk] . ... | def cget(self, item):
"""Return the value of an option"""
return getattr(self, '_' + item) if item in self.options else ttk.Frame.cget(self, item) |
def to_internal_value(self, data):
"""
Calls super() from DRF, but with an addition.
Creates initial_data and _validated_data for nested
EmbeddedDocumentSerializers, so that recursive_save could make
use of them.
If meets any arbitrary data, not expected by fields,
... | def function[to_internal_value, parameter[self, data]]:
constant[
Calls super() from DRF, but with an addition.
Creates initial_data and _validated_data for nested
EmbeddedDocumentSerializers, so that recursive_save could make
use of them.
If meets any arbitrary data, n... | keyword[def] identifier[to_internal_value] ( identifier[self] , identifier[data] ):
literal[string]
keyword[for] identifier[field] keyword[in] identifier[self] . identifier[_writable_fields] :
keyword[if] identifier[isinstance] ( identifier[field] , identifier[Emb... | def to_internal_value(self, data):
"""
Calls super() from DRF, but with an addition.
Creates initial_data and _validated_data for nested
EmbeddedDocumentSerializers, so that recursive_save could make
use of them.
If meets any arbitrary data, not expected by fields,
... |
def gabc(elem, doc):
"""Handle gabc file inclusion and gabc code block."""
if type(elem) == Code and "gabc" in elem.classes:
if doc.format == "latex":
if elem.identifier == "":
label = ""
else:
label = '\\label{' + elem.identifier + '}'
... | def function[gabc, parameter[elem, doc]]:
constant[Handle gabc file inclusion and gabc code block.]
if <ast.BoolOp object at 0x7da18bc73c40> begin[:]
if compare[name[doc].format equal[==] constant[latex]] begin[:]
if compare[name[elem].identifier equal[==] constan... | keyword[def] identifier[gabc] ( identifier[elem] , identifier[doc] ):
literal[string]
keyword[if] identifier[type] ( identifier[elem] )== identifier[Code] keyword[and] literal[string] keyword[in] identifier[elem] . identifier[classes] :
keyword[if] identifier[doc] . identifier[format] == lit... | def gabc(elem, doc):
"""Handle gabc file inclusion and gabc code block."""
if type(elem) == Code and 'gabc' in elem.classes:
if doc.format == 'latex':
if elem.identifier == '':
label = '' # depends on [control=['if'], data=[]]
else:
label = '\\lab... |
def size(array):
"""
Return a human-readable description of the number of bytes required
to store the data of the given array.
For example::
>>> array.nbytes
14000000
>> biggus.size(array)
'13.35 MiB'
Parameters
----------
array : array-like object
... | def function[size, parameter[array]]:
constant[
Return a human-readable description of the number of bytes required
to store the data of the given array.
For example::
>>> array.nbytes
14000000
>> biggus.size(array)
'13.35 MiB'
Parameters
----------
arr... | keyword[def] identifier[size] ( identifier[array] ):
literal[string]
identifier[nbytes] = identifier[array] . identifier[nbytes]
keyword[if] identifier[nbytes] <( literal[int] << literal[int] ):
identifier[size] = literal[string] . identifier[format] ( identifier[nbytes] )
keyword[elif... | def size(array):
"""
Return a human-readable description of the number of bytes required
to store the data of the given array.
For example::
>>> array.nbytes
14000000
>> biggus.size(array)
'13.35 MiB'
Parameters
----------
array : array-like object
... |
def _get_aws_variables(self):
"""
Returns the AWS specific environment variables that should be available in the Lambda runtime.
They are prefixed it "AWS_*".
:return dict: Name and value of AWS environment variable
"""
result = {
# Variable that says this f... | def function[_get_aws_variables, parameter[self]]:
constant[
Returns the AWS specific environment variables that should be available in the Lambda runtime.
They are prefixed it "AWS_*".
:return dict: Name and value of AWS environment variable
]
variable[result] assign[=]... | keyword[def] identifier[_get_aws_variables] ( identifier[self] ):
literal[string]
identifier[result] ={
literal[string] : literal[string] ,
literal[string] : identifier[str] ( identifier[self] . identifier[memory] ),
literal[string] : identifier[str] (... | def _get_aws_variables(self):
"""
Returns the AWS specific environment variables that should be available in the Lambda runtime.
They are prefixed it "AWS_*".
:return dict: Name and value of AWS environment variable
"""
# Variable that says this function is running in Local Lamb... |
def get_command(namespace):
"""
Get the pylint command for these arguments.
:param `Namespace` namespace: the namespace
"""
cmd = ["pylint", namespace.package] + arg_map[namespace.package]
if namespace.ignore:
cmd.append("--ignore=%s" % namespace.ignore)
return cmd | def function[get_command, parameter[namespace]]:
constant[
Get the pylint command for these arguments.
:param `Namespace` namespace: the namespace
]
variable[cmd] assign[=] binary_operation[list[[<ast.Constant object at 0x7da18f722bc0>, <ast.Attribute object at 0x7da18f722950>]] + call[name... | keyword[def] identifier[get_command] ( identifier[namespace] ):
literal[string]
identifier[cmd] =[ literal[string] , identifier[namespace] . identifier[package] ]+ identifier[arg_map] [ identifier[namespace] . identifier[package] ]
keyword[if] identifier[namespace] . identifier[ignore] :
ide... | def get_command(namespace):
"""
Get the pylint command for these arguments.
:param `Namespace` namespace: the namespace
"""
cmd = ['pylint', namespace.package] + arg_map[namespace.package]
if namespace.ignore:
cmd.append('--ignore=%s' % namespace.ignore) # depends on [control=['if'], d... |
def update_ports_tree(ports_tree):
'''
Updates the ports tree, either the default or the `ports_tree` specified
CLI Example:
.. code-block:: bash
salt '*' poudriere.update_ports_tree staging
'''
_check_config_exists()
if ports_tree:
cmd = 'poudriere ports -u -p {0}'.format... | def function[update_ports_tree, parameter[ports_tree]]:
constant[
Updates the ports tree, either the default or the `ports_tree` specified
CLI Example:
.. code-block:: bash
salt '*' poudriere.update_ports_tree staging
]
call[name[_check_config_exists], parameter[]]
if ... | keyword[def] identifier[update_ports_tree] ( identifier[ports_tree] ):
literal[string]
identifier[_check_config_exists] ()
keyword[if] identifier[ports_tree] :
identifier[cmd] = literal[string] . identifier[format] ( identifier[ports_tree] )
keyword[else] :
identifier[cmd] = li... | def update_ports_tree(ports_tree):
"""
Updates the ports tree, either the default or the `ports_tree` specified
CLI Example:
.. code-block:: bash
salt '*' poudriere.update_ports_tree staging
"""
_check_config_exists()
if ports_tree:
cmd = 'poudriere ports -u -p {0}'.format... |
def fmt_subst(regex, subst):
"""Replace regex with string."""
return lambda text: re.sub(regex, subst, text) if text else text | def function[fmt_subst, parameter[regex, subst]]:
constant[Replace regex with string.]
return[<ast.Lambda object at 0x7da1b13e8b20>] | keyword[def] identifier[fmt_subst] ( identifier[regex] , identifier[subst] ):
literal[string]
keyword[return] keyword[lambda] identifier[text] : identifier[re] . identifier[sub] ( identifier[regex] , identifier[subst] , identifier[text] ) keyword[if] identifier[text] keyword[else] identifier[text] | def fmt_subst(regex, subst):
"""Replace regex with string."""
return lambda text: re.sub(regex, subst, text) if text else text |
def MapFile(self, key_path_prefix, registry_file):
"""Maps the Windows Registry file to a specific key path prefix.
Args:
key_path_prefix (str): key path prefix.
registry_file (WinRegistryFile): Windows Registry file.
"""
self._registry_files[key_path_prefix.upper()] = registry_file
reg... | def function[MapFile, parameter[self, key_path_prefix, registry_file]]:
constant[Maps the Windows Registry file to a specific key path prefix.
Args:
key_path_prefix (str): key path prefix.
registry_file (WinRegistryFile): Windows Registry file.
]
call[name[self]._registry_files][cal... | keyword[def] identifier[MapFile] ( identifier[self] , identifier[key_path_prefix] , identifier[registry_file] ):
literal[string]
identifier[self] . identifier[_registry_files] [ identifier[key_path_prefix] . identifier[upper] ()]= identifier[registry_file]
identifier[registry_file] . identifier[SetKe... | def MapFile(self, key_path_prefix, registry_file):
"""Maps the Windows Registry file to a specific key path prefix.
Args:
key_path_prefix (str): key path prefix.
registry_file (WinRegistryFile): Windows Registry file.
"""
self._registry_files[key_path_prefix.upper()] = registry_file
reg... |
def modflow_hob_to_instruction_file(hob_file):
"""write an instruction file for a modflow head observation file
Parameters
----------
hob_file : str
modflow hob file
Returns
-------
df : pandas.DataFrame
pandas DataFrame with control file observation information
"""
... | def function[modflow_hob_to_instruction_file, parameter[hob_file]]:
constant[write an instruction file for a modflow head observation file
Parameters
----------
hob_file : str
modflow hob file
Returns
-------
df : pandas.DataFrame
pandas DataFrame with control file obse... | keyword[def] identifier[modflow_hob_to_instruction_file] ( identifier[hob_file] ):
literal[string]
identifier[hob_df] = identifier[pd] . identifier[read_csv] ( identifier[hob_file] , identifier[delim_whitespace] = keyword[True] , identifier[skiprows] = literal[int] ,
identifier[header] = keyword[None... | def modflow_hob_to_instruction_file(hob_file):
"""write an instruction file for a modflow head observation file
Parameters
----------
hob_file : str
modflow hob file
Returns
-------
df : pandas.DataFrame
pandas DataFrame with control file observation information
"""
... |
def registry_path(cls, project, location, registry):
"""Return a fully-qualified registry string."""
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/registries/{registry}",
project=project,
location=location,
registry=... | def function[registry_path, parameter[cls, project, location, registry]]:
constant[Return a fully-qualified registry string.]
return[call[name[google].api_core.path_template.expand, parameter[constant[projects/{project}/locations/{location}/registries/{registry}]]]] | keyword[def] identifier[registry_path] ( identifier[cls] , identifier[project] , identifier[location] , identifier[registry] ):
literal[string]
keyword[return] identifier[google] . identifier[api_core] . identifier[path_template] . identifier[expand] (
literal[string] ,
identifie... | def registry_path(cls, project, location, registry):
"""Return a fully-qualified registry string."""
return google.api_core.path_template.expand('projects/{project}/locations/{location}/registries/{registry}', project=project, location=location, registry=registry) |
def prepare_outdir(outdir):
"""
Creates the output directory if not existing.
If outdir is None or if no output_files are provided nothing happens.
:param outdir: The output directory to create.
"""
if outdir:
outdir = os.path.expanduser(outdir)
if not os.path.isdir(outdir):
... | def function[prepare_outdir, parameter[outdir]]:
constant[
Creates the output directory if not existing.
If outdir is None or if no output_files are provided nothing happens.
:param outdir: The output directory to create.
]
if name[outdir] begin[:]
variable[outdir] assig... | keyword[def] identifier[prepare_outdir] ( identifier[outdir] ):
literal[string]
keyword[if] identifier[outdir] :
identifier[outdir] = identifier[os] . identifier[path] . identifier[expanduser] ( identifier[outdir] )
keyword[if] keyword[not] identifier[os] . identifier[path] . identifie... | def prepare_outdir(outdir):
"""
Creates the output directory if not existing.
If outdir is None or if no output_files are provided nothing happens.
:param outdir: The output directory to create.
"""
if outdir:
outdir = os.path.expanduser(outdir)
if not os.path.isdir(outdir):
... |
def encipher(self,string):
"""Encipher string using Porta cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = Porta('HELLO').encipher(plaintext)
:param string: The string to encipher.
:retur... | def function[encipher, parameter[self, string]]:
constant[Encipher string using Porta cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = Porta('HELLO').encipher(plaintext)
:param string: The string... | keyword[def] identifier[encipher] ( identifier[self] , identifier[string] ):
literal[string]
identifier[string] = identifier[self] . identifier[remove_punctuation] ( identifier[string] )
identifier[ret] = literal[string]
keyword[for] ( identifier[i] , identifier[c] ) keyword[in] ... | def encipher(self, string):
"""Encipher string using Porta cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = Porta('HELLO').encipher(plaintext)
:param string: The string to encipher.
:returns:... |
def vertex_fingerprints(self):
"""A fingerprint for each vertex
The result is invariant under permutation of the vertex indexes.
Vertices that are symmetrically equivalent will get the same
fingerprint, e.g. the hydrogens in methane would get the same
fingerprint.
... | def function[vertex_fingerprints, parameter[self]]:
constant[A fingerprint for each vertex
The result is invariant under permutation of the vertex indexes.
Vertices that are symmetrically equivalent will get the same
fingerprint, e.g. the hydrogens in methane would get the same... | keyword[def] identifier[vertex_fingerprints] ( identifier[self] ):
literal[string]
keyword[return] identifier[self] . identifier[get_vertex_fingerprints] (
[ identifier[self] . identifier[get_vertex_string] ( identifier[i] ) keyword[for] identifier[i] keyword[in] identifier[range] ( ide... | def vertex_fingerprints(self):
"""A fingerprint for each vertex
The result is invariant under permutation of the vertex indexes.
Vertices that are symmetrically equivalent will get the same
fingerprint, e.g. the hydrogens in methane would get the same
fingerprint.
... |
def netflix(es, ps, e0, l=.0001):
"""
Combine predictions with the optimal weights to minimize RMSE.
Args:
es (list of float): RMSEs of predictions
ps (list of np.array): predictions
e0 (float): RMSE of all zero prediction
l (float): lambda as in the ridge regression
Re... | def function[netflix, parameter[es, ps, e0, l]]:
constant[
Combine predictions with the optimal weights to minimize RMSE.
Args:
es (list of float): RMSEs of predictions
ps (list of np.array): predictions
e0 (float): RMSE of all zero prediction
l (float): lambda as in the... | keyword[def] identifier[netflix] ( identifier[es] , identifier[ps] , identifier[e0] , identifier[l] = literal[int] ):
literal[string]
identifier[m] = identifier[len] ( identifier[es] )
identifier[n] = identifier[len] ( identifier[ps] [ literal[int] ])
identifier[X] = identifier[np] . identifier[... | def netflix(es, ps, e0, l=0.0001):
"""
Combine predictions with the optimal weights to minimize RMSE.
Args:
es (list of float): RMSEs of predictions
ps (list of np.array): predictions
e0 (float): RMSE of all zero prediction
l (float): lambda as in the ridge regression
R... |
def get_substring_idxs(substr, string):
"""
Return a list of indexes of substr. If substr not found, list is
empty.
Arguments:
substr (str): Substring to match.
string (str): String to match in.
Returns:
list of int: Start indices of substr.
"""
return [match.start(... | def function[get_substring_idxs, parameter[substr, string]]:
constant[
Return a list of indexes of substr. If substr not found, list is
empty.
Arguments:
substr (str): Substring to match.
string (str): String to match in.
Returns:
list of int: Start indices of substr.
... | keyword[def] identifier[get_substring_idxs] ( identifier[substr] , identifier[string] ):
literal[string]
keyword[return] [ identifier[match] . identifier[start] () keyword[for] identifier[match] keyword[in] identifier[re] . identifier[finditer] ( identifier[substr] , identifier[string] )] | def get_substring_idxs(substr, string):
"""
Return a list of indexes of substr. If substr not found, list is
empty.
Arguments:
substr (str): Substring to match.
string (str): String to match in.
Returns:
list of int: Start indices of substr.
"""
return [match.start(... |
def simulate(self, T):
"""Simulate state and observation processes.
Parameters
----------
T: int
processes are simulated from time 0 to time T-1
Returns
-------
x, y: lists
lists of length T
"""
x = []
for t in ra... | def function[simulate, parameter[self, T]]:
constant[Simulate state and observation processes.
Parameters
----------
T: int
processes are simulated from time 0 to time T-1
Returns
-------
x, y: lists
lists of length T
]
v... | keyword[def] identifier[simulate] ( identifier[self] , identifier[T] ):
literal[string]
identifier[x] =[]
keyword[for] identifier[t] keyword[in] identifier[range] ( identifier[T] ):
identifier[law_x] = identifier[self] . identifier[PX0] () keyword[if] identifier[t] == lite... | def simulate(self, T):
"""Simulate state and observation processes.
Parameters
----------
T: int
processes are simulated from time 0 to time T-1
Returns
-------
x, y: lists
lists of length T
"""
x = []
for t in range(T):
... |
def format_symbol(self, symbol, link_resolver):
"""
Format a symbols.Symbol
"""
if not symbol:
return ''
if isinstance(symbol, FieldSymbol):
return ''
# pylint: disable=unused-variable
out = self._format_symbol(symbol)
template = ... | def function[format_symbol, parameter[self, symbol, link_resolver]]:
constant[
Format a symbols.Symbol
]
if <ast.UnaryOp object at 0x7da18f00eef0> begin[:]
return[constant[]]
if call[name[isinstance], parameter[name[symbol], name[FieldSymbol]]] begin[:]
return[con... | keyword[def] identifier[format_symbol] ( identifier[self] , identifier[symbol] , identifier[link_resolver] ):
literal[string]
keyword[if] keyword[not] identifier[symbol] :
keyword[return] literal[string]
keyword[if] identifier[isinstance] ( identifier[symbol] , identifie... | def format_symbol(self, symbol, link_resolver):
"""
Format a symbols.Symbol
"""
if not symbol:
return '' # depends on [control=['if'], data=[]]
if isinstance(symbol, FieldSymbol):
return '' # depends on [control=['if'], data=[]]
# pylint: disable=unused-variable
out... |
def albedo(self, value=999.0):
"""Corresponds to IDD Field `albedo`
Args:
value (float): value for IDD Field `albedo`
Missing value: 999.0
if `value` is None it will not be checked against the
specification and is assumed to be a missing value... | def function[albedo, parameter[self, value]]:
constant[Corresponds to IDD Field `albedo`
Args:
value (float): value for IDD Field `albedo`
Missing value: 999.0
if `value` is None it will not be checked against the
specification and is assumed ... | keyword[def] identifier[albedo] ( identifier[self] , identifier[value] = literal[int] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[not] keyword[None] :
keyword[try] :
identifier[value] = identifier[float] ( identifier[value] )
k... | def albedo(self, value=999.0):
"""Corresponds to IDD Field `albedo`
Args:
value (float): value for IDD Field `albedo`
Missing value: 999.0
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
... |
def resolve_inline_message_id(inline_msg_id):
"""
Resolves an inline message ID. Returns a tuple of
``(message id, peer, dc id, access hash)``
The ``peer`` may either be a :tl:`PeerUser` referencing
the user who sent the message via the bot in a private
conversation or small group chat, or a :t... | def function[resolve_inline_message_id, parameter[inline_msg_id]]:
constant[
Resolves an inline message ID. Returns a tuple of
``(message id, peer, dc id, access hash)``
The ``peer`` may either be a :tl:`PeerUser` referencing
the user who sent the message via the bot in a private
conversati... | keyword[def] identifier[resolve_inline_message_id] ( identifier[inline_msg_id] ):
literal[string]
keyword[try] :
identifier[dc_id] , identifier[message_id] , identifier[pid] , identifier[access_hash] = identifier[struct] . identifier[unpack] ( literal[string] , identifier[_decode_telegram_base64] ... | def resolve_inline_message_id(inline_msg_id):
"""
Resolves an inline message ID. Returns a tuple of
``(message id, peer, dc id, access hash)``
The ``peer`` may either be a :tl:`PeerUser` referencing
the user who sent the message via the bot in a private
conversation or small group chat, or a :t... |
def load_raw_arrays(self, fields, start_dt, end_dt, sids):
"""
Parameters
----------
fields : list of str
'open', 'high', 'low', 'close', or 'volume'
start_dt: Timestamp
Beginning of the window range.
end_dt: Timestamp
End of the window ra... | def function[load_raw_arrays, parameter[self, fields, start_dt, end_dt, sids]]:
constant[
Parameters
----------
fields : list of str
'open', 'high', 'low', 'close', or 'volume'
start_dt: Timestamp
Beginning of the window range.
end_dt: Timestamp
... | keyword[def] identifier[load_raw_arrays] ( identifier[self] , identifier[fields] , identifier[start_dt] , identifier[end_dt] , identifier[sids] ):
literal[string]
identifier[start_idx] = identifier[self] . identifier[_find_position_of_minute] ( identifier[start_dt] )
identifier[end_idx] = ... | def load_raw_arrays(self, fields, start_dt, end_dt, sids):
"""
Parameters
----------
fields : list of str
'open', 'high', 'low', 'close', or 'volume'
start_dt: Timestamp
Beginning of the window range.
end_dt: Timestamp
End of the window range.... |
def _parse_player(self, index, attributes, postgame, game_type):
"""Parse a player."""
try:
voobly_user = voobly.user(self._voobly_session, attributes.player_name,
ladder_ids=VOOBLY_LADDERS.values())
voobly_ladder = '{} {}'.format(game_type, ... | def function[_parse_player, parameter[self, index, attributes, postgame, game_type]]:
constant[Parse a player.]
<ast.Try object at 0x7da1b25efd60>
variable[player] assign[=] dictionary[[<ast.Constant object at 0x7da1b25ef1c0>, <ast.Constant object at 0x7da1b25ef190>, <ast.Constant object at 0x7da1b2... | keyword[def] identifier[_parse_player] ( identifier[self] , identifier[index] , identifier[attributes] , identifier[postgame] , identifier[game_type] ):
literal[string]
keyword[try] :
identifier[voobly_user] = identifier[voobly] . identifier[user] ( identifier[self] . identifier[_voobl... | def _parse_player(self, index, attributes, postgame, game_type):
"""Parse a player."""
try:
voobly_user = voobly.user(self._voobly_session, attributes.player_name, ladder_ids=VOOBLY_LADDERS.values())
voobly_ladder = '{} {}'.format(game_type, self._diplomacy['type'])
voobly_ladder_id = VO... |
def run(self, context):
"""We have to overwrite this method because we don't want an implicit context
"""
args = []
kwargs = {}
for arg in self.explicit_arguments:
if arg.name is not None:
kwargs[arg.name] = arg.value
else:
... | def function[run, parameter[self, context]]:
constant[We have to overwrite this method because we don't want an implicit context
]
variable[args] assign[=] list[[]]
variable[kwargs] assign[=] dictionary[[], []]
for taget[name[arg]] in starred[name[self].explicit_arguments] begin[... | keyword[def] identifier[run] ( identifier[self] , identifier[context] ):
literal[string]
identifier[args] =[]
identifier[kwargs] ={}
keyword[for] identifier[arg] keyword[in] identifier[self] . identifier[explicit_arguments] :
keyword[if] identifier[arg] . identif... | def run(self, context):
"""We have to overwrite this method because we don't want an implicit context
"""
args = []
kwargs = {}
for arg in self.explicit_arguments:
if arg.name is not None:
kwargs[arg.name] = arg.value # depends on [control=['if'], data=[]]
else:
... |
def find_elements_by_id(self, id_):
"""
Finds multiple elements by id.
:Args:
- id\\_ - The id of the elements to be found.
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
... | def function[find_elements_by_id, parameter[self, id_]]:
constant[
Finds multiple elements by id.
:Args:
- id\_ - The id of the elements to be found.
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usa... | keyword[def] identifier[find_elements_by_id] ( identifier[self] , identifier[id_] ):
literal[string]
keyword[return] identifier[self] . identifier[find_elements] ( identifier[by] = identifier[By] . identifier[ID] , identifier[value] = identifier[id_] ) | def find_elements_by_id(self, id_):
"""
Finds multiple elements by id.
:Args:
- id\\_ - The id of the elements to be found.
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
... |
def _Supercooled(T, P):
"""Guideline on thermodynamic properties of supercooled water
Parameters
----------
T : float
Temperature, [K]
P : float
Pressure, [MPa]
Returns
-------
prop : dict
Dict with calculated properties of water. The available properties are:
... | def function[_Supercooled, parameter[T, P]]:
constant[Guideline on thermodynamic properties of supercooled water
Parameters
----------
T : float
Temperature, [K]
P : float
Pressure, [MPa]
Returns
-------
prop : dict
Dict with calculated properties of water. ... | keyword[def] identifier[_Supercooled] ( identifier[T] , identifier[P] ):
literal[string]
keyword[if] identifier[P] < literal[int] :
identifier[Tita] = identifier[T] / literal[int]
identifier[Ph] = literal[int] + literal[int] *( literal[int] - identifier[Tita] ** literal[int] )+ li... | def _Supercooled(T, P):
"""Guideline on thermodynamic properties of supercooled water
Parameters
----------
T : float
Temperature, [K]
P : float
Pressure, [MPa]
Returns
-------
prop : dict
Dict with calculated properties of water. The available properties are:
... |
def stop_instance(self, instance_id):
"""Stops the instance gracefully.
:param str instance_id: instance identifier
"""
instance = self._load_instance(instance_id)
instance.terminate()
del self._instances[instance_id] | def function[stop_instance, parameter[self, instance_id]]:
constant[Stops the instance gracefully.
:param str instance_id: instance identifier
]
variable[instance] assign[=] call[name[self]._load_instance, parameter[name[instance_id]]]
call[name[instance].terminate, parameter[]]... | keyword[def] identifier[stop_instance] ( identifier[self] , identifier[instance_id] ):
literal[string]
identifier[instance] = identifier[self] . identifier[_load_instance] ( identifier[instance_id] )
identifier[instance] . identifier[terminate] ()
keyword[del] identifier[self] . ... | def stop_instance(self, instance_id):
"""Stops the instance gracefully.
:param str instance_id: instance identifier
"""
instance = self._load_instance(instance_id)
instance.terminate()
del self._instances[instance_id] |
def timeFormat(time_from, time_to=None, prefix="", infix=None):
"""
Format the times time_from and optionally time_to, e.g. 10am
"""
retval = ""
if time_from != "" and time_from is not None:
retval += prefix
retval += dateformat.time_format(time_from, "fA").lower()
if time_to != ... | def function[timeFormat, parameter[time_from, time_to, prefix, infix]]:
constant[
Format the times time_from and optionally time_to, e.g. 10am
]
variable[retval] assign[=] constant[]
if <ast.BoolOp object at 0x7da204620c70> begin[:]
<ast.AugAssign object at 0x7da204623c40>
... | keyword[def] identifier[timeFormat] ( identifier[time_from] , identifier[time_to] = keyword[None] , identifier[prefix] = literal[string] , identifier[infix] = keyword[None] ):
literal[string]
identifier[retval] = literal[string]
keyword[if] identifier[time_from] != literal[string] keyword[and] ide... | def timeFormat(time_from, time_to=None, prefix='', infix=None):
"""
Format the times time_from and optionally time_to, e.g. 10am
"""
retval = ''
if time_from != '' and time_from is not None:
retval += prefix
retval += dateformat.time_format(time_from, 'fA').lower() # depends on [con... |
def reset(self):
'''Restores the starting position.'''
self.piece_bb = [
BB_VOID, # NONE
BB_RANK_C | BB_RANK_G, # PAWN
BB_A1 | BB_I1 | BB_A9 | BB_I9, # LANCE
BB_A2 | BB_A8 | BB_I2 | BB_I8, # KNIGHT
... | def function[reset, parameter[self]]:
constant[Restores the starting position.]
name[self].piece_bb assign[=] list[[<ast.Name object at 0x7da1b03fb0a0>, <ast.BinOp object at 0x7da1b03fab60>, <ast.BinOp object at 0x7da1b03f9fc0>, <ast.BinOp object at 0x7da1b03fa1d0>, <ast.BinOp object at 0x7da1b03fb4c0>,... | keyword[def] identifier[reset] ( identifier[self] ):
literal[string]
identifier[self] . identifier[piece_bb] =[
identifier[BB_VOID] ,
identifier[BB_RANK_C] | identifier[BB_RANK_G] ,
identifier[BB_A1] | identifier[BB_I1] | identifier[BB_A9] | identifier[BB_I9] ,
i... | def reset(self):
"""Restores the starting position.""" # NONE
# PAWN
# LANCE
# KNIGHT
# SILVER
# GOLD
# BISHOP
# ROOK
# KING
# PROM_PAWN
# PROM_LANCE
# PROM_KNIGHT
# PROM_SILVER
# PROM_BISHOP
# PROM_ROOK
self.piece_bb = [BB_VOID, BB_RANK_C | BB_RANK_G, BB... |
def line_ribbon(self):
'''Display the protein secondary structure as a white lines that passes through the
backbone chain.
'''
# Control points are the CA (C alphas)
backbone = np.array(self.topology['atom_names']) == 'CA'
smoothline = self.add_representation('smoothl... | def function[line_ribbon, parameter[self]]:
constant[Display the protein secondary structure as a white lines that passes through the
backbone chain.
]
variable[backbone] assign[=] compare[call[name[np].array, parameter[call[name[self].topology][constant[atom_names]]]] equal[==] cons... | keyword[def] identifier[line_ribbon] ( identifier[self] ):
literal[string]
identifier[backbone] = identifier[np] . identifier[array] ( identifier[self] . identifier[topology] [ literal[string] ])== literal[string]
identifier[smoothline] = identifier[self] . identifier[add_represe... | def line_ribbon(self):
"""Display the protein secondary structure as a white lines that passes through the
backbone chain.
"""
# Control points are the CA (C alphas)
backbone = np.array(self.topology['atom_names']) == 'CA'
smoothline = self.add_representation('smoothline', {'coordina... |
def _fix_dependendent_params(self, i):
"""Unhide keys if necessary after removing the param at index *i*."""
if not self.params[i].showkey:
for param in self.params[i + 1:]:
if not param.showkey:
param.showkey = True | def function[_fix_dependendent_params, parameter[self, i]]:
constant[Unhide keys if necessary after removing the param at index *i*.]
if <ast.UnaryOp object at 0x7da20cabf430> begin[:]
for taget[name[param]] in starred[call[name[self].params][<ast.Slice object at 0x7da20cabee60>]] begin[... | keyword[def] identifier[_fix_dependendent_params] ( identifier[self] , identifier[i] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[params] [ identifier[i] ]. identifier[showkey] :
keyword[for] identifier[param] keyword[in] identifier[self] . identifier[... | def _fix_dependendent_params(self, i):
"""Unhide keys if necessary after removing the param at index *i*."""
if not self.params[i].showkey:
for param in self.params[i + 1:]:
if not param.showkey:
param.showkey = True # depends on [control=['if'], data=[]] # depends on [cont... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.