code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _evaluate(self,R,phi=0.,t=0.):
"""
NAME:
_evaluate
PURPOSE:
evaluate the potential at R,phi,t
INPUT:
R - Galactocentric cylindrical radius
phi - azimuth
t - time
OUTPUT:
Phi(R,phi,t)
HISTORY:
... | def function[_evaluate, parameter[self, R, phi, t]]:
constant[
NAME:
_evaluate
PURPOSE:
evaluate the potential at R,phi,t
INPUT:
R - Galactocentric cylindrical radius
phi - azimuth
t - time
OUTPUT:
Phi(R,phi,t)
... | keyword[def] identifier[_evaluate] ( identifier[self] , identifier[R] , identifier[phi] = literal[int] , identifier[t] = literal[int] ):
literal[string]
keyword[return] identifier[self] . identifier[_A] * identifier[math] . identifier[exp] (-( identifier[t] - identifier[self] . identifier[_to] )**... | def _evaluate(self, R, phi=0.0, t=0.0):
"""
NAME:
_evaluate
PURPOSE:
evaluate the potential at R,phi,t
INPUT:
R - Galactocentric cylindrical radius
phi - azimuth
t - time
OUTPUT:
Phi(R,phi,t)
HISTORY:
... |
def get_content(self, content_type=None, space_key=None, title=None, status=None, posting_day=None,
expand=None, start=None, limit=None, callback=None):
"""
Returns a paginated list of Content.
:param content_type (string): OPTIONAL: The content type to return. Default value:... | def function[get_content, parameter[self, content_type, space_key, title, status, posting_day, expand, start, limit, callback]]:
constant[
Returns a paginated list of Content.
:param content_type (string): OPTIONAL: The content type to return. Default value: "page".
... | keyword[def] identifier[get_content] ( identifier[self] , identifier[content_type] = keyword[None] , identifier[space_key] = keyword[None] , identifier[title] = keyword[None] , identifier[status] = keyword[None] , identifier[posting_day] = keyword[None] ,
identifier[expand] = keyword[None] , identifier[start] = keyw... | def get_content(self, content_type=None, space_key=None, title=None, status=None, posting_day=None, expand=None, start=None, limit=None, callback=None):
"""
Returns a paginated list of Content.
:param content_type (string): OPTIONAL: The content type to return. Default value: "page".
... |
def keep_color(ax=None):
''' Keep the same color for the same graph.
Warning: due to the structure of Python iterators I couldn't help but
iterate over all the cycle twice. One first time to get the number of elements
in the cycle, one second time to stop just before the last. And this still
only ... | def function[keep_color, parameter[ax]]:
constant[ Keep the same color for the same graph.
Warning: due to the structure of Python iterators I couldn't help but
iterate over all the cycle twice. One first time to get the number of elements
in the cycle, one second time to stop just before the last.... | keyword[def] identifier[keep_color] ( identifier[ax] = keyword[None] ):
literal[string]
keyword[if] identifier[ax] keyword[is] keyword[None] :
identifier[ax] = identifier[mpl] . identifier[pyplot] . identifier[gca] ()
identifier[i] = literal[int]
identifier[cycle] = identifier[ax] ... | def keep_color(ax=None):
""" Keep the same color for the same graph.
Warning: due to the structure of Python iterators I couldn't help but
iterate over all the cycle twice. One first time to get the number of elements
in the cycle, one second time to stop just before the last. And this still
only ... |
def from_buffer(buffer, mime=False):
"""
Accepts a binary string and returns the detected filetype. Return
value is the mimetype if mime=True, otherwise a human readable
name.
>>> magic.from_buffer(open("testdata/test.pdf").read(1024))
'PDF document, version 1.2'
"""
m = _get_magic_typ... | def function[from_buffer, parameter[buffer, mime]]:
constant[
Accepts a binary string and returns the detected filetype. Return
value is the mimetype if mime=True, otherwise a human readable
name.
>>> magic.from_buffer(open("testdata/test.pdf").read(1024))
'PDF document, version 1.2'
]... | keyword[def] identifier[from_buffer] ( identifier[buffer] , identifier[mime] = keyword[False] ):
literal[string]
identifier[m] = identifier[_get_magic_type] ( identifier[mime] )
keyword[return] identifier[m] . identifier[from_buffer] ( identifier[buffer] ) | def from_buffer(buffer, mime=False):
"""
Accepts a binary string and returns the detected filetype. Return
value is the mimetype if mime=True, otherwise a human readable
name.
>>> magic.from_buffer(open("testdata/test.pdf").read(1024))
'PDF document, version 1.2'
"""
m = _get_magic_typ... |
def getExperimentDescriptionInterfaceFromModule(module):
"""
:param module: imported description.py module
:returns: (:class:`nupic.frameworks.opf.exp_description_api.DescriptionIface`)
represents the experiment description
"""
result = module.descriptionInterface
assert isinstance(result, exp_... | def function[getExperimentDescriptionInterfaceFromModule, parameter[module]]:
constant[
:param module: imported description.py module
:returns: (:class:`nupic.frameworks.opf.exp_description_api.DescriptionIface`)
represents the experiment description
]
variable[result] assign[=] name[... | keyword[def] identifier[getExperimentDescriptionInterfaceFromModule] ( identifier[module] ):
literal[string]
identifier[result] = identifier[module] . identifier[descriptionInterface]
keyword[assert] identifier[isinstance] ( identifier[result] , identifier[exp_description_api] . identifier[DescriptionIfac... | def getExperimentDescriptionInterfaceFromModule(module):
"""
:param module: imported description.py module
:returns: (:class:`nupic.frameworks.opf.exp_description_api.DescriptionIface`)
represents the experiment description
"""
result = module.descriptionInterface
assert isinstance(result... |
def get_parent_object(self, parent_queryset=None):
"""
Returns the parent object the view is displaying.
You may want to override this if you need to provide non-standard
queryset lookups. Eg if parent objects are referenced using multiple
keyword arguments in the url conf.
... | def function[get_parent_object, parameter[self, parent_queryset]]:
constant[
Returns the parent object the view is displaying.
You may want to override this if you need to provide non-standard
queryset lookups. Eg if parent objects are referenced using multiple
keyword arguments... | keyword[def] identifier[get_parent_object] ( identifier[self] , identifier[parent_queryset] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[_parent_object_cache] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[self] . identifier[_pa... | def get_parent_object(self, parent_queryset=None):
"""
Returns the parent object the view is displaying.
You may want to override this if you need to provide non-standard
queryset lookups. Eg if parent objects are referenced using multiple
keyword arguments in the url conf.
... |
def union(self, *args):
"""Unions the equivalence classes containing the elements in `*args`."""
if self._readonly:
raise AttributeError
if len(args) == 0:
return None
if len(args) == 1:
return self[args[0]]
for a, b in zip(args[:-1], args[1:]... | def function[union, parameter[self]]:
constant[Unions the equivalence classes containing the elements in `*args`.]
if name[self]._readonly begin[:]
<ast.Raise object at 0x7da18bccb1c0>
if compare[call[name[len], parameter[name[args]]] equal[==] constant[0]] begin[:]
return[consta... | keyword[def] identifier[union] ( identifier[self] ,* identifier[args] ):
literal[string]
keyword[if] identifier[self] . identifier[_readonly] :
keyword[raise] identifier[AttributeError]
keyword[if] identifier[len] ( identifier[args] )== literal[int] :
keyword... | def union(self, *args):
"""Unions the equivalence classes containing the elements in `*args`."""
if self._readonly:
raise AttributeError # depends on [control=['if'], data=[]]
if len(args) == 0:
return None # depends on [control=['if'], data=[]]
if len(args) == 1:
return self[a... |
def docker_to_uuid(uuid):
'''
Get the image uuid from an imported docker image
.. versionadded:: 2019.2.0
'''
if _is_uuid(uuid):
return uuid
if _is_docker_uuid(uuid):
images = list_installed(verbose=True)
for image_uuid in images:
if 'name' not in images[imag... | def function[docker_to_uuid, parameter[uuid]]:
constant[
Get the image uuid from an imported docker image
.. versionadded:: 2019.2.0
]
if call[name[_is_uuid], parameter[name[uuid]]] begin[:]
return[name[uuid]]
if call[name[_is_docker_uuid], parameter[name[uuid]]] begin[:]
... | keyword[def] identifier[docker_to_uuid] ( identifier[uuid] ):
literal[string]
keyword[if] identifier[_is_uuid] ( identifier[uuid] ):
keyword[return] identifier[uuid]
keyword[if] identifier[_is_docker_uuid] ( identifier[uuid] ):
identifier[images] = identifier[list_installed] ( id... | def docker_to_uuid(uuid):
"""
Get the image uuid from an imported docker image
.. versionadded:: 2019.2.0
"""
if _is_uuid(uuid):
return uuid # depends on [control=['if'], data=[]]
if _is_docker_uuid(uuid):
images = list_installed(verbose=True)
for image_uuid in images:
... |
def get_nodes(n=8, exclude=[], loop=None):
'''Get Ukko nodes with the least amount of load.
May return less than *n* nodes if there are not as many nodes available,
the nodes are reserved or the nodes are on the exclude list.
:param int n: Number of Ukko nodes to return.
:param list exclude: Nodes... | def function[get_nodes, parameter[n, exclude, loop]]:
constant[Get Ukko nodes with the least amount of load.
May return less than *n* nodes if there are not as many nodes available,
the nodes are reserved or the nodes are on the exclude list.
:param int n: Number of Ukko nodes to return.
:para... | keyword[def] identifier[get_nodes] ( identifier[n] = literal[int] , identifier[exclude] =[], identifier[loop] = keyword[None] ):
literal[string]
identifier[report] = identifier[_get_ukko_report] ()
identifier[nodes] = identifier[_parse_ukko_report] ( identifier[report] )
identifier[ret] =[]
... | def get_nodes(n=8, exclude=[], loop=None):
"""Get Ukko nodes with the least amount of load.
May return less than *n* nodes if there are not as many nodes available,
the nodes are reserved or the nodes are on the exclude list.
:param int n: Number of Ukko nodes to return.
:param list exclude: Nodes... |
def gep(self, i):
"""
Resolve the type of the i-th element (for getelementptr lookups).
"""
if not isinstance(i.type, IntType):
raise TypeError(i.type)
return self.element | def function[gep, parameter[self, i]]:
constant[
Resolve the type of the i-th element (for getelementptr lookups).
]
if <ast.UnaryOp object at 0x7da1b19ee350> begin[:]
<ast.Raise object at 0x7da1b19ec910>
return[name[self].element] | keyword[def] identifier[gep] ( identifier[self] , identifier[i] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[i] . identifier[type] , identifier[IntType] ):
keyword[raise] identifier[TypeError] ( identifier[i] . identifier[type] )
keyword[r... | def gep(self, i):
"""
Resolve the type of the i-th element (for getelementptr lookups).
"""
if not isinstance(i.type, IntType):
raise TypeError(i.type) # depends on [control=['if'], data=[]]
return self.element |
def _FieldToJsonObject(self, field, value):
"""Converts field value according to Proto3 JSON Specification."""
if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
return self._MessageToJsonObject(value)
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
enum_value = fie... | def function[_FieldToJsonObject, parameter[self, field, value]]:
constant[Converts field value according to Proto3 JSON Specification.]
if compare[name[field].cpp_type equal[==] name[descriptor].FieldDescriptor.CPPTYPE_MESSAGE] begin[:]
return[call[name[self]._MessageToJsonObject, parameter[name... | keyword[def] identifier[_FieldToJsonObject] ( identifier[self] , identifier[field] , identifier[value] ):
literal[string]
keyword[if] identifier[field] . identifier[cpp_type] == identifier[descriptor] . identifier[FieldDescriptor] . identifier[CPPTYPE_MESSAGE] :
keyword[return] identifier[self] . ... | def _FieldToJsonObject(self, field, value):
"""Converts field value according to Proto3 JSON Specification."""
if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
return self._MessageToJsonObject(value) # depends on [control=['if'], data=[]]
elif field.cpp_type == descriptor.FieldDescr... |
def overlap_bbox_and_point(bbox, xp, yp):
"""Given a bbox that contains a given point, return the (x, y) displacement
necessary to make the bbox not overlap the point."""
cx, cy = get_midpoint(bbox)
dir_x = np.sign(cx-xp)
dir_y = np.sign(cy-yp)
if dir_x == -1:
dx = xp - bbox.xmax
e... | def function[overlap_bbox_and_point, parameter[bbox, xp, yp]]:
constant[Given a bbox that contains a given point, return the (x, y) displacement
necessary to make the bbox not overlap the point.]
<ast.Tuple object at 0x7da20e9b2da0> assign[=] call[name[get_midpoint], parameter[name[bbox]]]
v... | keyword[def] identifier[overlap_bbox_and_point] ( identifier[bbox] , identifier[xp] , identifier[yp] ):
literal[string]
identifier[cx] , identifier[cy] = identifier[get_midpoint] ( identifier[bbox] )
identifier[dir_x] = identifier[np] . identifier[sign] ( identifier[cx] - identifier[xp] )
identi... | def overlap_bbox_and_point(bbox, xp, yp):
"""Given a bbox that contains a given point, return the (x, y) displacement
necessary to make the bbox not overlap the point."""
(cx, cy) = get_midpoint(bbox)
dir_x = np.sign(cx - xp)
dir_y = np.sign(cy - yp)
if dir_x == -1:
dx = xp - bbox.xmax ... |
def _process_response(self, response, object_mapping=None):
"""
Attempt to find a ResponseHandler that knows how to process this response.
If no handler can be found, raise an Exception.
"""
try:
pretty_response = response.json()
except ValueError:
... | def function[_process_response, parameter[self, response, object_mapping]]:
constant[
Attempt to find a ResponseHandler that knows how to process this response.
If no handler can be found, raise an Exception.
]
<ast.Try object at 0x7da2047eb070>
for taget[name[handler]] in st... | keyword[def] identifier[_process_response] ( identifier[self] , identifier[response] , identifier[object_mapping] = keyword[None] ):
literal[string]
keyword[try] :
identifier[pretty_response] = identifier[response] . identifier[json] ()
keyword[except] identifier[ValueError] ... | def _process_response(self, response, object_mapping=None):
"""
Attempt to find a ResponseHandler that knows how to process this response.
If no handler can be found, raise an Exception.
"""
try:
pretty_response = response.json() # depends on [control=['try'], data=[]]
excep... |
def _skip_spaces_and_peek(self):
""" Skips all spaces and comments.
:return: The first character that follows the skipped spaces and comments or
None if the end of the json string has been reached.
"""
while 1:
# skipping spaces
self.skip_chars(sel... | def function[_skip_spaces_and_peek, parameter[self]]:
constant[ Skips all spaces and comments.
:return: The first character that follows the skipped spaces and comments or
None if the end of the json string has been reached.
]
while constant[1] begin[:]
ca... | keyword[def] identifier[_skip_spaces_and_peek] ( identifier[self] ):
literal[string]
keyword[while] literal[int] :
identifier[self] . identifier[skip_chars] ( identifier[self] . identifier[end] , keyword[lambda] identifier[x] : identifier[x] keyword[in] identifier[self] . ... | def _skip_spaces_and_peek(self):
""" Skips all spaces and comments.
:return: The first character that follows the skipped spaces and comments or
None if the end of the json string has been reached.
"""
while 1:
# skipping spaces
self.skip_chars(self.end, lambda x:... |
def setup(self):
"""Setup the ShortcutEditor with the provided arguments."""
# Widgets
icon_info = HelperToolButton()
icon_info.setIcon(get_std_icon('MessageBoxInformation'))
layout_icon_info = QVBoxLayout()
layout_icon_info.setContentsMargins(0, 0, 0, 0)
l... | def function[setup, parameter[self]]:
constant[Setup the ShortcutEditor with the provided arguments.]
variable[icon_info] assign[=] call[name[HelperToolButton], parameter[]]
call[name[icon_info].setIcon, parameter[call[name[get_std_icon], parameter[constant[MessageBoxInformation]]]]]
var... | keyword[def] identifier[setup] ( identifier[self] ):
literal[string]
identifier[icon_info] = identifier[HelperToolButton] ()
identifier[icon_info] . identifier[setIcon] ( identifier[get_std_icon] ( literal[string] ))
identifier[layout_icon_info] = identifier[QVBoxLay... | def setup(self):
"""Setup the ShortcutEditor with the provided arguments.""" # Widgets
icon_info = HelperToolButton()
icon_info.setIcon(get_std_icon('MessageBoxInformation'))
layout_icon_info = QVBoxLayout()
layout_icon_info.setContentsMargins(0, 0, 0, 0)
layout_icon_info.setSpacing(0)
layo... |
def typechecked_module(md, force_recursive = False):
"""Works like typechecked, but is only applicable to modules (by explicit call).
md must be a module or a module name contained in sys.modules.
"""
if not pytypes.checking_enabled:
return md
if isinstance(md, str):
if md in sys.mod... | def function[typechecked_module, parameter[md, force_recursive]]:
constant[Works like typechecked, but is only applicable to modules (by explicit call).
md must be a module or a module name contained in sys.modules.
]
if <ast.UnaryOp object at 0x7da18ede4ca0> begin[:]
return[name[md]]
... | keyword[def] identifier[typechecked_module] ( identifier[md] , identifier[force_recursive] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[pytypes] . identifier[checking_enabled] :
keyword[return] identifier[md]
keyword[if] identifier[isinstance] ( identifier[md] ... | def typechecked_module(md, force_recursive=False):
"""Works like typechecked, but is only applicable to modules (by explicit call).
md must be a module or a module name contained in sys.modules.
"""
if not pytypes.checking_enabled:
return md # depends on [control=['if'], data=[]]
if isinsta... |
def draw_final_outputs(img, results):
"""
Args:
results: [DetectionResult]
"""
if len(results) == 0:
return img
# Display in largest to smallest order to reduce occlusion
boxes = np.asarray([r.box for r in results])
areas = np_area(boxes)
sorted_inds = np.argsort(-areas)... | def function[draw_final_outputs, parameter[img, results]]:
constant[
Args:
results: [DetectionResult]
]
if compare[call[name[len], parameter[name[results]]] equal[==] constant[0]] begin[:]
return[name[img]]
variable[boxes] assign[=] call[name[np].asarray, parameter[<ast.L... | keyword[def] identifier[draw_final_outputs] ( identifier[img] , identifier[results] ):
literal[string]
keyword[if] identifier[len] ( identifier[results] )== literal[int] :
keyword[return] identifier[img]
identifier[boxes] = identifier[np] . identifier[asarray] ([ identifier[r] . ... | def draw_final_outputs(img, results):
"""
Args:
results: [DetectionResult]
"""
if len(results) == 0:
return img # depends on [control=['if'], data=[]]
# Display in largest to smallest order to reduce occlusion
boxes = np.asarray([r.box for r in results])
areas = np_area(boxe... |
def bind_parameters(self, value_dict):
"""Assign parameters to values yielding a new circuit.
Args:
value_dict (dict): {parameter: value, ...}
Raises:
QiskitError: If value_dict contains parameters not present in the circuit
Returns:
QuantumCircuit:... | def function[bind_parameters, parameter[self, value_dict]]:
constant[Assign parameters to values yielding a new circuit.
Args:
value_dict (dict): {parameter: value, ...}
Raises:
QiskitError: If value_dict contains parameters not present in the circuit
Returns:
... | keyword[def] identifier[bind_parameters] ( identifier[self] , identifier[value_dict] ):
literal[string]
identifier[new_circuit] = identifier[self] . identifier[copy] ()
keyword[if] identifier[value_dict] . identifier[keys] ()> identifier[self] . identifier[parameters] :
keyw... | def bind_parameters(self, value_dict):
"""Assign parameters to values yielding a new circuit.
Args:
value_dict (dict): {parameter: value, ...}
Raises:
QiskitError: If value_dict contains parameters not present in the circuit
Returns:
QuantumCircuit: cop... |
def get_next_iteration(self, iteration, iteration_kwargs={}):
"""
BO-HB uses (just like Hyperband) SuccessiveHalving for each iteration.
See Li et al. (2016) for reference.
Parameters:
-----------
iteration: int
the index of the iteration to be instantiated
Returns:
--------
Succes... | def function[get_next_iteration, parameter[self, iteration, iteration_kwargs]]:
constant[
BO-HB uses (just like Hyperband) SuccessiveHalving for each iteration.
See Li et al. (2016) for reference.
Parameters:
-----------
iteration: int
the index of the iteration to be instantiated
R... | keyword[def] identifier[get_next_iteration] ( identifier[self] , identifier[iteration] , identifier[iteration_kwargs] ={}):
literal[string]
identifier[min_budget] = identifier[max] ( identifier[self] . identifier[min_budget] , identifier[self] . identifier[config_generator] . identifier[largest_budget_with_mo... | def get_next_iteration(self, iteration, iteration_kwargs={}):
"""
BO-HB uses (just like Hyperband) SuccessiveHalving for each iteration.
See Li et al. (2016) for reference.
Parameters:
-----------
iteration: int
the index of the iteration to be instantiated
Returns:
--------
Succ... |
def create_custom_menu(self, menu_data, matchrule):
"""
创建个性化菜单::
button = [
{
"type":"click",
"name":"今日歌曲",
"key":"V1001_TODAY_MUSIC"
},
{
"name":"菜单",
... | def function[create_custom_menu, parameter[self, menu_data, matchrule]]:
constant[
创建个性化菜单::
button = [
{
"type":"click",
"name":"今日歌曲",
"key":"V1001_TODAY_MUSIC"
},
{
... | keyword[def] identifier[create_custom_menu] ( identifier[self] , identifier[menu_data] , identifier[matchrule] ):
literal[string]
keyword[return] identifier[self] . identifier[post] (
identifier[url] = literal[string] ,
identifier[data] ={
literal[string] : identifier[me... | def create_custom_menu(self, menu_data, matchrule):
"""
创建个性化菜单::
button = [
{
"type":"click",
"name":"今日歌曲",
"key":"V1001_TODAY_MUSIC"
},
{
"name":"菜单",
... |
def update(self, **kwargs):
u"""Updating or creation of new simple nodes.
Each dict key is used as a tagname and value as text.
"""
for key, value in kwargs.items():
helper = helpers.CAST_DICT.get(type(value), str)
tag = self._get_aliases().get(key, key)
... | def function[update, parameter[self]]:
constant[Updating or creation of new simple nodes.
Each dict key is used as a tagname and value as text.
]
for taget[tuple[[<ast.Name object at 0x7da1b277d540>, <ast.Name object at 0x7da1b277ffd0>]]] in starred[call[name[kwargs].items, parameter[]]... | keyword[def] identifier[update] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[kwargs] . identifier[items] ():
identifier[helper] = identifier[helpers] . identifier[CAST_DICT] . identifier[get] ( i... | def update(self, **kwargs):
u"""Updating or creation of new simple nodes.
Each dict key is used as a tagname and value as text.
"""
for (key, value) in kwargs.items():
helper = helpers.CAST_DICT.get(type(value), str)
tag = self._get_aliases().get(key, key)
elements = lis... |
def pybel_to_json(molecule, name=None):
"""Converts a pybel molecule to json.
Args:
molecule: An instance of `pybel.Molecule`
name: (Optional) If specified, will save a "name" property
Returns:
A Python dictionary containing atom and bond data
"""
# Save atom element type and... | def function[pybel_to_json, parameter[molecule, name]]:
constant[Converts a pybel molecule to json.
Args:
molecule: An instance of `pybel.Molecule`
name: (Optional) If specified, will save a "name" property
Returns:
A Python dictionary containing atom and bond data
]
... | keyword[def] identifier[pybel_to_json] ( identifier[molecule] , identifier[name] = keyword[None] ):
literal[string]
identifier[atoms] =[{ literal[string] : identifier[table] . identifier[GetSymbol] ( identifier[atom] . identifier[atomicnum] ),
literal[string] : identifier[list] ( identifier[atom]... | def pybel_to_json(molecule, name=None):
"""Converts a pybel molecule to json.
Args:
molecule: An instance of `pybel.Molecule`
name: (Optional) If specified, will save a "name" property
Returns:
A Python dictionary containing atom and bond data
"""
# Save atom element type and... |
def runGetInfo(self, request):
"""
Returns information about the service including protocol version.
"""
return protocol.toJson(protocol.GetInfoResponse(
protocol_version=protocol.version)) | def function[runGetInfo, parameter[self, request]]:
constant[
Returns information about the service including protocol version.
]
return[call[name[protocol].toJson, parameter[call[name[protocol].GetInfoResponse, parameter[]]]]] | keyword[def] identifier[runGetInfo] ( identifier[self] , identifier[request] ):
literal[string]
keyword[return] identifier[protocol] . identifier[toJson] ( identifier[protocol] . identifier[GetInfoResponse] (
identifier[protocol_version] = identifier[protocol] . identifier[version] )) | def runGetInfo(self, request):
"""
Returns information about the service including protocol version.
"""
return protocol.toJson(protocol.GetInfoResponse(protocol_version=protocol.version)) |
def _initialize_uaa_cache(self):
"""
If we don't yet have a uaa cache we need to
initialize it. As there may be more than one
UAA instance we index by issuer and then store
any clients, users, etc.
"""
try:
os.makedirs(os.path.dirname(self._cache_path... | def function[_initialize_uaa_cache, parameter[self]]:
constant[
If we don't yet have a uaa cache we need to
initialize it. As there may be more than one
UAA instance we index by issuer and then store
any clients, users, etc.
]
<ast.Try object at 0x7da204344490>
... | keyword[def] identifier[_initialize_uaa_cache] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[os] . identifier[makedirs] ( identifier[os] . identifier[path] . identifier[dirname] ( identifier[self] . identifier[_cache_path] ))
keyword[except] identifier[OSErr... | def _initialize_uaa_cache(self):
"""
If we don't yet have a uaa cache we need to
initialize it. As there may be more than one
UAA instance we index by issuer and then store
any clients, users, etc.
"""
try:
os.makedirs(os.path.dirname(self._cache_path)) # depend... |
def load(cls, sc, path):
"""
Load a model from the given path.
"""
java_model = sc._jvm.org.apache.spark.mllib.classification.SVMModel.load(
sc._jsc.sc(), path)
weights = _java2py(sc, java_model.weights())
intercept = java_model.intercept()
threshold =... | def function[load, parameter[cls, sc, path]]:
constant[
Load a model from the given path.
]
variable[java_model] assign[=] call[name[sc]._jvm.org.apache.spark.mllib.classification.SVMModel.load, parameter[call[name[sc]._jsc.sc, parameter[]], name[path]]]
variable[weights] assign[... | keyword[def] identifier[load] ( identifier[cls] , identifier[sc] , identifier[path] ):
literal[string]
identifier[java_model] = identifier[sc] . identifier[_jvm] . identifier[org] . identifier[apache] . identifier[spark] . identifier[mllib] . identifier[classification] . identifier[SVMModel] . iden... | def load(cls, sc, path):
"""
Load a model from the given path.
"""
java_model = sc._jvm.org.apache.spark.mllib.classification.SVMModel.load(sc._jsc.sc(), path)
weights = _java2py(sc, java_model.weights())
intercept = java_model.intercept()
threshold = java_model.getThreshold().get()
... |
def Sleep(self, timeout):
"""Sleeps the calling thread with heartbeat."""
if self.nanny_controller:
self.nanny_controller.Heartbeat()
# Split a long sleep interval into 1 second intervals so we can heartbeat.
while timeout > 0:
time.sleep(min(1., timeout))
timeout -= 1
# If the ... | def function[Sleep, parameter[self, timeout]]:
constant[Sleeps the calling thread with heartbeat.]
if name[self].nanny_controller begin[:]
call[name[self].nanny_controller.Heartbeat, parameter[]]
while compare[name[timeout] greater[>] constant[0]] begin[:]
call[na... | keyword[def] identifier[Sleep] ( identifier[self] , identifier[timeout] ):
literal[string]
keyword[if] identifier[self] . identifier[nanny_controller] :
identifier[self] . identifier[nanny_controller] . identifier[Heartbeat] ()
keyword[while] identifier[timeout] > literal[int] :
... | def Sleep(self, timeout):
"""Sleeps the calling thread with heartbeat."""
if self.nanny_controller:
self.nanny_controller.Heartbeat() # depends on [control=['if'], data=[]]
# Split a long sleep interval into 1 second intervals so we can heartbeat.
while timeout > 0:
time.sleep(min(1.0, ... |
def _fit_island(self, island_data):
"""
Take an Island, do all the parameter estimation and fitting.
Parameters
----------
island_data : :class:`AegeanTools.models.IslandFittingData`
The island to be fit.
Returns
-------
sources : list
... | def function[_fit_island, parameter[self, island_data]]:
constant[
Take an Island, do all the parameter estimation and fitting.
Parameters
----------
island_data : :class:`AegeanTools.models.IslandFittingData`
The island to be fit.
Returns
-------
... | keyword[def] identifier[_fit_island] ( identifier[self] , identifier[island_data] ):
literal[string]
identifier[global_data] = identifier[self] . identifier[global_data]
identifier[dcurve] = identifier[global_data] . identifier[dcurve]
identifier[rmsimg] = identifier[g... | def _fit_island(self, island_data):
"""
Take an Island, do all the parameter estimation and fitting.
Parameters
----------
island_data : :class:`AegeanTools.models.IslandFittingData`
The island to be fit.
Returns
-------
sources : list
... |
def generate_header_validator(headers, context, **kwargs):
"""
Generates a validation function that will validate a dictionary of headers.
"""
validators = ValidationDict()
for header_definition in headers:
header_processor = generate_value_processor(
context=context,
... | def function[generate_header_validator, parameter[headers, context]]:
constant[
Generates a validation function that will validate a dictionary of headers.
]
variable[validators] assign[=] call[name[ValidationDict], parameter[]]
for taget[name[header_definition]] in starred[name[headers]... | keyword[def] identifier[generate_header_validator] ( identifier[headers] , identifier[context] ,** identifier[kwargs] ):
literal[string]
identifier[validators] = identifier[ValidationDict] ()
keyword[for] identifier[header_definition] keyword[in] identifier[headers] :
identifier[header_pro... | def generate_header_validator(headers, context, **kwargs):
"""
Generates a validation function that will validate a dictionary of headers.
"""
validators = ValidationDict()
for header_definition in headers:
header_processor = generate_value_processor(context=context, **header_definition)
... |
def _sync_binary_dep_links(self, target, gopath, lib_binary_map):
"""Syncs symlinks under gopath to the library binaries of target's transitive dependencies.
:param Target target: Target whose transitive dependencies must be linked.
:param str gopath: $GOPATH of target whose "pkg/" directory must be popula... | def function[_sync_binary_dep_links, parameter[self, target, gopath, lib_binary_map]]:
constant[Syncs symlinks under gopath to the library binaries of target's transitive dependencies.
:param Target target: Target whose transitive dependencies must be linked.
:param str gopath: $GOPATH of target whose ... | keyword[def] identifier[_sync_binary_dep_links] ( identifier[self] , identifier[target] , identifier[gopath] , identifier[lib_binary_map] ):
literal[string]
identifier[required_links] = identifier[set] ()
keyword[for] identifier[dep] keyword[in] identifier[target] . identifier[closure] ():
k... | def _sync_binary_dep_links(self, target, gopath, lib_binary_map):
"""Syncs symlinks under gopath to the library binaries of target's transitive dependencies.
:param Target target: Target whose transitive dependencies must be linked.
:param str gopath: $GOPATH of target whose "pkg/" directory must be popula... |
def _split_by_callable_region(data):
"""Split by callable or variant regions.
We expect joint calling to be deep in numbers of samples per region, so prefer
splitting aggressively by regions.
"""
batch = tz.get_in(("metadata", "batch"), data)
jointcaller = tz.get_in(("config", "algorithm", "joi... | def function[_split_by_callable_region, parameter[data]]:
constant[Split by callable or variant regions.
We expect joint calling to be deep in numbers of samples per region, so prefer
splitting aggressively by regions.
]
variable[batch] assign[=] call[name[tz].get_in, parameter[tuple[[<ast.... | keyword[def] identifier[_split_by_callable_region] ( identifier[data] ):
literal[string]
identifier[batch] = identifier[tz] . identifier[get_in] (( literal[string] , literal[string] ), identifier[data] )
identifier[jointcaller] = identifier[tz] . identifier[get_in] (( literal[string] , literal[string]... | def _split_by_callable_region(data):
"""Split by callable or variant regions.
We expect joint calling to be deep in numbers of samples per region, so prefer
splitting aggressively by regions.
"""
batch = tz.get_in(('metadata', 'batch'), data)
jointcaller = tz.get_in(('config', 'algorithm', 'joi... |
def UFL(Hc=None, atoms={}, CASRN='', AvailableMethods=False, Method=None):
r'''This function handles the retrieval or calculation of a chemical's
Upper Flammability Limit. Lookup is based on CASRNs. Two predictive methods
are currently implemented. Will automatically select a data source to use
if no Me... | def function[UFL, parameter[Hc, atoms, CASRN, AvailableMethods, Method]]:
constant[This function handles the retrieval or calculation of a chemical's
Upper Flammability Limit. Lookup is based on CASRNs. Two predictive methods
are currently implemented. Will automatically select a data source to use
... | keyword[def] identifier[UFL] ( identifier[Hc] = keyword[None] , identifier[atoms] ={}, identifier[CASRN] = literal[string] , identifier[AvailableMethods] = keyword[False] , identifier[Method] = keyword[None] ):
literal[string]
keyword[def] identifier[list_methods] ():
identifier[methods] =[]
... | def UFL(Hc=None, atoms={}, CASRN='', AvailableMethods=False, Method=None):
"""This function handles the retrieval or calculation of a chemical's
Upper Flammability Limit. Lookup is based on CASRNs. Two predictive methods
are currently implemented. Will automatically select a data source to use
if no Met... |
def set_area_to_sip_signature(self, xmin, xmax, zmin, zmax, spectrum):
"""Parameterize the eit instance by supplying one
SIP spectrum and the area to apply to.
Parameters
----------
xmin : float
Minimum x coordinate of the area
xmax : float
Maximu... | def function[set_area_to_sip_signature, parameter[self, xmin, xmax, zmin, zmax, spectrum]]:
constant[Parameterize the eit instance by supplying one
SIP spectrum and the area to apply to.
Parameters
----------
xmin : float
Minimum x coordinate of the area
xmax... | keyword[def] identifier[set_area_to_sip_signature] ( identifier[self] , identifier[xmin] , identifier[xmax] , identifier[zmin] , identifier[zmax] , identifier[spectrum] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[spectrum] ,( identifier[sip_response] , identifier[sip_res... | def set_area_to_sip_signature(self, xmin, xmax, zmin, zmax, spectrum):
"""Parameterize the eit instance by supplying one
SIP spectrum and the area to apply to.
Parameters
----------
xmin : float
Minimum x coordinate of the area
xmax : float
Maximum x ... |
def _add_disease_associations(self, disease_associations: dict) -> None:
"""Add disease association annotation to the network.
:param disease_associations: Dictionary of disease-gene associations.
"""
if disease_associations is not None:
for target_id, disease_id_list in dis... | def function[_add_disease_associations, parameter[self, disease_associations]]:
constant[Add disease association annotation to the network.
:param disease_associations: Dictionary of disease-gene associations.
]
if compare[name[disease_associations] is_not constant[None]] begin[:]
... | keyword[def] identifier[_add_disease_associations] ( identifier[self] , identifier[disease_associations] : identifier[dict] )-> keyword[None] :
literal[string]
keyword[if] identifier[disease_associations] keyword[is] keyword[not] keyword[None] :
keyword[for] identifier[target_id] ... | def _add_disease_associations(self, disease_associations: dict) -> None:
"""Add disease association annotation to the network.
:param disease_associations: Dictionary of disease-gene associations.
"""
if disease_associations is not None:
for (target_id, disease_id_list) in disease_assoc... |
def print_upper_triangular_matrix(matrix):
"""Prints a CVRP data dict matrix
Arguments
---------
matrix : dict
Description
Notes
-----
It is assummed that the first row of matrix contains all needed headers.
"""
# Print column header
# Assumes first row con... | def function[print_upper_triangular_matrix, parameter[matrix]]:
constant[Prints a CVRP data dict matrix
Arguments
---------
matrix : dict
Description
Notes
-----
It is assummed that the first row of matrix contains all needed headers.
]
variable[first] a... | keyword[def] identifier[print_upper_triangular_matrix] ( identifier[matrix] ):
literal[string]
identifier[first] = identifier[sorted] ( identifier[matrix] . identifier[keys] ())[ literal[int] ]
identifier[print] ( literal[string] , identifier[end] = literal[string] )
keyword[for] iden... | def print_upper_triangular_matrix(matrix):
"""Prints a CVRP data dict matrix
Arguments
---------
matrix : dict
Description
Notes
-----
It is assummed that the first row of matrix contains all needed headers.
"""
# Print column header
# Assumes first row cont... |
def rate_limit(self):
"""Returns a dictionary with information from /rate_limit.
The dictionary has two keys: ``resources`` and ``rate``. In
``resources`` you can access information about ``core`` or ``search``.
Note: the ``rate`` key will be deprecated before version 3 of the
... | def function[rate_limit, parameter[self]]:
constant[Returns a dictionary with information from /rate_limit.
The dictionary has two keys: ``resources`` and ``rate``. In
``resources`` you can access information about ``core`` or ``search``.
Note: the ``rate`` key will be deprecated befor... | keyword[def] identifier[rate_limit] ( identifier[self] ):
literal[string]
identifier[url] = identifier[self] . identifier[_build_url] ( literal[string] )
keyword[return] identifier[self] . identifier[_json] ( identifier[self] . identifier[_get] ( identifier[url] ), literal[int] ) | def rate_limit(self):
"""Returns a dictionary with information from /rate_limit.
The dictionary has two keys: ``resources`` and ``rate``. In
``resources`` you can access information about ``core`` or ``search``.
Note: the ``rate`` key will be deprecated before version 3 of the
GitH... |
def word_error_rate(ref: Sequence[T], hyp: Sequence[T]) -> float:
""" Calculate the word error rate of a sequence against a reference.
Args:
ref: The gold-standard reference sequence
hyp: The hypothesis to be evaluated against the reference.
Returns:
The word error rate of the supp... | def function[word_error_rate, parameter[ref, hyp]]:
constant[ Calculate the word error rate of a sequence against a reference.
Args:
ref: The gold-standard reference sequence
hyp: The hypothesis to be evaluated against the reference.
Returns:
The word error rate of the supplied... | keyword[def] identifier[word_error_rate] ( identifier[ref] : identifier[Sequence] [ identifier[T] ], identifier[hyp] : identifier[Sequence] [ identifier[T] ])-> identifier[float] :
literal[string]
keyword[if] identifier[len] ( identifier[ref] )== literal[int] :
keyword[raise] identifier[EmptyRe... | def word_error_rate(ref: Sequence[T], hyp: Sequence[T]) -> float:
""" Calculate the word error rate of a sequence against a reference.
Args:
ref: The gold-standard reference sequence
hyp: The hypothesis to be evaluated against the reference.
Returns:
The word error rate of the supp... |
def clean(self):
"""
Cleans the input values of this configuration object.
Fields that have gotten updated through properties are converted to configuration values that match the
format needed by functions using them. For example, for list-like values it means that input of single strin... | def function[clean, parameter[self]]:
constant[
Cleans the input values of this configuration object.
Fields that have gotten updated through properties are converted to configuration values that match the
format needed by functions using them. For example, for list-like values it means... | keyword[def] identifier[clean] ( identifier[self] ):
literal[string]
identifier[all_props] = identifier[self] . identifier[__class__] . identifier[CONFIG_PROPERTIES]
keyword[for] identifier[prop_name] keyword[in] identifier[self] . identifier[_modified] :
identifier[attr_c... | def clean(self):
"""
Cleans the input values of this configuration object.
Fields that have gotten updated through properties are converted to configuration values that match the
format needed by functions using them. For example, for list-like values it means that input of single strings
... |
def compile(self, db):
"""Building the sql expression
:param db: the database instance
"""
sql = self.expression
if self.alias:
sql += (' AS ' + db.quote_column(self.alias))
return sql | def function[compile, parameter[self, db]]:
constant[Building the sql expression
:param db: the database instance
]
variable[sql] assign[=] name[self].expression
if name[self].alias begin[:]
<ast.AugAssign object at 0x7da20cabfb20>
return[name[sql]] | keyword[def] identifier[compile] ( identifier[self] , identifier[db] ):
literal[string]
identifier[sql] = identifier[self] . identifier[expression]
keyword[if] identifier[self] . identifier[alias] :
identifier[sql] +=( literal[string] + identifier[db] . identifier[quote_colu... | def compile(self, db):
"""Building the sql expression
:param db: the database instance
"""
sql = self.expression
if self.alias:
sql += ' AS ' + db.quote_column(self.alias) # depends on [control=['if'], data=[]]
return sql |
def vector_unit_nonull(v):
"""Return unit vectors.
Any null vectors raise an Exception.
Parameters
----------
v: array, shape (a1, a2, ..., d)
Cartesian vectors, with last axis indexing the dimension.
Returns
-------
v_new: array, shape of v
"""
if v.size == 0:
... | def function[vector_unit_nonull, parameter[v]]:
constant[Return unit vectors.
Any null vectors raise an Exception.
Parameters
----------
v: array, shape (a1, a2, ..., d)
Cartesian vectors, with last axis indexing the dimension.
Returns
-------
v_new: array, shape of v
]... | keyword[def] identifier[vector_unit_nonull] ( identifier[v] ):
literal[string]
keyword[if] identifier[v] . identifier[size] == literal[int] :
keyword[return] identifier[v]
keyword[return] identifier[v] / identifier[vector_mag] ( identifier[v] )[..., identifier[np] . identifier[newaxis] ] | def vector_unit_nonull(v):
"""Return unit vectors.
Any null vectors raise an Exception.
Parameters
----------
v: array, shape (a1, a2, ..., d)
Cartesian vectors, with last axis indexing the dimension.
Returns
-------
v_new: array, shape of v
"""
if v.size == 0:
... |
def integrate_adaptive(rhs, jac, y0, x0, xend, atol, rtol, dx0=.0, dx_max=.0,
check_callable=False, check_indexing=False, **kwargs):
"""
Integrates a system of ordinary differential equations.
Parameters
----------
rhs: callable
Function with signature f(t, y, fout) w... | def function[integrate_adaptive, parameter[rhs, jac, y0, x0, xend, atol, rtol, dx0, dx_max, check_callable, check_indexing]]:
constant[
Integrates a system of ordinary differential equations.
Parameters
----------
rhs: callable
Function with signature f(t, y, fout) which modifies fout *... | keyword[def] identifier[integrate_adaptive] ( identifier[rhs] , identifier[jac] , identifier[y0] , identifier[x0] , identifier[xend] , identifier[atol] , identifier[rtol] , identifier[dx0] = literal[int] , identifier[dx_max] = literal[int] ,
identifier[check_callable] = keyword[False] , identifier[check_indexing] = ... | def integrate_adaptive(rhs, jac, y0, x0, xend, atol, rtol, dx0=0.0, dx_max=0.0, check_callable=False, check_indexing=False, **kwargs):
"""
Integrates a system of ordinary differential equations.
Parameters
----------
rhs: callable
Function with signature f(t, y, fout) which modifies fout *i... |
def get_cod_ids(self, formula):
"""
Queries the COD for all cod ids associated with a formula. Requires
mysql executable to be in the path.
Args:
formula (str): Formula.
Returns:
List of cod ids.
"""
# TODO: Remove dependency on external ... | def function[get_cod_ids, parameter[self, formula]]:
constant[
Queries the COD for all cod ids associated with a formula. Requires
mysql executable to be in the path.
Args:
formula (str): Formula.
Returns:
List of cod ids.
]
variable[sql]... | keyword[def] identifier[get_cod_ids] ( identifier[self] , identifier[formula] ):
literal[string]
identifier[sql] = literal[string] % identifier[Composition] ( identifier[formula] ). identifier[hill_formula]
identifier[text] = identifier[self] . identifier[query] ( iden... | def get_cod_ids(self, formula):
"""
Queries the COD for all cod ids associated with a formula. Requires
mysql executable to be in the path.
Args:
formula (str): Formula.
Returns:
List of cod ids.
"""
# TODO: Remove dependency on external mysql ca... |
def get_ignored_files(self):
"""Returns the list of files being ignored in this repository.
Note that file names, not directories, are returned.
So, we will get the following:
a/b.txt
a/c.txt
instead of just:
a/
Returns:
List[str] - list ... | def function[get_ignored_files, parameter[self]]:
constant[Returns the list of files being ignored in this repository.
Note that file names, not directories, are returned.
So, we will get the following:
a/b.txt
a/c.txt
instead of just:
a/
Returns:
... | keyword[def] identifier[get_ignored_files] ( identifier[self] ):
literal[string]
keyword[return] [ identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[path] , identifier[p] ) keyword[for] identifier[p] keyword[in]
identifier[self] . identifier[run] ( lit... | def get_ignored_files(self):
"""Returns the list of files being ignored in this repository.
Note that file names, not directories, are returned.
So, we will get the following:
a/b.txt
a/c.txt
instead of just:
a/
Returns:
List[str] - list of i... |
def get_message(self, *parameters):
"""Get encoded message.
* Send Message -keywords are convenience methods, that will call this to
get the message object and then send it. Optional parameters are message
field values separated with colon.
Examples:
| ${msg} = | Get me... | def function[get_message, parameter[self]]:
constant[Get encoded message.
* Send Message -keywords are convenience methods, that will call this to
get the message object and then send it. Optional parameters are message
field values separated with colon.
Examples:
| ${m... | keyword[def] identifier[get_message] ( identifier[self] ,* identifier[parameters] ):
literal[string]
identifier[_] , identifier[message_fields] , identifier[header_fields] = identifier[self] . identifier[_get_parameters_with_defaults] ( identifier[parameters] )
keyword[return] identifier[... | def get_message(self, *parameters):
"""Get encoded message.
* Send Message -keywords are convenience methods, that will call this to
get the message object and then send it. Optional parameters are message
field values separated with colon.
Examples:
| ${msg} = | Get messag... |
def kill_websudo(self):
"""Destroy the user's current WebSudo session.
Works only for non-cloud deployments, for others does nothing.
:rtype: Optional[Any]
"""
if self.deploymentType != 'Cloud':
url = self._options['server'] + '/rest/auth/1/websudo'
retu... | def function[kill_websudo, parameter[self]]:
constant[Destroy the user's current WebSudo session.
Works only for non-cloud deployments, for others does nothing.
:rtype: Optional[Any]
]
if compare[name[self].deploymentType not_equal[!=] constant[Cloud]] begin[:]
... | keyword[def] identifier[kill_websudo] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[deploymentType] != literal[string] :
identifier[url] = identifier[self] . identifier[_options] [ literal[string] ]+ literal[string]
keyword[return] iden... | def kill_websudo(self):
"""Destroy the user's current WebSudo session.
Works only for non-cloud deployments, for others does nothing.
:rtype: Optional[Any]
"""
if self.deploymentType != 'Cloud':
url = self._options['server'] + '/rest/auth/1/websudo'
return self._session... |
def _piecewise_learning_rate(step, boundaries, values):
"""Scale learning rate according to the given schedule.
Multipliers are not cumulative.
Args:
step: global step
boundaries: List of steps to transition on.
values: Multiplier to apply at each boundary transition.
Returns:
Scaled value fo... | def function[_piecewise_learning_rate, parameter[step, boundaries, values]]:
constant[Scale learning rate according to the given schedule.
Multipliers are not cumulative.
Args:
step: global step
boundaries: List of steps to transition on.
values: Multiplier to apply at each boundary transition... | keyword[def] identifier[_piecewise_learning_rate] ( identifier[step] , identifier[boundaries] , identifier[values] ):
literal[string]
identifier[values] =[ literal[int] ]+ identifier[values]
identifier[boundaries] =[ identifier[float] ( identifier[x] ) keyword[for] identifier[x] keyword[in] identifier[b... | def _piecewise_learning_rate(step, boundaries, values):
"""Scale learning rate according to the given schedule.
Multipliers are not cumulative.
Args:
step: global step
boundaries: List of steps to transition on.
values: Multiplier to apply at each boundary transition.
Returns:
Scaled value ... |
def _localized_name(val, klass):
"""If no language is defined 'en' is the default"""
try:
(text, lang) = val
return klass(text=text, lang=lang)
except ValueError:
return klass(text=val, lang="en") | def function[_localized_name, parameter[val, klass]]:
constant[If no language is defined 'en' is the default]
<ast.Try object at 0x7da20c9905e0> | keyword[def] identifier[_localized_name] ( identifier[val] , identifier[klass] ):
literal[string]
keyword[try] :
( identifier[text] , identifier[lang] )= identifier[val]
keyword[return] identifier[klass] ( identifier[text] = identifier[text] , identifier[lang] = identifier[lang] )
k... | def _localized_name(val, klass):
"""If no language is defined 'en' is the default"""
try:
(text, lang) = val
return klass(text=text, lang=lang) # depends on [control=['try'], data=[]]
except ValueError:
return klass(text=val, lang='en') # depends on [control=['except'], data=[]] |
def getobjectlist(self, window_name):
"""
Get list of items in given GUI.
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@return: list of items in LDTP naming convention.
@rtype: l... | def function[getobjectlist, parameter[self, window_name]]:
constant[
Get list of items in given GUI.
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@return: list of items in LDTP naming co... | keyword[def] identifier[getobjectlist] ( identifier[self] , identifier[window_name] ):
literal[string]
keyword[try] :
identifier[window_handle] , identifier[name] , identifier[app] = identifier[self] . identifier[_get_window_handle] ( identifier[window_name] , keyword[True] )
... | def getobjectlist(self, window_name):
"""
Get list of items in given GUI.
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@return: list of items in LDTP naming convention.
@rtype: list
... |
def n_day(date_string):
"""
date_string string in format "(number|a) day(s) ago"
"""
today = datetime.date.today()
match = re.match(r'(\d{1,3}|a) days? ago', date_string)
groups = match.groups()
if groups:
decrement = groups[0]
if decrement... | def function[n_day, parameter[date_string]]:
constant[
date_string string in format "(number|a) day(s) ago"
]
variable[today] assign[=] call[name[datetime].date.today, parameter[]]
variable[match] assign[=] call[name[re].match, parameter[constant[(\d{1,3}|a) days? ago], name[date... | keyword[def] identifier[n_day] ( identifier[date_string] ):
literal[string]
identifier[today] = identifier[datetime] . identifier[date] . identifier[today] ()
identifier[match] = identifier[re] . identifier[match] ( literal[string] , identifier[date_string] )
identifier[groups] = ... | def n_day(date_string):
"""
date_string string in format "(number|a) day(s) ago"
"""
today = datetime.date.today()
match = re.match('(\\d{1,3}|a) days? ago', date_string)
groups = match.groups()
if groups:
decrement = groups[0]
if decrement == 'a':
decreme... |
def get_bin_version(bin_path, version_flag='-v', kw={}):
"""
Get the version string through the binary and return a tuple of
integers.
"""
version_str = get_bin_version_str(bin_path, version_flag, kw)
if version_str:
return tuple(int(i) for i in version_str.split('.')) | def function[get_bin_version, parameter[bin_path, version_flag, kw]]:
constant[
Get the version string through the binary and return a tuple of
integers.
]
variable[version_str] assign[=] call[name[get_bin_version_str], parameter[name[bin_path], name[version_flag], name[kw]]]
if name... | keyword[def] identifier[get_bin_version] ( identifier[bin_path] , identifier[version_flag] = literal[string] , identifier[kw] ={}):
literal[string]
identifier[version_str] = identifier[get_bin_version_str] ( identifier[bin_path] , identifier[version_flag] , identifier[kw] )
keyword[if] identifier[ve... | def get_bin_version(bin_path, version_flag='-v', kw={}):
"""
Get the version string through the binary and return a tuple of
integers.
"""
version_str = get_bin_version_str(bin_path, version_flag, kw)
if version_str:
return tuple((int(i) for i in version_str.split('.'))) # depends on [c... |
def update_positions(self, r_array):
'''Update the coordinate array r_array'''
self.ar.update_positions(r_array)
if self.has_bonds:
self.br.update_positions(r_array) | def function[update_positions, parameter[self, r_array]]:
constant[Update the coordinate array r_array]
call[name[self].ar.update_positions, parameter[name[r_array]]]
if name[self].has_bonds begin[:]
call[name[self].br.update_positions, parameter[name[r_array]]] | keyword[def] identifier[update_positions] ( identifier[self] , identifier[r_array] ):
literal[string]
identifier[self] . identifier[ar] . identifier[update_positions] ( identifier[r_array] )
keyword[if] identifier[self] . identifier[has_bonds] :
identifier[self] . identifier... | def update_positions(self, r_array):
"""Update the coordinate array r_array"""
self.ar.update_positions(r_array)
if self.has_bonds:
self.br.update_positions(r_array) # depends on [control=['if'], data=[]] |
def count(self, filter=None, session=None, **kwargs):
"""**DEPRECATED** - Get the number of documents in this collection.
The :meth:`count` method is deprecated and **not** supported in a
transaction. Please use :meth:`count_documents` or
:meth:`estimated_document_count` instead.
... | def function[count, parameter[self, filter, session]]:
constant[**DEPRECATED** - Get the number of documents in this collection.
The :meth:`count` method is deprecated and **not** supported in a
transaction. Please use :meth:`count_documents` or
:meth:`estimated_document_count` instead.... | keyword[def] identifier[count] ( identifier[self] , identifier[filter] = keyword[None] , identifier[session] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[warnings] . identifier[warn] ( literal[string]
literal[string]
literal[string]
literal[stri... | def count(self, filter=None, session=None, **kwargs):
"""**DEPRECATED** - Get the number of documents in this collection.
The :meth:`count` method is deprecated and **not** supported in a
transaction. Please use :meth:`count_documents` or
:meth:`estimated_document_count` instead.
A... |
def handle_api_error(resp):
"""Stolen straight from the Stripe Python source."""
content = yield resp.json()
headers = HeaderWrapper(resp.headers)
try:
err = content['error']
except (KeyError, TypeError):
raise error.APIError(
"Invalid response object from API: %r (HTTP... | def function[handle_api_error, parameter[resp]]:
constant[Stolen straight from the Stripe Python source.]
variable[content] assign[=] <ast.Yield object at 0x7da1b26ae8c0>
variable[headers] assign[=] call[name[HeaderWrapper], parameter[name[resp].headers]]
<ast.Try object at 0x7da1b26ad150>
... | keyword[def] identifier[handle_api_error] ( identifier[resp] ):
literal[string]
identifier[content] = keyword[yield] identifier[resp] . identifier[json] ()
identifier[headers] = identifier[HeaderWrapper] ( identifier[resp] . identifier[headers] )
keyword[try] :
identifier[err] = ident... | def handle_api_error(resp):
"""Stolen straight from the Stripe Python source."""
content = (yield resp.json())
headers = HeaderWrapper(resp.headers)
try:
err = content['error'] # depends on [control=['try'], data=[]]
except (KeyError, TypeError):
raise error.APIError('Invalid respon... |
def DropPrivileges():
"""Attempt to drop privileges if required."""
if config.CONFIG["Server.username"]:
try:
os.setuid(pwd.getpwnam(config.CONFIG["Server.username"]).pw_uid)
except (KeyError, OSError):
logging.exception("Unable to switch to user %s",
config.CONFIG["Serve... | def function[DropPrivileges, parameter[]]:
constant[Attempt to drop privileges if required.]
if call[name[config].CONFIG][constant[Server.username]] begin[:]
<ast.Try object at 0x7da1b1b296c0> | keyword[def] identifier[DropPrivileges] ():
literal[string]
keyword[if] identifier[config] . identifier[CONFIG] [ literal[string] ]:
keyword[try] :
identifier[os] . identifier[setuid] ( identifier[pwd] . identifier[getpwnam] ( identifier[config] . identifier[CONFIG] [ literal[string] ]). identifie... | def DropPrivileges():
"""Attempt to drop privileges if required."""
if config.CONFIG['Server.username']:
try:
os.setuid(pwd.getpwnam(config.CONFIG['Server.username']).pw_uid) # depends on [control=['try'], data=[]]
except (KeyError, OSError):
logging.exception('Unable to... |
def flavor_extra_delete(request, flavor_id, keys):
"""Unset the flavor extra spec keys."""
flavor = _nova.novaclient(request).flavors.get(flavor_id)
return flavor.unset_keys(keys) | def function[flavor_extra_delete, parameter[request, flavor_id, keys]]:
constant[Unset the flavor extra spec keys.]
variable[flavor] assign[=] call[call[name[_nova].novaclient, parameter[name[request]]].flavors.get, parameter[name[flavor_id]]]
return[call[name[flavor].unset_keys, parameter[name[keys... | keyword[def] identifier[flavor_extra_delete] ( identifier[request] , identifier[flavor_id] , identifier[keys] ):
literal[string]
identifier[flavor] = identifier[_nova] . identifier[novaclient] ( identifier[request] ). identifier[flavors] . identifier[get] ( identifier[flavor_id] )
keyword[return] ide... | def flavor_extra_delete(request, flavor_id, keys):
"""Unset the flavor extra spec keys."""
flavor = _nova.novaclient(request).flavors.get(flavor_id)
return flavor.unset_keys(keys) |
def _get_binary_from_ipv4(self, ip_addr):
"""Converts IPv4 address to binary form."""
return struct.unpack("!L", socket.inet_pton(socket.AF_INET,
ip_addr))[0] | def function[_get_binary_from_ipv4, parameter[self, ip_addr]]:
constant[Converts IPv4 address to binary form.]
return[call[call[name[struct].unpack, parameter[constant[!L], call[name[socket].inet_pton, parameter[name[socket].AF_INET, name[ip_addr]]]]]][constant[0]]] | keyword[def] identifier[_get_binary_from_ipv4] ( identifier[self] , identifier[ip_addr] ):
literal[string]
keyword[return] identifier[struct] . identifier[unpack] ( literal[string] , identifier[socket] . identifier[inet_pton] ( identifier[socket] . identifier[AF_INET] ,
identifier[ip_add... | def _get_binary_from_ipv4(self, ip_addr):
"""Converts IPv4 address to binary form."""
return struct.unpack('!L', socket.inet_pton(socket.AF_INET, ip_addr))[0] |
def mark_dead(self, proxy, _time=None):
""" Mark a proxy as dead """
if proxy not in self.proxies:
logger.warn("Proxy <%s> was not found in proxies list" % proxy)
return
if proxy in self.good:
logger.debug("GOOD proxy became DEAD: <%s>" % proxy)
else:... | def function[mark_dead, parameter[self, proxy, _time]]:
constant[ Mark a proxy as dead ]
if compare[name[proxy] <ast.NotIn object at 0x7da2590d7190> name[self].proxies] begin[:]
call[name[logger].warn, parameter[binary_operation[constant[Proxy <%s> was not found in proxies list] <ast.Mod... | keyword[def] identifier[mark_dead] ( identifier[self] , identifier[proxy] , identifier[_time] = keyword[None] ):
literal[string]
keyword[if] identifier[proxy] keyword[not] keyword[in] identifier[self] . identifier[proxies] :
identifier[logger] . identifier[warn] ( literal[string] %... | def mark_dead(self, proxy, _time=None):
""" Mark a proxy as dead """
if proxy not in self.proxies:
logger.warn('Proxy <%s> was not found in proxies list' % proxy)
return # depends on [control=['if'], data=['proxy']]
if proxy in self.good:
logger.debug('GOOD proxy became DEAD: <%s>' ... |
def format(self, typedval):
'Return displayable string of `typedval` according to `Column.fmtstr`'
if typedval is None:
return None
if isinstance(typedval, (list, tuple)):
return '[%s]' % len(typedval)
if isinstance(typedval, dict):
return '{%s}' % le... | def function[format, parameter[self, typedval]]:
constant[Return displayable string of `typedval` according to `Column.fmtstr`]
if compare[name[typedval] is constant[None]] begin[:]
return[constant[None]]
if call[name[isinstance], parameter[name[typedval], tuple[[<ast.Name object at 0x7d... | keyword[def] identifier[format] ( identifier[self] , identifier[typedval] ):
literal[string]
keyword[if] identifier[typedval] keyword[is] keyword[None] :
keyword[return] keyword[None]
keyword[if] identifier[isinstance] ( identifier[typedval] ,( identifier[list] , identi... | def format(self, typedval):
"""Return displayable string of `typedval` according to `Column.fmtstr`"""
if typedval is None:
return None # depends on [control=['if'], data=[]]
if isinstance(typedval, (list, tuple)):
return '[%s]' % len(typedval) # depends on [control=['if'], data=[]]
if... |
def from_zhang_huang_solar(cls, location, cloud_cover,
relative_humidity, dry_bulb_temperature,
wind_speed, atmospheric_pressure=None,
timestep=1, is_leap_year=False, use_disc=False):
"""Create a wea object from climate... | def function[from_zhang_huang_solar, parameter[cls, location, cloud_cover, relative_humidity, dry_bulb_temperature, wind_speed, atmospheric_pressure, timestep, is_leap_year, use_disc]]:
constant[Create a wea object from climate data using the Zhang-Huang model.
The Zhang-Huang solar model was developed... | keyword[def] identifier[from_zhang_huang_solar] ( identifier[cls] , identifier[location] , identifier[cloud_cover] ,
identifier[relative_humidity] , identifier[dry_bulb_temperature] ,
identifier[wind_speed] , identifier[atmospheric_pressure] = keyword[None] ,
identifier[timestep] = literal[int] , identifier[is_lea... | def from_zhang_huang_solar(cls, location, cloud_cover, relative_humidity, dry_bulb_temperature, wind_speed, atmospheric_pressure=None, timestep=1, is_leap_year=False, use_disc=False):
"""Create a wea object from climate data using the Zhang-Huang model.
The Zhang-Huang solar model was developed to estimate... |
def uniqify(cls, seq):
"""Returns a unique list of seq"""
seen = set()
seen_add = seen.add
return [ x for x in seq if x not in seen and not seen_add(x)] | def function[uniqify, parameter[cls, seq]]:
constant[Returns a unique list of seq]
variable[seen] assign[=] call[name[set], parameter[]]
variable[seen_add] assign[=] name[seen].add
return[<ast.ListComp object at 0x7da1b26ac700>] | keyword[def] identifier[uniqify] ( identifier[cls] , identifier[seq] ):
literal[string]
identifier[seen] = identifier[set] ()
identifier[seen_add] = identifier[seen] . identifier[add]
keyword[return] [ identifier[x] keyword[for] identifier[x] keyword[in] identifier[seq] keyw... | def uniqify(cls, seq):
"""Returns a unique list of seq"""
seen = set()
seen_add = seen.add
return [x for x in seq if x not in seen and (not seen_add(x))] |
def short_refs(self):
"""
we calculate on the fly to avoid managing registrations and un-registrations
Returns
-------
{ref: short_ref, ...
"""
naive_short_refs_d = dict() # naive_short_ref: {refs, ...}
for ef in self._external_files:
if ef.n... | def function[short_refs, parameter[self]]:
constant[
we calculate on the fly to avoid managing registrations and un-registrations
Returns
-------
{ref: short_ref, ...
]
variable[naive_short_refs_d] assign[=] call[name[dict], parameter[]]
for taget[name[ef... | keyword[def] identifier[short_refs] ( identifier[self] ):
literal[string]
identifier[naive_short_refs_d] = identifier[dict] ()
keyword[for] identifier[ef] keyword[in] identifier[self] . identifier[_external_files] :
keyword[if] identifier[ef] . identifier[naive_short_ref] ... | def short_refs(self):
"""
we calculate on the fly to avoid managing registrations and un-registrations
Returns
-------
{ref: short_ref, ...
"""
naive_short_refs_d = dict() # naive_short_ref: {refs, ...}
for ef in self._external_files:
if ef.naive_short_ref n... |
def build_filter(self, filter):
"""
Tries to build a :class:`filter.Filter` instance from the given filter.
Raises ValueError if the :class:`filter.Filter` object can't be build
from the given filter.
"""
try:
self.filter = Filter.from_string(filter, self.lim... | def function[build_filter, parameter[self, filter]]:
constant[
Tries to build a :class:`filter.Filter` instance from the given filter.
Raises ValueError if the :class:`filter.Filter` object can't be build
from the given filter.
]
<ast.Try object at 0x7da18f58d600>
return... | keyword[def] identifier[build_filter] ( identifier[self] , identifier[filter] ):
literal[string]
keyword[try] :
identifier[self] . identifier[filter] = identifier[Filter] . identifier[from_string] ( identifier[filter] , identifier[self] . identifier[limit] )
keyword[except] i... | def build_filter(self, filter):
"""
Tries to build a :class:`filter.Filter` instance from the given filter.
Raises ValueError if the :class:`filter.Filter` object can't be build
from the given filter.
"""
try:
self.filter = Filter.from_string(filter, self.limit) # depen... |
def remove_pid_file(self):
"""Remove the pid file.
This should be called at shutdown by registering a callback with
:func:`reactor.addSystemEventTrigger`. This needs to return
``None``.
"""
pid_file = os.path.join(self.profile_dir.pid_dir, self.name + u'.pid')
if... | def function[remove_pid_file, parameter[self]]:
constant[Remove the pid file.
This should be called at shutdown by registering a callback with
:func:`reactor.addSystemEventTrigger`. This needs to return
``None``.
]
variable[pid_file] assign[=] call[name[os].path.join, pa... | keyword[def] identifier[remove_pid_file] ( identifier[self] ):
literal[string]
identifier[pid_file] = identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[profile_dir] . identifier[pid_dir] , identifier[self] . identifier[name] + literal[string] )
keyword[if... | def remove_pid_file(self):
"""Remove the pid file.
This should be called at shutdown by registering a callback with
:func:`reactor.addSystemEventTrigger`. This needs to return
``None``.
"""
pid_file = os.path.join(self.profile_dir.pid_dir, self.name + u'.pid')
if os.path.isf... |
def from_rest(model, props):
""" Map the REST data onto the model
Additionally, perform the following tasks:
* set all blank strings to None where needed
* purge all fields not allowed as incoming data
* purge all unknown fields from the incoming data
* lowercase certain fields... | def function[from_rest, parameter[model, props]]:
constant[ Map the REST data onto the model
Additionally, perform the following tasks:
* set all blank strings to None where needed
* purge all fields not allowed as incoming data
* purge all unknown fields from the incoming data
... | keyword[def] identifier[from_rest] ( identifier[model] , identifier[props] ):
literal[string]
identifier[req] = identifier[goldman] . identifier[sess] . identifier[req]
identifier[_from_rest_blank] ( identifier[model] , identifier[props] )
identifier[_from_rest_hide] ( identifier[model] , iden... | def from_rest(model, props):
""" Map the REST data onto the model
Additionally, perform the following tasks:
* set all blank strings to None where needed
* purge all fields not allowed as incoming data
* purge all unknown fields from the incoming data
* lowercase certain fields... |
def unbounded(self):
"""
Get whether this node is unbounded I{(a collection)}
@return: True if unbounded, else False.
@rtype: boolean
"""
max = self.max
if max is None:
max = '1'
if max.isdigit():
return (int(max) > 1)
else:... | def function[unbounded, parameter[self]]:
constant[
Get whether this node is unbounded I{(a collection)}
@return: True if unbounded, else False.
@rtype: boolean
]
variable[max] assign[=] name[self].max
if compare[name[max] is constant[None]] begin[:]
... | keyword[def] identifier[unbounded] ( identifier[self] ):
literal[string]
identifier[max] = identifier[self] . identifier[max]
keyword[if] identifier[max] keyword[is] keyword[None] :
identifier[max] = literal[string]
keyword[if] identifier[max] . identifier[isdig... | def unbounded(self):
"""
Get whether this node is unbounded I{(a collection)}
@return: True if unbounded, else False.
@rtype: boolean
"""
max = self.max
if max is None:
max = '1' # depends on [control=['if'], data=['max']]
if max.isdigit():
return int(max... |
def _build_for_statement(self):
"""NOTE: this is not a complete implementation of for loop parsing.
Turns out for loops allow a number of wacky things going on,
such as declaring a variable in place of a condition.
These more peculiar cases are not covered. See
ht... | def function[_build_for_statement, parameter[self]]:
constant[NOTE: this is not a complete implementation of for loop parsing.
Turns out for loops allow a number of wacky things going on,
such as declaring a variable in place of a condition.
These more peculiar cases are not ... | keyword[def] identifier[_build_for_statement] ( identifier[self] ):
literal[string]
identifier[cppobj] = identifier[CppLoop] ( identifier[self] . identifier[scope] , identifier[self] . identifier[parent] , literal[string] )
identifier[cppobj] . identifier[file] = identifier[self] . identif... | def _build_for_statement(self):
"""NOTE: this is not a complete implementation of for loop parsing.
Turns out for loops allow a number of wacky things going on,
such as declaring a variable in place of a condition.
These more peculiar cases are not covered. See
http:/... |
def _detect_sse3(self):
"Does this compiler support SSE3 intrinsics?"
self._print_support_start('SSE3')
result = self.hasfunction('__m128 v; _mm_hadd_ps(v,v)',
include='<pmmintrin.h>',
extra_postargs=['-msse3'])
self._print_support_en... | def function[_detect_sse3, parameter[self]]:
constant[Does this compiler support SSE3 intrinsics?]
call[name[self]._print_support_start, parameter[constant[SSE3]]]
variable[result] assign[=] call[name[self].hasfunction, parameter[constant[__m128 v; _mm_hadd_ps(v,v)]]]
call[name[self]._pr... | keyword[def] identifier[_detect_sse3] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_print_support_start] ( literal[string] )
identifier[result] = identifier[self] . identifier[hasfunction] ( literal[string] ,
identifier[include] = literal[string] ,
... | def _detect_sse3(self):
"""Does this compiler support SSE3 intrinsics?"""
self._print_support_start('SSE3')
result = self.hasfunction('__m128 v; _mm_hadd_ps(v,v)', include='<pmmintrin.h>', extra_postargs=['-msse3'])
self._print_support_end('SSE3', result)
return result |
def silhouette_n_clusters(data, k_min, k_max, distance='euclidean'):
"""
Computes and plot the silhouette score vs number of clusters graph to help selecting the number of clusters visually
:param data: The data object
:param k_min: lowerbound of the cluster range
:param k_max: ... | def function[silhouette_n_clusters, parameter[data, k_min, k_max, distance]]:
constant[
Computes and plot the silhouette score vs number of clusters graph to help selecting the number of clusters visually
:param data: The data object
:param k_min: lowerbound of the cluster range
... | keyword[def] identifier[silhouette_n_clusters] ( identifier[data] , identifier[k_min] , identifier[k_max] , identifier[distance] = literal[string] ):
literal[string]
identifier[k_range] = identifier[range] ( identifier[k_min] , identifier[k_max] )
identifier[k_means_var] =[ identifier[Clu... | def silhouette_n_clusters(data, k_min, k_max, distance='euclidean'):
"""
Computes and plot the silhouette score vs number of clusters graph to help selecting the number of clusters visually
:param data: The data object
:param k_min: lowerbound of the cluster range
:param k_max: uppe... |
def _make_unknown_name(self, cursor):
'''Creates a name for unname type'''
parent = cursor.lexical_parent
pname = self.get_unique_name(parent)
log.debug('_make_unknown_name: Got parent get_unique_name %s',pname)
# we only look at types declarations
_cursor_decl = cursor.t... | def function[_make_unknown_name, parameter[self, cursor]]:
constant[Creates a name for unname type]
variable[parent] assign[=] name[cursor].lexical_parent
variable[pname] assign[=] call[name[self].get_unique_name, parameter[name[parent]]]
call[name[log].debug, parameter[constant[_make_un... | keyword[def] identifier[_make_unknown_name] ( identifier[self] , identifier[cursor] ):
literal[string]
identifier[parent] = identifier[cursor] . identifier[lexical_parent]
identifier[pname] = identifier[self] . identifier[get_unique_name] ( identifier[parent] )
identifier[log] . ... | def _make_unknown_name(self, cursor):
"""Creates a name for unname type"""
parent = cursor.lexical_parent
pname = self.get_unique_name(parent)
log.debug('_make_unknown_name: Got parent get_unique_name %s', pname)
# we only look at types declarations
_cursor_decl = cursor.type.get_declaration()
... |
def iter_descendants(self, strategy="levelorder", is_leaf_fn=None):
""" Returns an iterator over all descendant nodes."""
for n in self.traverse(strategy=strategy, is_leaf_fn=is_leaf_fn):
if n is not self:
yield n | def function[iter_descendants, parameter[self, strategy, is_leaf_fn]]:
constant[ Returns an iterator over all descendant nodes.]
for taget[name[n]] in starred[call[name[self].traverse, parameter[]]] begin[:]
if compare[name[n] is_not name[self]] begin[:]
<ast.Yiel... | keyword[def] identifier[iter_descendants] ( identifier[self] , identifier[strategy] = literal[string] , identifier[is_leaf_fn] = keyword[None] ):
literal[string]
keyword[for] identifier[n] keyword[in] identifier[self] . identifier[traverse] ( identifier[strategy] = identifier[strategy] , identif... | def iter_descendants(self, strategy='levelorder', is_leaf_fn=None):
""" Returns an iterator over all descendant nodes."""
for n in self.traverse(strategy=strategy, is_leaf_fn=is_leaf_fn):
if n is not self:
yield n # depends on [control=['if'], data=['n']] # depends on [control=['for'], dat... |
def tensormul(tensor0: BKTensor, tensor1: BKTensor,
indices: typing.List[int]) -> BKTensor:
r"""
Generalization of matrix multiplication to product tensors.
A state vector in product tensor representation has N dimension, one for
each contravariant index, e.g. for 3-qubit states
:math... | def function[tensormul, parameter[tensor0, tensor1, indices]]:
constant[
Generalization of matrix multiplication to product tensors.
A state vector in product tensor representation has N dimension, one for
each contravariant index, e.g. for 3-qubit states
:math:`B^{b_0,b_1,b_2}`. An operator ha... | keyword[def] identifier[tensormul] ( identifier[tensor0] : identifier[BKTensor] , identifier[tensor1] : identifier[BKTensor] ,
identifier[indices] : identifier[typing] . identifier[List] [ identifier[int] ])-> identifier[BKTensor] :
literal[string]
... | def tensormul(tensor0: BKTensor, tensor1: BKTensor, indices: typing.List[int]) -> BKTensor:
"""
Generalization of matrix multiplication to product tensors.
A state vector in product tensor representation has N dimension, one for
each contravariant index, e.g. for 3-qubit states
:math:`B^{b_0,b_1,b_... |
def reorder_indices(self, indices_order):
'reorder all the indices'
# allow mixed index syntax like int
indices_order, single = convert_index_to_keys(self.indices, indices_order)
old_indices = force_list(self.indices.keys())
if indices_order == old_indices: # no changes
... | def function[reorder_indices, parameter[self, indices_order]]:
constant[reorder all the indices]
<ast.Tuple object at 0x7da2044c3310> assign[=] call[name[convert_index_to_keys], parameter[name[self].indices, name[indices_order]]]
variable[old_indices] assign[=] call[name[force_list], parameter[c... | keyword[def] identifier[reorder_indices] ( identifier[self] , identifier[indices_order] ):
literal[string]
identifier[indices_order] , identifier[single] = identifier[convert_index_to_keys] ( identifier[self] . identifier[indices] , identifier[indices_order] )
identifier[old_indic... | def reorder_indices(self, indices_order):
"""reorder all the indices"""
# allow mixed index syntax like int
(indices_order, single) = convert_index_to_keys(self.indices, indices_order)
old_indices = force_list(self.indices.keys())
if indices_order == old_indices: # no changes
return # depe... |
def pos_tags(self):
"""Returns an list of tuples of the form (word, POS tag).
Example:
::
[('At', 'IN'), ('eight', 'CD'), ("o'clock", 'JJ'), ('on', 'IN'),
('Thursday', 'NNP'), ('morning', 'NN')]
:rtype: list of tuples
"""
return [(Word(... | def function[pos_tags, parameter[self]]:
constant[Returns an list of tuples of the form (word, POS tag).
Example:
::
[('At', 'IN'), ('eight', 'CD'), ("o'clock", 'JJ'), ('on', 'IN'),
('Thursday', 'NNP'), ('morning', 'NN')]
:rtype: list of tuples
... | keyword[def] identifier[pos_tags] ( identifier[self] ):
literal[string]
keyword[return] [( identifier[Word] ( identifier[word] , identifier[pos_tag] = identifier[t] ), identifier[unicode] ( identifier[t] ))
keyword[for] identifier[word] , identifier[t] keyword[in] identifier[self] . ide... | def pos_tags(self):
"""Returns an list of tuples of the form (word, POS tag).
Example:
::
[('At', 'IN'), ('eight', 'CD'), ("o'clock", 'JJ'), ('on', 'IN'),
('Thursday', 'NNP'), ('morning', 'NN')]
:rtype: list of tuples
"""
# new keyword PatternT... |
def serialize_to_json(data, **kwargs):
"""
A wrapper for simplejson.dumps with defaults as:
cls=LazyJSONEncoder
All arguments can be added via kwargs
"""
kwargs['cls'] = kwargs.get('cls', LazyJSONEncoder)
return json.dumps(data, **kwargs) | def function[serialize_to_json, parameter[data]]:
constant[
A wrapper for simplejson.dumps with defaults as:
cls=LazyJSONEncoder
All arguments can be added via kwargs
]
call[name[kwargs]][constant[cls]] assign[=] call[name[kwargs].get, parameter[constant[cls], name[LazyJSONEncoder]]]
... | keyword[def] identifier[serialize_to_json] ( identifier[data] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= identifier[kwargs] . identifier[get] ( literal[string] , identifier[LazyJSONEncoder] )
keyword[return] identifier[json] . identifier[dumps] ( identifier[dat... | def serialize_to_json(data, **kwargs):
"""
A wrapper for simplejson.dumps with defaults as:
cls=LazyJSONEncoder
All arguments can be added via kwargs
"""
kwargs['cls'] = kwargs.get('cls', LazyJSONEncoder)
return json.dumps(data, **kwargs) |
def requires_public_key(func):
"""
Decorator for functions that require the public key to be defined. By definition, this includes the private key, as such, it's enough to use this to effect definition of both public and private key.
"""
def func_wrapper(self, *args, **kwargs):
if hasattr(self,... | def function[requires_public_key, parameter[func]]:
constant[
Decorator for functions that require the public key to be defined. By definition, this includes the private key, as such, it's enough to use this to effect definition of both public and private key.
]
def function[func_wrapper, parame... | keyword[def] identifier[requires_public_key] ( identifier[func] ):
literal[string]
keyword[def] identifier[func_wrapper] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ):
identifier[func] ( ident... | def requires_public_key(func):
"""
Decorator for functions that require the public key to be defined. By definition, this includes the private key, as such, it's enough to use this to effect definition of both public and private key.
"""
def func_wrapper(self, *args, **kwargs):
if hasattr(self,... |
def to_markov_model(self):
"""
Converts bayesian model to markov model. The markov model created would
be the moral graph of the bayesian model.
Examples
--------
>>> from pgmpy.models import BayesianModel
>>> G = BayesianModel([('diff', 'grade'), ('intel', 'grad... | def function[to_markov_model, parameter[self]]:
constant[
Converts bayesian model to markov model. The markov model created would
be the moral graph of the bayesian model.
Examples
--------
>>> from pgmpy.models import BayesianModel
>>> G = BayesianModel([('diff'... | keyword[def] identifier[to_markov_model] ( identifier[self] ):
literal[string]
identifier[moral_graph] = identifier[self] . identifier[moralize] ()
identifier[mm] = identifier[MarkovModel] ( identifier[moral_graph] . identifier[edges] ())
identifier[mm] . identifier[add_factors] (... | def to_markov_model(self):
"""
Converts bayesian model to markov model. The markov model created would
be the moral graph of the bayesian model.
Examples
--------
>>> from pgmpy.models import BayesianModel
>>> G = BayesianModel([('diff', 'grade'), ('intel', 'grade'),... |
def on_mouse_motion(self, x, y, dx, dy):
"""
Pyglet specific mouse motion callback.
Forwards and traslates the event to :py:func:`cursor_event`
"""
# screen coordinates relative to the lower-left corner
self.cursor_event(x, self.buffer_height - y, dx, dy) | def function[on_mouse_motion, parameter[self, x, y, dx, dy]]:
constant[
Pyglet specific mouse motion callback.
Forwards and traslates the event to :py:func:`cursor_event`
]
call[name[self].cursor_event, parameter[name[x], binary_operation[name[self].buffer_height - name[y]], name... | keyword[def] identifier[on_mouse_motion] ( identifier[self] , identifier[x] , identifier[y] , identifier[dx] , identifier[dy] ):
literal[string]
identifier[self] . identifier[cursor_event] ( identifier[x] , identifier[self] . identifier[buffer_height] - identifier[y] , identifier[dx] , ... | def on_mouse_motion(self, x, y, dx, dy):
"""
Pyglet specific mouse motion callback.
Forwards and traslates the event to :py:func:`cursor_event`
""" # screen coordinates relative to the lower-left corner
self.cursor_event(x, self.buffer_height - y, dx, dy) |
def run(script, args='', **kwargs):
'''Execute specified script using bash. This action accepts common action arguments such as
input, active, workdir, docker_image and args. In particular, content of one or more files
specified by option input would be prepended before the specified script.'''
if sys.p... | def function[run, parameter[script, args]]:
constant[Execute specified script using bash. This action accepts common action arguments such as
input, active, workdir, docker_image and args. In particular, content of one or more files
specified by option input would be prepended before the specified scrip... | keyword[def] identifier[run] ( identifier[script] , identifier[args] = literal[string] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[sys] . identifier[platform] == literal[string] :
identifier[interpreter] = literal[string]
keyword[else] :
key... | def run(script, args='', **kwargs):
"""Execute specified script using bash. This action accepts common action arguments such as
input, active, workdir, docker_image and args. In particular, content of one or more files
specified by option input would be prepended before the specified script."""
if sys.p... |
def remove(self, w):
"""
Removes a word from the vocab. The indices are unchanged.
"""
if w not in self.f2i:
raise ValueError("'{}' does not exist.".format(w))
if w in self.reserved:
raise ValueError("'{}' is one of the reserved words, and thus"
... | def function[remove, parameter[self, w]]:
constant[
Removes a word from the vocab. The indices are unchanged.
]
if compare[name[w] <ast.NotIn object at 0x7da2590d7190> name[self].f2i] begin[:]
<ast.Raise object at 0x7da1b1ffa740>
if compare[name[w] in name[self].reserved]... | keyword[def] identifier[remove] ( identifier[self] , identifier[w] ):
literal[string]
keyword[if] identifier[w] keyword[not] keyword[in] identifier[self] . identifier[f2i] :
keyword[raise] identifier[ValueError] ( literal[string] . identifier[format] ( identifier[w] ))
k... | def remove(self, w):
"""
Removes a word from the vocab. The indices are unchanged.
"""
if w not in self.f2i:
raise ValueError("'{}' does not exist.".format(w)) # depends on [control=['if'], data=['w']]
if w in self.reserved:
raise ValueError("'{}' is one of the reserved word... |
def wait_until_exit(self):
""" Wait until all the threads are finished.
"""
[t.join() for t in self.threads]
self.threads = list() | def function[wait_until_exit, parameter[self]]:
constant[ Wait until all the threads are finished.
]
<ast.ListComp object at 0x7da1b0404790>
name[self].threads assign[=] call[name[list], parameter[]] | keyword[def] identifier[wait_until_exit] ( identifier[self] ):
literal[string]
[ identifier[t] . identifier[join] () keyword[for] identifier[t] keyword[in] identifier[self] . identifier[threads] ]
identifier[self] . identifier[threads] = identifier[list] () | def wait_until_exit(self):
""" Wait until all the threads are finished.
"""
[t.join() for t in self.threads]
self.threads = list() |
def process_text(text, out_file='sofia_output.json', auth=None):
"""Return processor by processing text given as a string.
Parameters
----------
text : str
A string containing the text to be processed with Sofia.
out_file : Optional[str]
The path to a file to save the reader's outpu... | def function[process_text, parameter[text, out_file, auth]]:
constant[Return processor by processing text given as a string.
Parameters
----------
text : str
A string containing the text to be processed with Sofia.
out_file : Optional[str]
The path to a file to save the reader's... | keyword[def] identifier[process_text] ( identifier[text] , identifier[out_file] = literal[string] , identifier[auth] = keyword[None] ):
literal[string]
identifier[text_json] ={ literal[string] : identifier[text] }
keyword[if] keyword[not] identifier[auth] :
identifier[user] , identifier[pas... | def process_text(text, out_file='sofia_output.json', auth=None):
"""Return processor by processing text given as a string.
Parameters
----------
text : str
A string containing the text to be processed with Sofia.
out_file : Optional[str]
The path to a file to save the reader's outpu... |
def sendGame(self, chat_id, game_short_name,
disable_notification=None,
reply_to_message_id=None,
reply_markup=None):
""" See: https://core.telegram.org/bots/api#sendgame """
p = _strip(locals())
return self._api_request('sendGame', _rectify(p)) | def function[sendGame, parameter[self, chat_id, game_short_name, disable_notification, reply_to_message_id, reply_markup]]:
constant[ See: https://core.telegram.org/bots/api#sendgame ]
variable[p] assign[=] call[name[_strip], parameter[call[name[locals], parameter[]]]]
return[call[name[self]._api_re... | keyword[def] identifier[sendGame] ( identifier[self] , identifier[chat_id] , identifier[game_short_name] ,
identifier[disable_notification] = keyword[None] ,
identifier[reply_to_message_id] = keyword[None] ,
identifier[reply_markup] = keyword[None] ):
literal[string]
identifier[p] = identifier[_... | def sendGame(self, chat_id, game_short_name, disable_notification=None, reply_to_message_id=None, reply_markup=None):
""" See: https://core.telegram.org/bots/api#sendgame """
p = _strip(locals())
return self._api_request('sendGame', _rectify(p)) |
def filter_query(self, query, field, value):
"""Filter a query."""
return query.where(field ** "%{}%".format(value.lower())) | def function[filter_query, parameter[self, query, field, value]]:
constant[Filter a query.]
return[call[name[query].where, parameter[binary_operation[name[field] ** call[constant[%{}%].format, parameter[call[name[value].lower, parameter[]]]]]]]] | keyword[def] identifier[filter_query] ( identifier[self] , identifier[query] , identifier[field] , identifier[value] ):
literal[string]
keyword[return] identifier[query] . identifier[where] ( identifier[field] ** literal[string] . identifier[format] ( identifier[value] . identifier[lower] ())) | def filter_query(self, query, field, value):
"""Filter a query."""
return query.where(field ** '%{}%'.format(value.lower())) |
def authenticate(self, request, username=None, password=None):
"""
Check credentials against RADIUS server and return a User object or
None.
"""
if isinstance(username, basestring):
username = username.encode('utf-8')
if isinstance(password, basestring):
... | def function[authenticate, parameter[self, request, username, password]]:
constant[
Check credentials against RADIUS server and return a User object or
None.
]
if call[name[isinstance], parameter[name[username], name[basestring]]] begin[:]
variable[username] assig... | keyword[def] identifier[authenticate] ( identifier[self] , identifier[request] , identifier[username] = keyword[None] , identifier[password] = keyword[None] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[username] , identifier[basestring] ):
identifier[username] = ... | def authenticate(self, request, username=None, password=None):
"""
Check credentials against RADIUS server and return a User object or
None.
"""
if isinstance(username, basestring):
username = username.encode('utf-8') # depends on [control=['if'], data=[]]
if isinstance(pass... |
def orbit(self, orbit):
"""Initialize the propagator
Args:
orbit (Orbit)
"""
self._orbit = orbit
tle = Tle.from_orbit(orbit)
lines = tle.text.splitlines()
if len(lines) == 3:
_, line1, line2 = lines
else:
line1, line2... | def function[orbit, parameter[self, orbit]]:
constant[Initialize the propagator
Args:
orbit (Orbit)
]
name[self]._orbit assign[=] name[orbit]
variable[tle] assign[=] call[name[Tle].from_orbit, parameter[name[orbit]]]
variable[lines] assign[=] call[name[tle].t... | keyword[def] identifier[orbit] ( identifier[self] , identifier[orbit] ):
literal[string]
identifier[self] . identifier[_orbit] = identifier[orbit]
identifier[tle] = identifier[Tle] . identifier[from_orbit] ( identifier[orbit] )
identifier[lines] = identifier[tle] . identifier[te... | def orbit(self, orbit):
"""Initialize the propagator
Args:
orbit (Orbit)
"""
self._orbit = orbit
tle = Tle.from_orbit(orbit)
lines = tle.text.splitlines()
if len(lines) == 3:
(_, line1, line2) = lines # depends on [control=['if'], data=[]]
else:
(lin... |
def intersection(self, coordinates, objects=False):
"""Return ids or objects in the index that intersect the given
coordinates.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's dimension * 2 coordi... | def function[intersection, parameter[self, coordinates, objects]]:
constant[Return ids or objects in the index that intersect the given
coordinates.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's... | keyword[def] identifier[intersection] ( identifier[self] , identifier[coordinates] , identifier[objects] = keyword[False] ):
literal[string]
keyword[if] identifier[objects] :
keyword[return] identifier[self] . identifier[_intersection_obj] ( identifier[coordinates] , identifier[obje... | def intersection(self, coordinates, objects=False):
"""Return ids or objects in the index that intersect the given
coordinates.
:param coordinates: sequence or array
This may be an object that satisfies the numpy array
protocol, providing the index's dimension * 2 coordinate... |
def process_log_record(self, log_record):
"""Add customer record keys and rename threadName key."""
log_record["version"] = __version__
log_record["program"] = PROGRAM_NAME
log_record["service_name"] = log_record.pop('threadName', None)
# return jsonlogger.JsonFormatter.process_l... | def function[process_log_record, parameter[self, log_record]]:
constant[Add customer record keys and rename threadName key.]
call[name[log_record]][constant[version]] assign[=] name[__version__]
call[name[log_record]][constant[program]] assign[=] name[PROGRAM_NAME]
call[name[log_record]]... | keyword[def] identifier[process_log_record] ( identifier[self] , identifier[log_record] ):
literal[string]
identifier[log_record] [ literal[string] ]= identifier[__version__]
identifier[log_record] [ literal[string] ]= identifier[PROGRAM_NAME]
identifier[log_record] [ literal[st... | def process_log_record(self, log_record):
"""Add customer record keys and rename threadName key."""
log_record['version'] = __version__
log_record['program'] = PROGRAM_NAME
log_record['service_name'] = log_record.pop('threadName', None)
# return jsonlogger.JsonFormatter.process_log_record(self, log_... |
def to_point(self, timestamp):
"""Get a Point conversion of this aggregation.
:type timestamp: :class: `datetime.datetime`
:param timestamp: The time to report the point as having been recorded.
:rtype: :class: `opencensus.metrics.export.point.Point`
:return: a :class: `opencen... | def function[to_point, parameter[self, timestamp]]:
constant[Get a Point conversion of this aggregation.
:type timestamp: :class: `datetime.datetime`
:param timestamp: The time to report the point as having been recorded.
:rtype: :class: `opencensus.metrics.export.point.Point`
... | keyword[def] identifier[to_point] ( identifier[self] , identifier[timestamp] ):
literal[string]
keyword[return] identifier[point] . identifier[Point] ( identifier[value] . identifier[ValueLong] ( identifier[self] . identifier[count_data] ), identifier[timestamp] ) | def to_point(self, timestamp):
"""Get a Point conversion of this aggregation.
:type timestamp: :class: `datetime.datetime`
:param timestamp: The time to report the point as having been recorded.
:rtype: :class: `opencensus.metrics.export.point.Point`
:return: a :class: `opencensus.... |
def __check_submodules(self):
"""
Verify that the submodules are checked out and clean.
"""
if not os.path.exists('.git'):
return
with open('.gitmodules') as f:
for l in f:
if 'path' in l:
p = l.split('=')[-1].strip()
... | def function[__check_submodules, parameter[self]]:
constant[
Verify that the submodules are checked out and clean.
]
if <ast.UnaryOp object at 0x7da18f58c0d0> begin[:]
return[None]
with call[name[open], parameter[constant[.gitmodules]]] begin[:]
for taget[... | keyword[def] identifier[__check_submodules] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( literal[string] ):
keyword[return]
keyword[with] identifier[open] ( literal[string] ) keyword[as] identifier... | def __check_submodules(self):
"""
Verify that the submodules are checked out and clean.
"""
if not os.path.exists('.git'):
return # depends on [control=['if'], data=[]]
with open('.gitmodules') as f:
for l in f:
if 'path' in l:
p = l.split('=')[-1... |
async def request(self, value: Any) -> Any:
"""\
Sends a command to and receives the reply from the task.
"""
await self.send(value)
return await self.recv() | <ast.AsyncFunctionDef object at 0x7da18bccac80> | keyword[async] keyword[def] identifier[request] ( identifier[self] , identifier[value] : identifier[Any] )-> identifier[Any] :
literal[string]
keyword[await] identifier[self] . identifier[send] ( identifier[value] )
keyword[return] keyword[await] identifier[self] . identifier[recv] () | async def request(self, value: Any) -> Any:
""" Sends a command to and receives the reply from the task.
"""
await self.send(value)
return await self.recv() |
def apply(cls, args, run):
"""Add priority info for this run."""
try:
priority = float(args)
except ValueError:
raise ValueError("The PRIORITY argument must be a number! "
"(but was '{}')".format(args))
run.meta_info['priority'] = prio... | def function[apply, parameter[cls, args, run]]:
constant[Add priority info for this run.]
<ast.Try object at 0x7da1b18fa590>
call[name[run].meta_info][constant[priority]] assign[=] name[priority] | keyword[def] identifier[apply] ( identifier[cls] , identifier[args] , identifier[run] ):
literal[string]
keyword[try] :
identifier[priority] = identifier[float] ( identifier[args] )
keyword[except] identifier[ValueError] :
keyword[raise] identifier[ValueError] (... | def apply(cls, args, run):
"""Add priority info for this run."""
try:
priority = float(args) # depends on [control=['try'], data=[]]
except ValueError:
raise ValueError("The PRIORITY argument must be a number! (but was '{}')".format(args)) # depends on [control=['except'], data=[]]
run... |
def predict_expectation(self, X):
"""
Compute the expected lifetime, E[T], using covariates X.
Parameters
----------
X: a (n,d) covariate numpy array or DataFrame
If a DataFrame, columns
can be in any order. If a numpy array, columns must be in the
... | def function[predict_expectation, parameter[self, X]]:
constant[
Compute the expected lifetime, E[T], using covariates X.
Parameters
----------
X: a (n,d) covariate numpy array or DataFrame
If a DataFrame, columns
can be in any order. If a numpy array, co... | keyword[def] identifier[predict_expectation] ( identifier[self] , identifier[X] ):
literal[string]
identifier[index] = identifier[_get_index] ( identifier[X] )
identifier[t] = identifier[self] . identifier[_index]
keyword[return] identifier[pd] . identifier[DataFrame] ( identifi... | def predict_expectation(self, X):
"""
Compute the expected lifetime, E[T], using covariates X.
Parameters
----------
X: a (n,d) covariate numpy array or DataFrame
If a DataFrame, columns
can be in any order. If a numpy array, columns must be in the
... |
def _make_dynamic(self, hmap, dynamic_fn, streams):
"""
Accepts a HoloMap and a dynamic callback function creating
an equivalent DynamicMap from the HoloMap.
"""
if isinstance(hmap, ViewableElement):
return DynamicMap(dynamic_fn, streams=streams)
dim_values = ... | def function[_make_dynamic, parameter[self, hmap, dynamic_fn, streams]]:
constant[
Accepts a HoloMap and a dynamic callback function creating
an equivalent DynamicMap from the HoloMap.
]
if call[name[isinstance], parameter[name[hmap], name[ViewableElement]]] begin[:]
retu... | keyword[def] identifier[_make_dynamic] ( identifier[self] , identifier[hmap] , identifier[dynamic_fn] , identifier[streams] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[hmap] , identifier[ViewableElement] ):
keyword[return] identifier[DynamicMap] ( identifier[dy... | def _make_dynamic(self, hmap, dynamic_fn, streams):
"""
Accepts a HoloMap and a dynamic callback function creating
an equivalent DynamicMap from the HoloMap.
"""
if isinstance(hmap, ViewableElement):
return DynamicMap(dynamic_fn, streams=streams) # depends on [control=['if'], da... |
def build_args():
"""Create command line argument parser."""
parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('recipe', type=str, help="The recipe file to load and run.")
parser.add_argument('-d', '--define', action="appe... | def function[build_args, parameter[]]:
constant[Create command line argument parser.]
variable[parser] assign[=] call[name[argparse].ArgumentParser, parameter[]]
call[name[parser].add_argument, parameter[constant[recipe]]]
call[name[parser].add_argument, parameter[constant[-d], constant[... | keyword[def] identifier[build_args] ():
literal[string]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] ( identifier[description] = identifier[DESCRIPTION] , identifier[formatter_class] = identifier[argparse] . identifier[RawDescriptionHelpFormatter] )
identifier[parser] . ident... | def build_args():
"""Create command line argument parser."""
parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('recipe', type=str, help='The recipe file to load and run.')
parser.add_argument('-d', '--define', action='appe... |
def get_serializer(context):
"""Returns a serializer for a given context"""
cluster_config = context.get_cluster_config()
serializer_clsname = cluster_config.get(constants.TOPOLOGY_SERIALIZER_CLASSNAME, None)
if serializer_clsname is None:
return PythonSerializer()
else:
try:
top... | def function[get_serializer, parameter[context]]:
constant[Returns a serializer for a given context]
variable[cluster_config] assign[=] call[name[context].get_cluster_config, parameter[]]
variable[serializer_clsname] assign[=] call[name[cluster_config].get, parameter[name[constants].TOPOLOGY_SER... | keyword[def] identifier[get_serializer] ( identifier[context] ):
literal[string]
identifier[cluster_config] = identifier[context] . identifier[get_cluster_config] ()
identifier[serializer_clsname] = identifier[cluster_config] . identifier[get] ( identifier[constants] . identifier[TOPOLOGY_SERIALIZER_C... | def get_serializer(context):
"""Returns a serializer for a given context"""
cluster_config = context.get_cluster_config()
serializer_clsname = cluster_config.get(constants.TOPOLOGY_SERIALIZER_CLASSNAME, None)
if serializer_clsname is None:
return PythonSerializer() # depends on [control=['if'],... |
def get_pluggable_module_information(self, id_or_uri):
"""
Gets all the pluggable module information.
Args:
id_or_uri: Can be either the interconnect id or uri.
Returns:
array: dicts of the pluggable module information.
"""
uri = self._client.bui... | def function[get_pluggable_module_information, parameter[self, id_or_uri]]:
constant[
Gets all the pluggable module information.
Args:
id_or_uri: Can be either the interconnect id or uri.
Returns:
array: dicts of the pluggable module information.
]
... | keyword[def] identifier[get_pluggable_module_information] ( identifier[self] , identifier[id_or_uri] ):
literal[string]
identifier[uri] = identifier[self] . identifier[_client] . identifier[build_uri] ( identifier[id_or_uri] )+ literal[string]
keyword[return] identifier[self] . identifie... | def get_pluggable_module_information(self, id_or_uri):
"""
Gets all the pluggable module information.
Args:
id_or_uri: Can be either the interconnect id or uri.
Returns:
array: dicts of the pluggable module information.
"""
uri = self._client.build_uri(i... |
def is_legal_object(self, data_type: str) -> bool:
"""
Do data_type validation according to the rules of the XML xsd schema.
Args:
data_type:
Returns:
"""
data_type = str(data_type)
ranges = self.included_ranges()
return not ranges or data_t... | def function[is_legal_object, parameter[self, data_type]]:
constant[
Do data_type validation according to the rules of the XML xsd schema.
Args:
data_type:
Returns:
]
variable[data_type] assign[=] call[name[str], parameter[name[data_type]]]
variable... | keyword[def] identifier[is_legal_object] ( identifier[self] , identifier[data_type] : identifier[str] )-> identifier[bool] :
literal[string]
identifier[data_type] = identifier[str] ( identifier[data_type] )
identifier[ranges] = identifier[self] . identifier[included_ranges] ()
key... | def is_legal_object(self, data_type: str) -> bool:
"""
Do data_type validation according to the rules of the XML xsd schema.
Args:
data_type:
Returns:
"""
data_type = str(data_type)
ranges = self.included_ranges()
return not ranges or data_type in ranges or... |
def to_dictionary(self):
"""Serialize an object into dictionary form. Useful if you have to
serialize an array of objects into JSON. Otherwise, if you call the
:meth:`to_json` method on each object in the list and then try to
dump the array, you end up with an array with one string."""... | def function[to_dictionary, parameter[self]]:
constant[Serialize an object into dictionary form. Useful if you have to
serialize an array of objects into JSON. Otherwise, if you call the
:meth:`to_json` method on each object in the list and then try to
dump the array, you end up with a... | keyword[def] identifier[to_dictionary] ( identifier[self] ):
literal[string]
identifier[j] ={}
keyword[for] identifier[p] keyword[in] identifier[self] . identifier[properties] :
identifier[j] [ identifier[p] ]= identifier[getattr] ( identifier[self] , identifier[p] )
... | def to_dictionary(self):
"""Serialize an object into dictionary form. Useful if you have to
serialize an array of objects into JSON. Otherwise, if you call the
:meth:`to_json` method on each object in the list and then try to
dump the array, you end up with an array with one string."""
... |
def _parse_bands(lines, n_start):
"""Parse band structure from cp2k output"""
kpoints = []
labels = []
bands_s1 = []
bands_s2 = []
known_kpoints = {}
pattern = re.compile(".*?Nr.*?Spin.*?K-Point.*?", re.DOTALL)
selected_lines = lines[n_start:]
for... | def function[_parse_bands, parameter[lines, n_start]]:
constant[Parse band structure from cp2k output]
variable[kpoints] assign[=] list[[]]
variable[labels] assign[=] list[[]]
variable[bands_s1] assign[=] list[[]]
variable[bands_s2] assign[=] list[[]]
variable[known_kpoin... | keyword[def] identifier[_parse_bands] ( identifier[lines] , identifier[n_start] ):
literal[string]
identifier[kpoints] =[]
identifier[labels] =[]
identifier[bands_s1] =[]
identifier[bands_s2] =[]
identifier[known_kpoints] ={}
identifier[pattern] = identi... | def _parse_bands(lines, n_start):
"""Parse band structure from cp2k output"""
kpoints = []
labels = []
bands_s1 = []
bands_s2 = []
known_kpoints = {}
pattern = re.compile('.*?Nr.*?Spin.*?K-Point.*?', re.DOTALL)
selected_lines = lines[n_start:]
for (current_line, line) in enumerate(se... |
def _write_template(upgrade_file, name, depends_on, repository, auto=False):
"""Write template to upgrade file."""
if auto:
# Ensure all models are loaded
from invenio_db import models
list(models)
template_args = produce_upgrade_operations()
operations_str = template_arg... | def function[_write_template, parameter[upgrade_file, name, depends_on, repository, auto]]:
constant[Write template to upgrade file.]
if name[auto] begin[:]
from relative_module[invenio_db] import module[models]
call[name[list], parameter[name[models]]]
variable[t... | keyword[def] identifier[_write_template] ( identifier[upgrade_file] , identifier[name] , identifier[depends_on] , identifier[repository] , identifier[auto] = keyword[False] ):
literal[string]
keyword[if] identifier[auto] :
keyword[from] identifier[invenio_db] keyword[import] identifier[mo... | def _write_template(upgrade_file, name, depends_on, repository, auto=False):
"""Write template to upgrade file."""
if auto:
# Ensure all models are loaded
from invenio_db import models
list(models)
template_args = produce_upgrade_operations()
operations_str = template_arg... |
async def add_relation(self, relation1, relation2):
"""Add a relation between two applications.
:param str relation1: '<application>[:<relation_name>]'
:param str relation2: '<application>[:<relation_name>]'
"""
connection = self.connection()
app_facade = client.Applica... | <ast.AsyncFunctionDef object at 0x7da1b0efa1a0> | keyword[async] keyword[def] identifier[add_relation] ( identifier[self] , identifier[relation1] , identifier[relation2] ):
literal[string]
identifier[connection] = identifier[self] . identifier[connection] ()
identifier[app_facade] = identifier[client] . identifier[ApplicationFacade] . id... | async def add_relation(self, relation1, relation2):
"""Add a relation between two applications.
:param str relation1: '<application>[:<relation_name>]'
:param str relation2: '<application>[:<relation_name>]'
"""
connection = self.connection()
app_facade = client.ApplicationFacade.f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.