code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def get_terms(term_id):
"""Get term(s) using term_id - given term_id may match multiple term records
Term ID has to match either the id, alt_ids or obsolete_ids
"""
search_body = {
"query": {
"bool": {
"should": [
{"term": {"id": term_id}},
... | def function[get_terms, parameter[term_id]]:
constant[Get term(s) using term_id - given term_id may match multiple term records
Term ID has to match either the id, alt_ids or obsolete_ids
]
variable[search_body] assign[=] dictionary[[<ast.Constant object at 0x7da1b19ccfd0>], [<ast.Dict object a... | keyword[def] identifier[get_terms] ( identifier[term_id] ):
literal[string]
identifier[search_body] ={
literal[string] :{
literal[string] :{
literal[string] :[
{ literal[string] :{ literal[string] : identifier[term_id] }},
{ literal[string] :{ literal[string] : identifier[term_id] }... | def get_terms(term_id):
"""Get term(s) using term_id - given term_id may match multiple term records
Term ID has to match either the id, alt_ids or obsolete_ids
"""
search_body = {'query': {'bool': {'should': [{'term': {'id': term_id}}, {'term': {'alt_ids': term_id}}, {'term': {'obsolete_ids': term_id}... |
def _plot_generic(self, filename=None):
"""Plots the current state of the shell, saving the value to the specified file
if specified.
"""
#Since the filename is being passed directly from the argument, check its validity.
if filename == "":
filename = None
if... | def function[_plot_generic, parameter[self, filename]]:
constant[Plots the current state of the shell, saving the value to the specified file
if specified.
]
if compare[name[filename] equal[==] constant[]] begin[:]
variable[filename] assign[=] constant[None]
if co... | keyword[def] identifier[_plot_generic] ( identifier[self] , identifier[filename] = keyword[None] ):
literal[string]
keyword[if] identifier[filename] == literal[string] :
identifier[filename] = keyword[None]
keyword[if] literal[string] keyword[not] keyword[in] i... | def _plot_generic(self, filename=None):
"""Plots the current state of the shell, saving the value to the specified file
if specified.
"""
#Since the filename is being passed directly from the argument, check its validity.
if filename == '':
filename = None # depends on [control=['if... |
def CreateControls(self):
"""Create our sub-controls"""
wx.EVT_LIST_COL_CLICK(self, self.GetId(), self.OnReorder)
wx.EVT_LIST_ITEM_SELECTED(self, self.GetId(), self.OnNodeSelected)
wx.EVT_MOTION(self, self.OnMouseMove)
wx.EVT_LIST_ITEM_ACTIVATED(self, self.GetId(), self.OnNodeAct... | def function[CreateControls, parameter[self]]:
constant[Create our sub-controls]
call[name[wx].EVT_LIST_COL_CLICK, parameter[name[self], call[name[self].GetId, parameter[]], name[self].OnReorder]]
call[name[wx].EVT_LIST_ITEM_SELECTED, parameter[name[self], call[name[self].GetId, parameter[]], na... | keyword[def] identifier[CreateControls] ( identifier[self] ):
literal[string]
identifier[wx] . identifier[EVT_LIST_COL_CLICK] ( identifier[self] , identifier[self] . identifier[GetId] (), identifier[self] . identifier[OnReorder] )
identifier[wx] . identifier[EVT_LIST_ITEM_SELECTED] ( ident... | def CreateControls(self):
"""Create our sub-controls"""
wx.EVT_LIST_COL_CLICK(self, self.GetId(), self.OnReorder)
wx.EVT_LIST_ITEM_SELECTED(self, self.GetId(), self.OnNodeSelected)
wx.EVT_MOTION(self, self.OnMouseMove)
wx.EVT_LIST_ITEM_ACTIVATED(self, self.GetId(), self.OnNodeActivated)
self.Cre... |
async def fetch_lightpad(self, lpid):
"""Lookup details for a given lightpad"""
url = "https://production.plum.technology/v2/getLightpad"
data = {"lpid": lpid}
return await self.__post(url, data) | <ast.AsyncFunctionDef object at 0x7da1b14d7130> | keyword[async] keyword[def] identifier[fetch_lightpad] ( identifier[self] , identifier[lpid] ):
literal[string]
identifier[url] = literal[string]
identifier[data] ={ literal[string] : identifier[lpid] }
keyword[return] keyword[await] identifier[self] . identifier[__post] ( ide... | async def fetch_lightpad(self, lpid):
"""Lookup details for a given lightpad"""
url = 'https://production.plum.technology/v2/getLightpad'
data = {'lpid': lpid}
return await self.__post(url, data) |
def list_attached_storage_groups(self, full_properties=False):
"""
Return the storage groups that are attached to this partition.
The CPC must have the "dpm-storage-management" feature enabled.
Authorization requirements:
* Object-access permission to this partition.
*... | def function[list_attached_storage_groups, parameter[self, full_properties]]:
constant[
Return the storage groups that are attached to this partition.
The CPC must have the "dpm-storage-management" feature enabled.
Authorization requirements:
* Object-access permission to this... | keyword[def] identifier[list_attached_storage_groups] ( identifier[self] , identifier[full_properties] = keyword[False] ):
literal[string]
identifier[sg_list] =[]
identifier[sg_uris] = identifier[self] . identifier[get_property] ( literal[string] )
keyword[if] identifier[sg_uris]... | def list_attached_storage_groups(self, full_properties=False):
"""
Return the storage groups that are attached to this partition.
The CPC must have the "dpm-storage-management" feature enabled.
Authorization requirements:
* Object-access permission to this partition.
* Tas... |
def reorder(self, handle, low_value):
"""
Move an item, specified by handle, into position in a sorted list. Uses
the item comparator, if any, to determine the new location. If low_value
is true, starts searching from the start of the list, otherwise searches
from the end.
"""
return lib... | def function[reorder, parameter[self, handle, low_value]]:
constant[
Move an item, specified by handle, into position in a sorted list. Uses
the item comparator, if any, to determine the new location. If low_value
is true, starts searching from the start of the list, otherwise searches
from the end.
... | keyword[def] identifier[reorder] ( identifier[self] , identifier[handle] , identifier[low_value] ):
literal[string]
keyword[return] identifier[lib] . identifier[zlistx_reorder] ( identifier[self] . identifier[_as_parameter_] , identifier[handle] , identifier[low_value] ) | def reorder(self, handle, low_value):
"""
Move an item, specified by handle, into position in a sorted list. Uses
the item comparator, if any, to determine the new location. If low_value
is true, starts searching from the start of the list, otherwise searches
from the end.
"""
return lib.zlistx_... |
def process_cell(self, row, column, cell):
"""
对于读模板,只记录格式为 {{xxx}} 的字段
:param cell:
:return: 如果不是第一行,则每列返回{'col':列值, 'field'},否则只返回 {'value':...}
"""
value, field = self.parse_cell(cell)
if value or field:
return {'col':column, 'field':field, 'value'... | def function[process_cell, parameter[self, row, column, cell]]:
constant[
对于读模板,只记录格式为 {{xxx}} 的字段
:param cell:
:return: 如果不是第一行,则每列返回{'col':列值, 'field'},否则只返回 {'value':...}
]
<ast.Tuple object at 0x7da18f720bb0> assign[=] call[name[self].parse_cell, parameter[name[cell]]... | keyword[def] identifier[process_cell] ( identifier[self] , identifier[row] , identifier[column] , identifier[cell] ):
literal[string]
identifier[value] , identifier[field] = identifier[self] . identifier[parse_cell] ( identifier[cell] )
keyword[if] identifier[value] keyword[or] identif... | def process_cell(self, row, column, cell):
"""
对于读模板,只记录格式为 {{xxx}} 的字段
:param cell:
:return: 如果不是第一行,则每列返回{'col':列值, 'field'},否则只返回 {'value':...}
"""
(value, field) = self.parse_cell(cell)
if value or field:
return {'col': column, 'field': field, 'value': value} # d... |
def read_ncbi_gene2go(fin_gene2go, taxids=None, **kws):
"""Read NCBI's gene2go. Return gene2go data for user-specified taxids."""
obj = Gene2GoReader(fin_gene2go, taxids=taxids)
# By default, return id2gos. User can cause go2geneids to be returned by:
# >>> read_ncbi_gene2go(..., go2geneids=True
i... | def function[read_ncbi_gene2go, parameter[fin_gene2go, taxids]]:
constant[Read NCBI's gene2go. Return gene2go data for user-specified taxids.]
variable[obj] assign[=] call[name[Gene2GoReader], parameter[name[fin_gene2go]]]
if compare[constant[taxid2asscs] <ast.NotIn object at 0x7da2590d7190> nam... | keyword[def] identifier[read_ncbi_gene2go] ( identifier[fin_gene2go] , identifier[taxids] = keyword[None] ,** identifier[kws] ):
literal[string]
identifier[obj] = identifier[Gene2GoReader] ( identifier[fin_gene2go] , identifier[taxids] = identifier[taxids] )
keyword[if] literal[string] key... | def read_ncbi_gene2go(fin_gene2go, taxids=None, **kws):
"""Read NCBI's gene2go. Return gene2go data for user-specified taxids."""
obj = Gene2GoReader(fin_gene2go, taxids=taxids)
# By default, return id2gos. User can cause go2geneids to be returned by:
# >>> read_ncbi_gene2go(..., go2geneids=True
i... |
def distort_matrix_X(Z, X, f, new_xmin, new_xmax, subsample=3):
"""
Applies a distortion (remapping) to the matrix Z (and x-values X) using function f.
returns new_Z, new_X
f is an INVERSE function old_x(new_x)
Z is a matrix. X is an array where X[n] is the x-value associated with the array Z[n].
... | def function[distort_matrix_X, parameter[Z, X, f, new_xmin, new_xmax, subsample]]:
constant[
Applies a distortion (remapping) to the matrix Z (and x-values X) using function f.
returns new_Z, new_X
f is an INVERSE function old_x(new_x)
Z is a matrix. X is an array where X[n] is the x-value ass... | keyword[def] identifier[distort_matrix_X] ( identifier[Z] , identifier[X] , identifier[f] , identifier[new_xmin] , identifier[new_xmax] , identifier[subsample] = literal[int] ):
literal[string]
identifier[Z] = identifier[_n] . identifier[array] ( identifier[Z] )
identifier[X] = identifier[_n] . ident... | def distort_matrix_X(Z, X, f, new_xmin, new_xmax, subsample=3):
"""
Applies a distortion (remapping) to the matrix Z (and x-values X) using function f.
returns new_Z, new_X
f is an INVERSE function old_x(new_x)
Z is a matrix. X is an array where X[n] is the x-value associated with the array Z[n].
... |
def load(self, data, size=None):
"""Data is cffi array"""
self.bind()
if size is None:
# ffi's sizeof understands arrays
size = sizeof(data)
if size == self.buffer_size:
# same size - no need to allocate new buffer, just copy
glBufferSubDat... | def function[load, parameter[self, data, size]]:
constant[Data is cffi array]
call[name[self].bind, parameter[]]
if compare[name[size] is constant[None]] begin[:]
variable[size] assign[=] call[name[sizeof], parameter[name[data]]]
if compare[name[size] equal[==] name[self]... | keyword[def] identifier[load] ( identifier[self] , identifier[data] , identifier[size] = keyword[None] ):
literal[string]
identifier[self] . identifier[bind] ()
keyword[if] identifier[size] keyword[is] keyword[None] :
identifier[size] = identifier[sizeof] ( identif... | def load(self, data, size=None):
"""Data is cffi array"""
self.bind()
if size is None:
# ffi's sizeof understands arrays
size = sizeof(data) # depends on [control=['if'], data=['size']]
if size == self.buffer_size:
# same size - no need to allocate new buffer, just copy
... |
def set_bpf_filter_on_all_devices(filterstr):
'''
Long method name, but self-explanatory. Set the bpf
filter on all devices that have been opened.
'''
with PcapLiveDevice._lock:
for dev in PcapLiveDevice._OpenDevices.values():
_PcapFfi.instance()._set... | def function[set_bpf_filter_on_all_devices, parameter[filterstr]]:
constant[
Long method name, but self-explanatory. Set the bpf
filter on all devices that have been opened.
]
with name[PcapLiveDevice]._lock begin[:]
for taget[name[dev]] in starred[call[name[Pcap... | keyword[def] identifier[set_bpf_filter_on_all_devices] ( identifier[filterstr] ):
literal[string]
keyword[with] identifier[PcapLiveDevice] . identifier[_lock] :
keyword[for] identifier[dev] keyword[in] identifier[PcapLiveDevice] . identifier[_OpenDevices] . identifier[values] ():
... | def set_bpf_filter_on_all_devices(filterstr):
"""
Long method name, but self-explanatory. Set the bpf
filter on all devices that have been opened.
"""
with PcapLiveDevice._lock:
for dev in PcapLiveDevice._OpenDevices.values():
_PcapFfi.instance()._set_filter(dev, fil... |
def _set_bypass_lsp(self, v, load=False):
"""
Setter method for bypass_lsp, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/bypass_lsp (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_bypass_lsp is considered as a private
method. Backends lo... | def function[_set_bypass_lsp, parameter[self, v, load]]:
constant[
Setter method for bypass_lsp, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/bypass_lsp (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_bypass_lsp is considered as a privat... | keyword[def] identifier[_set_bypass_lsp] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
ide... | def _set_bypass_lsp(self, v, load=False):
"""
Setter method for bypass_lsp, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/bypass_lsp (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_bypass_lsp is considered as a private
method. Backends lo... |
def unapply_top_patch(self, force=False):
""" Unapply top patch """
self._check(force)
patch = self.db.top_patch()
self._unapply_patch(patch)
self.db.save()
self.unapplied(self.db.top_patch()) | def function[unapply_top_patch, parameter[self, force]]:
constant[ Unapply top patch ]
call[name[self]._check, parameter[name[force]]]
variable[patch] assign[=] call[name[self].db.top_patch, parameter[]]
call[name[self]._unapply_patch, parameter[name[patch]]]
call[name[self].db.s... | keyword[def] identifier[unapply_top_patch] ( identifier[self] , identifier[force] = keyword[False] ):
literal[string]
identifier[self] . identifier[_check] ( identifier[force] )
identifier[patch] = identifier[self] . identifier[db] . identifier[top_patch] ()
identifier[self] . id... | def unapply_top_patch(self, force=False):
""" Unapply top patch """
self._check(force)
patch = self.db.top_patch()
self._unapply_patch(patch)
self.db.save()
self.unapplied(self.db.top_patch()) |
def release_dynamips_id(self, project_id, dynamips_id):
"""
A Dynamips id can be reused by another VM
:param project_id: UUID of the project
:param dynamips_id: Asked id
"""
self._dynamips_ids.setdefault(project_id, set())
if dynamips_id in self._dynamips_ids[pro... | def function[release_dynamips_id, parameter[self, project_id, dynamips_id]]:
constant[
A Dynamips id can be reused by another VM
:param project_id: UUID of the project
:param dynamips_id: Asked id
]
call[name[self]._dynamips_ids.setdefault, parameter[name[project_id], ca... | keyword[def] identifier[release_dynamips_id] ( identifier[self] , identifier[project_id] , identifier[dynamips_id] ):
literal[string]
identifier[self] . identifier[_dynamips_ids] . identifier[setdefault] ( identifier[project_id] , identifier[set] ())
keyword[if] identifier[dynamips_id] k... | def release_dynamips_id(self, project_id, dynamips_id):
"""
A Dynamips id can be reused by another VM
:param project_id: UUID of the project
:param dynamips_id: Asked id
"""
self._dynamips_ids.setdefault(project_id, set())
if dynamips_id in self._dynamips_ids[project_id]:
... |
def add_document(self, doc_url, data):
""" Add the given document to the cache, updating
the existing content data if the document is already present
:type doc_url: String or Document
:param doc_url: the URL of the document, or a Document object
:type data: String
:param... | def function[add_document, parameter[self, doc_url, data]]:
constant[ Add the given document to the cache, updating
the existing content data if the document is already present
:type doc_url: String or Document
:param doc_url: the URL of the document, or a Document object
:type ... | keyword[def] identifier[add_document] ( identifier[self] , identifier[doc_url] , identifier[data] ):
literal[string]
identifier[file_path] = identifier[self] . identifier[__generate_filepath] ()
keyword[with] identifier[open] ( identifier[file_path] , literal[string] ) keyword[as] identi... | def add_document(self, doc_url, data):
""" Add the given document to the cache, updating
the existing content data if the document is already present
:type doc_url: String or Document
:param doc_url: the URL of the document, or a Document object
:type data: String
:param dat... |
def edit_user(self, id, user_avatar_token=None, user_avatar_url=None, user_email=None, user_locale=None, user_name=None, user_short_name=None, user_sortable_name=None, user_time_zone=None):
"""
Edit a user.
Modify an existing user. To modify a user's login, see the documentation for logins.... | def function[edit_user, parameter[self, id, user_avatar_token, user_avatar_url, user_email, user_locale, user_name, user_short_name, user_sortable_name, user_time_zone]]:
constant[
Edit a user.
Modify an existing user. To modify a user's login, see the documentation for logins.
]
... | keyword[def] identifier[edit_user] ( identifier[self] , identifier[id] , identifier[user_avatar_token] = keyword[None] , identifier[user_avatar_url] = keyword[None] , identifier[user_email] = keyword[None] , identifier[user_locale] = keyword[None] , identifier[user_name] = keyword[None] , identifier[user_short_name] ... | def edit_user(self, id, user_avatar_token=None, user_avatar_url=None, user_email=None, user_locale=None, user_name=None, user_short_name=None, user_sortable_name=None, user_time_zone=None):
"""
Edit a user.
Modify an existing user. To modify a user's login, see the documentation for logins.
... |
async def _set_get_started(self):
"""
Set the "get started" action for all configured pages.
"""
page = self.settings()
if 'get_started' in page:
payload = page['get_started']
else:
payload = {'action': 'get_started'}
await self._send_to... | <ast.AsyncFunctionDef object at 0x7da204567850> | keyword[async] keyword[def] identifier[_set_get_started] ( identifier[self] ):
literal[string]
identifier[page] = identifier[self] . identifier[settings] ()
keyword[if] literal[string] keyword[in] identifier[page] :
identifier[payload] = identifier[page] [ literal[string... | async def _set_get_started(self):
"""
Set the "get started" action for all configured pages.
"""
page = self.settings()
if 'get_started' in page:
payload = page['get_started'] # depends on [control=['if'], data=['page']]
else:
payload = {'action': 'get_started'}
awai... |
def encode(cls, line):
"""
Backslash escape line.value.
"""
if not line.encoded:
encoding = getattr(line, 'encoding_param', None)
if encoding and encoding.upper() == cls.base64string:
if isinstance(line.value, bytes):
line.value... | def function[encode, parameter[cls, line]]:
constant[
Backslash escape line.value.
]
if <ast.UnaryOp object at 0x7da18bcca620> begin[:]
variable[encoding] assign[=] call[name[getattr], parameter[name[line], constant[encoding_param], constant[None]]]
if <as... | keyword[def] identifier[encode] ( identifier[cls] , identifier[line] ):
literal[string]
keyword[if] keyword[not] identifier[line] . identifier[encoded] :
identifier[encoding] = identifier[getattr] ( identifier[line] , literal[string] , keyword[None] )
keyword[if] identi... | def encode(cls, line):
"""
Backslash escape line.value.
"""
if not line.encoded:
encoding = getattr(line, 'encoding_param', None)
if encoding and encoding.upper() == cls.base64string:
if isinstance(line.value, bytes):
line.value = codecs.encode(line.va... |
def axis_rotation_matrix(axis, angle):
"""Matrix of the rotation around an axis in 3d.
The matrix is computed according to `Rodriguez' rotation formula`_.
Parameters
----------
axis : `array-like`, shape ``(3,)``
Rotation axis, assumed to be a unit vector.
angle : float or `array-like`... | def function[axis_rotation_matrix, parameter[axis, angle]]:
constant[Matrix of the rotation around an axis in 3d.
The matrix is computed according to `Rodriguez' rotation formula`_.
Parameters
----------
axis : `array-like`, shape ``(3,)``
Rotation axis, assumed to be a unit vector.
... | keyword[def] identifier[axis_rotation_matrix] ( identifier[axis] , identifier[angle] ):
literal[string]
identifier[scalar_out] =( identifier[np] . identifier[shape] ( identifier[angle] )==())
identifier[axis] = identifier[np] . identifier[asarray] ( identifier[axis] )
keyword[if] identifier[axis... | def axis_rotation_matrix(axis, angle):
"""Matrix of the rotation around an axis in 3d.
The matrix is computed according to `Rodriguez' rotation formula`_.
Parameters
----------
axis : `array-like`, shape ``(3,)``
Rotation axis, assumed to be a unit vector.
angle : float or `array-like`... |
def account(self, url):
"""
Return accounts references for the given account id.
:param account_id:
:param accounts_password: The password for decrypting the secret
:return:
"""
from sqlalchemy.orm.exc import NoResultFound
from ambry.orm.exc import NotFoun... | def function[account, parameter[self, url]]:
constant[
Return accounts references for the given account id.
:param account_id:
:param accounts_password: The password for decrypting the secret
:return:
]
from relative_module[sqlalchemy.orm.exc] import module[NoResultFo... | keyword[def] identifier[account] ( identifier[self] , identifier[url] ):
literal[string]
keyword[from] identifier[sqlalchemy] . identifier[orm] . identifier[exc] keyword[import] identifier[NoResultFound]
keyword[from] identifier[ambry] . identifier[orm] . identifier[exc] keyword[impo... | def account(self, url):
"""
Return accounts references for the given account id.
:param account_id:
:param accounts_password: The password for decrypting the secret
:return:
"""
from sqlalchemy.orm.exc import NoResultFound
from ambry.orm.exc import NotFoundError
f... |
def get_cycles(self):
"""Get the selected cycle(s in order).
Returns
-------
list of tuple
Each tuple is (start time (sec), end time (sec), index (starting
at 1)."""
idx_cyc_sel = [
int(x.text()) - 1 for x in self.idx_cycle.selectedItems()... | def function[get_cycles, parameter[self]]:
constant[Get the selected cycle(s in order).
Returns
-------
list of tuple
Each tuple is (start time (sec), end time (sec), index (starting
at 1).]
variable[idx_cyc_sel] assign[=] <ast.ListComp object at 0x7da1b2... | keyword[def] identifier[get_cycles] ( identifier[self] ):
literal[string]
identifier[idx_cyc_sel] =[
identifier[int] ( identifier[x] . identifier[text] ())- literal[int] keyword[for] identifier[x] keyword[in] identifier[self] . identifier[idx_cycle] . identifier[selectedItems] ()]
... | def get_cycles(self):
"""Get the selected cycle(s in order).
Returns
-------
list of tuple
Each tuple is (start time (sec), end time (sec), index (starting
at 1)."""
idx_cyc_sel = [int(x.text()) - 1 for x in self.idx_cycle.selectedItems()]
if not idx_cyc_sel:... |
def build_tool(self, doc, entity):
"""Builds a tool object out of a string representation.
Returns built tool. Raises SPDXValueError if failed to extract
tool name or name is malformed
"""
match = self.tool_re.match(entity)
if match and validations.validate_tool_name(matc... | def function[build_tool, parameter[self, doc, entity]]:
constant[Builds a tool object out of a string representation.
Returns built tool. Raises SPDXValueError if failed to extract
tool name or name is malformed
]
variable[match] assign[=] call[name[self].tool_re.match, parameter... | keyword[def] identifier[build_tool] ( identifier[self] , identifier[doc] , identifier[entity] ):
literal[string]
identifier[match] = identifier[self] . identifier[tool_re] . identifier[match] ( identifier[entity] )
keyword[if] identifier[match] keyword[and] identifier[validations] . ide... | def build_tool(self, doc, entity):
"""Builds a tool object out of a string representation.
Returns built tool. Raises SPDXValueError if failed to extract
tool name or name is malformed
"""
match = self.tool_re.match(entity)
if match and validations.validate_tool_name(match.group(self... |
def delete_if_exists(self, **kwargs):
"""
Deletes an object if it exists in database according to given query
parameters and returns True otherwise does nothing and returns False.
Args:
**kwargs: query parameters
Returns(bool): True or False
"""
... | def function[delete_if_exists, parameter[self]]:
constant[
Deletes an object if it exists in database according to given query
parameters and returns True otherwise does nothing and returns False.
Args:
**kwargs: query parameters
Returns(bool): True or Fals... | keyword[def] identifier[delete_if_exists] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
identifier[self] . identifier[get] (** identifier[kwargs] ). identifier[blocking_delete] ()
keyword[return] keyword[True]
keyword[except] ident... | def delete_if_exists(self, **kwargs):
"""
Deletes an object if it exists in database according to given query
parameters and returns True otherwise does nothing and returns False.
Args:
**kwargs: query parameters
Returns(bool): True or False
"""
t... |
def start(self):
""" TODO: docstring """
logger.info("Starting interchange")
# last = time.time()
while True:
# active_flag = False
socks = dict(self.poller.poll(1))
if socks.get(self.task_incoming) == zmq.POLLIN:
message = self.task_... | def function[start, parameter[self]]:
constant[ TODO: docstring ]
call[name[logger].info, parameter[constant[Starting interchange]]]
while constant[True] begin[:]
variable[socks] assign[=] call[name[dict], parameter[call[name[self].poller.poll, parameter[constant[1]]]]]
... | keyword[def] identifier[start] ( identifier[self] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] )
keyword[while] keyword[True] :
identifier[socks] = identifier[dict] ( identifier[self] . identifier[poller] . identifier[poll] ( l... | def start(self):
""" TODO: docstring """
logger.info('Starting interchange')
# last = time.time()
while True:
# active_flag = False
socks = dict(self.poller.poll(1))
if socks.get(self.task_incoming) == zmq.POLLIN:
message = self.task_incoming.recv_multipart()
... |
def _shutdown(self):
"""Gracefully shut down the consumer and exit."""
if self._channel:
_log.info("Halting %r consumer sessions", self._channel.consumer_tags)
self._running = False
if self._connection and self._connection.is_open:
self._connection.close()
... | def function[_shutdown, parameter[self]]:
constant[Gracefully shut down the consumer and exit.]
if name[self]._channel begin[:]
call[name[_log].info, parameter[constant[Halting %r consumer sessions], name[self]._channel.consumer_tags]]
name[self]._running assign[=] constant[False... | keyword[def] identifier[_shutdown] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_channel] :
identifier[_log] . identifier[info] ( literal[string] , identifier[self] . identifier[_channel] . identifier[consumer_tags] )
identifier[self] . iden... | def _shutdown(self):
"""Gracefully shut down the consumer and exit."""
if self._channel:
_log.info('Halting %r consumer sessions', self._channel.consumer_tags) # depends on [control=['if'], data=[]]
self._running = False
if self._connection and self._connection.is_open:
self._connection... |
def swap(self, i, j):
"""Swap the values at indices i & j.
.. versionadded:: 1.1
"""
i = self._fix_neg_index(i)
j = self._fix_neg_index(j)
self._list[i], self._list[j] = self._list[j], self._list[i]
self._dict[self._list[i]] = i
self._dict[self._list[j]] = j | def function[swap, parameter[self, i, j]]:
constant[Swap the values at indices i & j.
.. versionadded:: 1.1
]
variable[i] assign[=] call[name[self]._fix_neg_index, parameter[name[i]]]
variable[j] assign[=] call[name[self]._fix_neg_index, parameter[name[j]]]
<ast.Tuple object at 0x7d... | keyword[def] identifier[swap] ( identifier[self] , identifier[i] , identifier[j] ):
literal[string]
identifier[i] = identifier[self] . identifier[_fix_neg_index] ( identifier[i] )
identifier[j] = identifier[self] . identifier[_fix_neg_index] ( identifier[j] )
identifier[self] . identifier[_list] [ identi... | def swap(self, i, j):
"""Swap the values at indices i & j.
.. versionadded:: 1.1
"""
i = self._fix_neg_index(i)
j = self._fix_neg_index(j)
(self._list[i], self._list[j]) = (self._list[j], self._list[i])
self._dict[self._list[i]] = i
self._dict[self._list[j]] = j |
def open_image(fname_or_instance: Union[str, IO[bytes]]):
"""Opens a Image and returns it.
:param fname_or_instance: Can either be the location of the image as a
string or the Image.Image instance itself.
"""
if isinstance(fname_or_instance, Image.Image):
return fn... | def function[open_image, parameter[fname_or_instance]]:
constant[Opens a Image and returns it.
:param fname_or_instance: Can either be the location of the image as a
string or the Image.Image instance itself.
]
if call[name[isinstance], parameter[name[fname_or_inst... | keyword[def] identifier[open_image] ( identifier[fname_or_instance] : identifier[Union] [ identifier[str] , identifier[IO] [ identifier[bytes] ]]):
literal[string]
keyword[if] identifier[isinstance] ( identifier[fname_or_instance] , identifier[Image] . identifier[Image] ):
keyword[return] identi... | def open_image(fname_or_instance: Union[str, IO[bytes]]):
"""Opens a Image and returns it.
:param fname_or_instance: Can either be the location of the image as a
string or the Image.Image instance itself.
"""
if isinstance(fname_or_instance, Image.Image):
return fn... |
def deletegitlabciservice(self, project_id, token, project_url):
"""
Delete GitLab CI service settings
:param project_id: Project ID
:param token: Token
:param project_url: Project URL
:return: true if success, false if not
"""
request = requests.delete(
... | def function[deletegitlabciservice, parameter[self, project_id, token, project_url]]:
constant[
Delete GitLab CI service settings
:param project_id: Project ID
:param token: Token
:param project_url: Project URL
:return: true if success, false if not
]
va... | keyword[def] identifier[deletegitlabciservice] ( identifier[self] , identifier[project_id] , identifier[token] , identifier[project_url] ):
literal[string]
identifier[request] = identifier[requests] . identifier[delete] (
literal[string] . identifier[format] ( identifier[self] . identifier... | def deletegitlabciservice(self, project_id, token, project_url):
"""
Delete GitLab CI service settings
:param project_id: Project ID
:param token: Token
:param project_url: Project URL
:return: true if success, false if not
"""
request = requests.delete('{0}/{1}/... |
def create_token(self, creds):
'''
Create token with creds.
Token authorizes salt access if successful authentication
with the credentials in creds.
creds format is as follows:
{
'username': 'namestring',
'password': 'passwordstring',
... | def function[create_token, parameter[self, creds]]:
constant[
Create token with creds.
Token authorizes salt access if successful authentication
with the credentials in creds.
creds format is as follows:
{
'username': 'namestring',
'password': 'pa... | keyword[def] identifier[create_token] ( identifier[self] , identifier[creds] ):
literal[string]
keyword[try] :
identifier[tokenage] = identifier[self] . identifier[resolver] . identifier[mk_token] ( identifier[creds] )
keyword[except] identifier[Exception] keyword[as] ident... | def create_token(self, creds):
"""
Create token with creds.
Token authorizes salt access if successful authentication
with the credentials in creds.
creds format is as follows:
{
'username': 'namestring',
'password': 'passwordstring',
'eau... |
def store(self, bank, key, data):
'''
Store data using the specified module
:param bank:
The name of the location inside the cache which will hold the key
and its associated data.
:param key:
The name of the key (or file inside a directory) which wil... | def function[store, parameter[self, bank, key, data]]:
constant[
Store data using the specified module
:param bank:
The name of the location inside the cache which will hold the key
and its associated data.
:param key:
The name of the key (or file in... | keyword[def] identifier[store] ( identifier[self] , identifier[bank] , identifier[key] , identifier[data] ):
literal[string]
identifier[fun] = literal[string] . identifier[format] ( identifier[self] . identifier[driver] )
keyword[return] identifier[self] . identifier[modules] [ identifier... | def store(self, bank, key, data):
"""
Store data using the specified module
:param bank:
The name of the location inside the cache which will hold the key
and its associated data.
:param key:
The name of the key (or file inside a directory) which will ho... |
def stop(self, wait=True):
''' Stop the Bokeh Server.
This stops and removes all Bokeh Server ``IOLoop`` callbacks, as well
as stops the ``HTTPServer`` that this instance was configured with.
Args:
fast (bool):
Whether to wait for orderly cleanup (default: T... | def function[stop, parameter[self, wait]]:
constant[ Stop the Bokeh Server.
This stops and removes all Bokeh Server ``IOLoop`` callbacks, as well
as stops the ``HTTPServer`` that this instance was configured with.
Args:
fast (bool):
Whether to wait for order... | keyword[def] identifier[stop] ( identifier[self] , identifier[wait] = keyword[True] ):
literal[string]
keyword[assert] keyword[not] identifier[self] . identifier[_stopped] , literal[string]
identifier[self] . identifier[_stopped] = keyword[True]
identifier[self] . identifier[_... | def stop(self, wait=True):
""" Stop the Bokeh Server.
This stops and removes all Bokeh Server ``IOLoop`` callbacks, as well
as stops the ``HTTPServer`` that this instance was configured with.
Args:
fast (bool):
Whether to wait for orderly cleanup (default: True)... |
def record_sets_list_by_type(zone_name, resource_group, record_type, top=None, recordsetnamesuffix=None, **kwargs):
'''
.. versionadded:: Fluorine
Lists the record sets of a specified type in a DNS zone.
:param zone_name: The name of the DNS zone (without a terminating dot).
:param resource_group... | def function[record_sets_list_by_type, parameter[zone_name, resource_group, record_type, top, recordsetnamesuffix]]:
constant[
.. versionadded:: Fluorine
Lists the record sets of a specified type in a DNS zone.
:param zone_name: The name of the DNS zone (without a terminating dot).
:param res... | keyword[def] identifier[record_sets_list_by_type] ( identifier[zone_name] , identifier[resource_group] , identifier[record_type] , identifier[top] = keyword[None] , identifier[recordsetnamesuffix] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[result] ={}
identifier[dnsconn] = id... | def record_sets_list_by_type(zone_name, resource_group, record_type, top=None, recordsetnamesuffix=None, **kwargs):
"""
.. versionadded:: Fluorine
Lists the record sets of a specified type in a DNS zone.
:param zone_name: The name of the DNS zone (without a terminating dot).
:param resource_group... |
def dflin2dfbinarymap(dflin,col1,col2,params_df2submap={'aggfunc':'sum','binary':True,'binaryby':'nan'},test=False):
"""
if not binary:
dropna the df by value [col index and value] column
"""
# get the submap ready
df_map=df2submap(df=dflin,
col=col1,idx=col2,**params_df2submap... | def function[dflin2dfbinarymap, parameter[dflin, col1, col2, params_df2submap, test]]:
constant[
if not binary:
dropna the df by value [col index and value] column
]
variable[df_map] assign[=] call[name[df2submap], parameter[]]
if name[test] begin[:]
call[name[log... | keyword[def] identifier[dflin2dfbinarymap] ( identifier[dflin] , identifier[col1] , identifier[col2] , identifier[params_df2submap] ={ literal[string] : literal[string] , literal[string] : keyword[True] , literal[string] : literal[string] }, identifier[test] = keyword[False] ):
literal[string]
identif... | def dflin2dfbinarymap(dflin, col1, col2, params_df2submap={'aggfunc': 'sum', 'binary': True, 'binaryby': 'nan'}, test=False):
"""
if not binary:
dropna the df by value [col index and value] column
"""
# get the submap ready
df_map = df2submap(df=dflin, col=col1, idx=col2, **params_df2submap)... |
def dateint_to_datetime(dateint):
"""Converts the given dateint to a datetime object, in local timezone.
Arguments
---------
dateint : int
An integer object decipting a specific calendaric day; e.g. 20161225.
Returns
-------
datetime.datetime
A timezone-unaware datetime obj... | def function[dateint_to_datetime, parameter[dateint]]:
constant[Converts the given dateint to a datetime object, in local timezone.
Arguments
---------
dateint : int
An integer object decipting a specific calendaric day; e.g. 20161225.
Returns
-------
datetime.datetime
... | keyword[def] identifier[dateint_to_datetime] ( identifier[dateint] ):
literal[string]
keyword[if] identifier[len] ( identifier[str] ( identifier[dateint] ))!= literal[int] :
keyword[raise] identifier[ValueError] (
literal[string]
literal[string] )
identifier[year] , ident... | def dateint_to_datetime(dateint):
"""Converts the given dateint to a datetime object, in local timezone.
Arguments
---------
dateint : int
An integer object decipting a specific calendaric day; e.g. 20161225.
Returns
-------
datetime.datetime
A timezone-unaware datetime obj... |
def result(self, timeout=None):
"""Returns the result of the call that the future represents.
:param timeout: The number of seconds to wait for the result
if the future has not been completed. None, the default,
sets no limit.
:returns: The result of the call that the fu... | def function[result, parameter[self, timeout]]:
constant[Returns the result of the call that the future represents.
:param timeout: The number of seconds to wait for the result
if the future has not been completed. None, the default,
sets no limit.
:returns: The result o... | keyword[def] identifier[result] ( identifier[self] , identifier[timeout] = keyword[None] ):
literal[string]
identifier[result] = identifier[super] ( identifier[FutureRef] , identifier[self] ). identifier[result] ( identifier[timeout] )
keyword[return] identifier[get_host] (). identifier[l... | def result(self, timeout=None):
"""Returns the result of the call that the future represents.
:param timeout: The number of seconds to wait for the result
if the future has not been completed. None, the default,
sets no limit.
:returns: The result of the call that the future... |
def reloadFileOfCurrentItem(self, rtiRegItem=None):
""" Finds the repo tree item that holds the file of the current item and reloads it.
Reloading is done by removing the repo tree item and inserting a new one.
The new item will have by of type rtiRegItem.cls. If rtiRegItem is None (the... | def function[reloadFileOfCurrentItem, parameter[self, rtiRegItem]]:
constant[ Finds the repo tree item that holds the file of the current item and reloads it.
Reloading is done by removing the repo tree item and inserting a new one.
The new item will have by of type rtiRegItem.cls. If r... | keyword[def] identifier[reloadFileOfCurrentItem] ( identifier[self] , identifier[rtiRegItem] = keyword[None] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] . identifier[format] ( identifier[rtiRegItem] ))
identifier[currentIndex] = identifier[self] . identifi... | def reloadFileOfCurrentItem(self, rtiRegItem=None):
""" Finds the repo tree item that holds the file of the current item and reloads it.
Reloading is done by removing the repo tree item and inserting a new one.
The new item will have by of type rtiRegItem.cls. If rtiRegItem is None (the def... |
def set_marker_color(self, color='#3ea0e4', edgecolor='k'):
""" set the marker color used in the plot
:param color: matplotlib color (ie 'r', '#000000')
"""
# TODO allow a colour set per another variable
self._marker_color = color
self._edge_color = edgecolor | def function[set_marker_color, parameter[self, color, edgecolor]]:
constant[ set the marker color used in the plot
:param color: matplotlib color (ie 'r', '#000000')
]
name[self]._marker_color assign[=] name[color]
name[self]._edge_color assign[=] name[edgecolor] | keyword[def] identifier[set_marker_color] ( identifier[self] , identifier[color] = literal[string] , identifier[edgecolor] = literal[string] ):
literal[string]
identifier[self] . identifier[_marker_color] = identifier[color]
identifier[self] . identifier[_edge_color] = identifier... | def set_marker_color(self, color='#3ea0e4', edgecolor='k'):
""" set the marker color used in the plot
:param color: matplotlib color (ie 'r', '#000000')
"""
# TODO allow a colour set per another variable
self._marker_color = color
self._edge_color = edgecolor |
def construct_selector(self, el, attr=''):
"""Construct an selector for context."""
selector = deque()
ancestor = el
while ancestor and ancestor.parent:
if ancestor is not el:
selector.appendleft(ancestor.name)
else:
tag = ancestor... | def function[construct_selector, parameter[self, el, attr]]:
constant[Construct an selector for context.]
variable[selector] assign[=] call[name[deque], parameter[]]
variable[ancestor] assign[=] name[el]
while <ast.BoolOp object at 0x7da18bcc82e0> begin[:]
if compare[name... | keyword[def] identifier[construct_selector] ( identifier[self] , identifier[el] , identifier[attr] = literal[string] ):
literal[string]
identifier[selector] = identifier[deque] ()
identifier[ancestor] = identifier[el]
keyword[while] identifier[ancestor] keyword[and] identifie... | def construct_selector(self, el, attr=''):
"""Construct an selector for context."""
selector = deque()
ancestor = el
while ancestor and ancestor.parent:
if ancestor is not el:
selector.appendleft(ancestor.name) # depends on [control=['if'], data=['ancestor']]
else:
... |
def _can_update(self):
"""
Called by the save function to check if this should be
persisted with update or insert
:return:
"""
if not self._is_persisted: return False
pks = self._primary_keys.keys()
return all([not self._values[k].changed for k in self._p... | def function[_can_update, parameter[self]]:
constant[
Called by the save function to check if this should be
persisted with update or insert
:return:
]
if <ast.UnaryOp object at 0x7da18f7223e0> begin[:]
return[constant[False]]
variable[pks] assign[=] call... | keyword[def] identifier[_can_update] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_is_persisted] : keyword[return] keyword[False]
identifier[pks] = identifier[self] . identifier[_primary_keys] . identifier[keys] ()
keyword[return... | def _can_update(self):
"""
Called by the save function to check if this should be
persisted with update or insert
:return:
"""
if not self._is_persisted:
return False # depends on [control=['if'], data=[]]
pks = self._primary_keys.keys()
return all([not self._va... |
def run_in_executor(f):
"""
A decorator to run the given method in the ThreadPoolExecutor.
"""
@wraps(f)
def new_f(self, *args, **kwargs):
if self.is_shutdown:
return
try:
future = self.executor.submit(f, self, *args, **kwargs)
future.add_done_ca... | def function[run_in_executor, parameter[f]]:
constant[
A decorator to run the given method in the ThreadPoolExecutor.
]
def function[new_f, parameter[self]]:
if name[self].is_shutdown begin[:]
return[None]
<ast.Try object at 0x7da20e9b1fc0>
return[name[new... | keyword[def] identifier[run_in_executor] ( identifier[f] ):
literal[string]
@ identifier[wraps] ( identifier[f] )
keyword[def] identifier[new_f] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
keyword[if] identifier[self] . identifier[is_shutdown] :
keyword[re... | def run_in_executor(f):
"""
A decorator to run the given method in the ThreadPoolExecutor.
"""
@wraps(f)
def new_f(self, *args, **kwargs):
if self.is_shutdown:
return # depends on [control=['if'], data=[]]
try:
future = self.executor.submit(f, self, *args, *... |
def colors(self, value):
"""
Setter for **self.__colors** attribute.
:param value: Attribute value.
:type value: tuple
"""
if value is not None:
assert type(value) is tuple, "'{0}' attribute: '{1}' type is not 'tuple'!".format("colors", value)
ass... | def function[colors, parameter[self, value]]:
constant[
Setter for **self.__colors** attribute.
:param value: Attribute value.
:type value: tuple
]
if compare[name[value] is_not constant[None]] begin[:]
assert[compare[call[name[type], parameter[name[value]]] is n... | keyword[def] identifier[colors] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[not] keyword[None] :
keyword[assert] identifier[type] ( identifier[value] ) keyword[is] identifier[tuple] , literal[string] . identifier[for... | def colors(self, value):
"""
Setter for **self.__colors** attribute.
:param value: Attribute value.
:type value: tuple
"""
if value is not None:
assert type(value) is tuple, "'{0}' attribute: '{1}' type is not 'tuple'!".format('colors', value)
assert len(value) =... |
def add_sign(xml, key, cert, debug=False, sign_algorithm=OneLogin_Saml2_Constants.RSA_SHA1, digest_algorithm=OneLogin_Saml2_Constants.SHA1):
"""
Adds signature key and senders certificate to an element (Message or
Assertion).
:param xml: The element we should sign
:type: string ... | def function[add_sign, parameter[xml, key, cert, debug, sign_algorithm, digest_algorithm]]:
constant[
Adds signature key and senders certificate to an element (Message or
Assertion).
:param xml: The element we should sign
:type: string | Document
:param key: The private... | keyword[def] identifier[add_sign] ( identifier[xml] , identifier[key] , identifier[cert] , identifier[debug] = keyword[False] , identifier[sign_algorithm] = identifier[OneLogin_Saml2_Constants] . identifier[RSA_SHA1] , identifier[digest_algorithm] = identifier[OneLogin_Saml2_Constants] . identifier[SHA1] ):
... | def add_sign(xml, key, cert, debug=False, sign_algorithm=OneLogin_Saml2_Constants.RSA_SHA1, digest_algorithm=OneLogin_Saml2_Constants.SHA1):
"""
Adds signature key and senders certificate to an element (Message or
Assertion).
:param xml: The element we should sign
:type: string | Do... |
def set_layer(self, layer=None, keywords=None):
"""Set layer and update UI accordingly.
:param layer: A QgsVectorLayer.
:type layer: QgsVectorLayer
:param keywords: Keywords for the layer.
:type keywords: dict, None
"""
if self.field_mapping_widget is not None:
... | def function[set_layer, parameter[self, layer, keywords]]:
constant[Set layer and update UI accordingly.
:param layer: A QgsVectorLayer.
:type layer: QgsVectorLayer
:param keywords: Keywords for the layer.
:type keywords: dict, None
]
if compare[name[self].field... | keyword[def] identifier[set_layer] ( identifier[self] , identifier[layer] = keyword[None] , identifier[keywords] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[field_mapping_widget] keyword[is] keyword[not] keyword[None] :
identifier[self] . identifier... | def set_layer(self, layer=None, keywords=None):
"""Set layer and update UI accordingly.
:param layer: A QgsVectorLayer.
:type layer: QgsVectorLayer
:param keywords: Keywords for the layer.
:type keywords: dict, None
"""
if self.field_mapping_widget is not None:
... |
def create_producer(self):
"""Context manager that yields an instance of ``Producer``."""
with self.connection_pool.acquire(block=True) as conn:
yield self.producer(conn) | def function[create_producer, parameter[self]]:
constant[Context manager that yields an instance of ``Producer``.]
with call[name[self].connection_pool.acquire, parameter[]] begin[:]
<ast.Yield object at 0x7da207f02800> | keyword[def] identifier[create_producer] ( identifier[self] ):
literal[string]
keyword[with] identifier[self] . identifier[connection_pool] . identifier[acquire] ( identifier[block] = keyword[True] ) keyword[as] identifier[conn] :
keyword[yield] identifier[self] . identifier[produce... | def create_producer(self):
"""Context manager that yields an instance of ``Producer``."""
with self.connection_pool.acquire(block=True) as conn:
yield self.producer(conn) # depends on [control=['with'], data=['conn']] |
def set_server_params(
self, client_notify_address=None, mountpoints_depth=None, require_vassal=None,
tolerance=None, tolerance_inactive=None, key_dot_split=None):
"""Sets subscription server related params.
:param str|unicode client_notify_address: Set the notification socket f... | def function[set_server_params, parameter[self, client_notify_address, mountpoints_depth, require_vassal, tolerance, tolerance_inactive, key_dot_split]]:
constant[Sets subscription server related params.
:param str|unicode client_notify_address: Set the notification socket for subscriptions.
... | keyword[def] identifier[set_server_params] (
identifier[self] , identifier[client_notify_address] = keyword[None] , identifier[mountpoints_depth] = keyword[None] , identifier[require_vassal] = keyword[None] ,
identifier[tolerance] = keyword[None] , identifier[tolerance_inactive] = keyword[None] , identifier[key_dot... | def set_server_params(self, client_notify_address=None, mountpoints_depth=None, require_vassal=None, tolerance=None, tolerance_inactive=None, key_dot_split=None):
"""Sets subscription server related params.
:param str|unicode client_notify_address: Set the notification socket for subscriptions.
... |
def previous_page_url(self):
"""
:return str: Returns a link to the previous_page_url or None if doesn't exist.
"""
if 'meta' in self._payload and 'previous_page_url' in self._payload['meta']:
return self._payload['meta']['previous_page_url']
elif 'previous_page_uri' ... | def function[previous_page_url, parameter[self]]:
constant[
:return str: Returns a link to the previous_page_url or None if doesn't exist.
]
if <ast.BoolOp object at 0x7da2054a44c0> begin[:]
return[call[call[name[self]._payload][constant[meta]]][constant[previous_page_url]]]
... | keyword[def] identifier[previous_page_url] ( identifier[self] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[self] . identifier[_payload] keyword[and] literal[string] keyword[in] identifier[self] . identifier[_payload] [ literal[string] ]:
keyword[return] ... | def previous_page_url(self):
"""
:return str: Returns a link to the previous_page_url or None if doesn't exist.
"""
if 'meta' in self._payload and 'previous_page_url' in self._payload['meta']:
return self._payload['meta']['previous_page_url'] # depends on [control=['if'], data=[]]
e... |
def _parse(reactor, directory, pemdir, *args, **kwargs):
"""
Parse a txacme endpoint description.
:param reactor: The Twisted reactor.
:param directory: ``twisted.python.url.URL`` for the ACME directory to use
for issuing certs.
:param str pemdir: The path to the certificate directory to us... | def function[_parse, parameter[reactor, directory, pemdir]]:
constant[
Parse a txacme endpoint description.
:param reactor: The Twisted reactor.
:param directory: ``twisted.python.url.URL`` for the ACME directory to use
for issuing certs.
:param str pemdir: The path to the certificate d... | keyword[def] identifier[_parse] ( identifier[reactor] , identifier[directory] , identifier[pemdir] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[def] identifier[colon_join] ( identifier[items] ):
keyword[return] literal[string] . identifier[join] ([ identifier[item] . ide... | def _parse(reactor, directory, pemdir, *args, **kwargs):
"""
Parse a txacme endpoint description.
:param reactor: The Twisted reactor.
:param directory: ``twisted.python.url.URL`` for the ACME directory to use
for issuing certs.
:param str pemdir: The path to the certificate directory to us... |
def get_modules(modulename=None):
"""Return a list of modules and packages under modulename.
If modulename is not given, return a list of all top level modules
and packages.
"""
modulename = compat.ensure_not_unicode(modulename)
if not modulename:
try:
return ([modname for ... | def function[get_modules, parameter[modulename]]:
constant[Return a list of modules and packages under modulename.
If modulename is not given, return a list of all top level modules
and packages.
]
variable[modulename] assign[=] call[name[compat].ensure_not_unicode, parameter[name[modulena... | keyword[def] identifier[get_modules] ( identifier[modulename] = keyword[None] ):
literal[string]
identifier[modulename] = identifier[compat] . identifier[ensure_not_unicode] ( identifier[modulename] )
keyword[if] keyword[not] identifier[modulename] :
keyword[try] :
keyword[retu... | def get_modules(modulename=None):
"""Return a list of modules and packages under modulename.
If modulename is not given, return a list of all top level modules
and packages.
"""
modulename = compat.ensure_not_unicode(modulename)
if not modulename:
try:
return [modname for (... |
def delete_package(self, cache, pkg):
"""Deletes the package from the system.
Deletes the package form the system, properly handling virtual
packages.
:param cache: the apt cache
:param pkg: the package to remove
"""
if self.is_virtual_package(pkg):
... | def function[delete_package, parameter[self, cache, pkg]]:
constant[Deletes the package from the system.
Deletes the package form the system, properly handling virtual
packages.
:param cache: the apt cache
:param pkg: the package to remove
]
if call[name[self].i... | keyword[def] identifier[delete_package] ( identifier[self] , identifier[cache] , identifier[pkg] ):
literal[string]
keyword[if] identifier[self] . identifier[is_virtual_package] ( identifier[pkg] ):
identifier[log] ( literal[string] %
identifier[pkg] . identifier[name] , ... | def delete_package(self, cache, pkg):
"""Deletes the package from the system.
Deletes the package form the system, properly handling virtual
packages.
:param cache: the apt cache
:param pkg: the package to remove
"""
if self.is_virtual_package(pkg):
log("Package... |
async def listen(self, address, target):
'''
starts event listener for the contract
:return:
'''
if not address:
return None, "listening address not provided"
EZO.log.info(bright("hello ezo::listening to address: {}".format(blue(address))))
interval ... | <ast.AsyncFunctionDef object at 0x7da207f03580> | keyword[async] keyword[def] identifier[listen] ( identifier[self] , identifier[address] , identifier[target] ):
literal[string]
keyword[if] keyword[not] identifier[address] :
keyword[return] keyword[None] , literal[string]
identifier[EZO] . identifier[log] . identifier[... | async def listen(self, address, target):
"""
starts event listener for the contract
:return:
"""
if not address:
return (None, 'listening address not provided') # depends on [control=['if'], data=[]]
EZO.log.info(bright('hello ezo::listening to address: {}'.format(blue(addre... |
def get_washing_regex():
"""Return a washing regex list."""
global _washing_regex
if len(_washing_regex):
return _washing_regex
washing_regex = [
# Replace non and anti with non- and anti-. This allows a better
# detection of keywords such as nonabelian.
(re.compile(r"(\... | def function[get_washing_regex, parameter[]]:
constant[Return a washing regex list.]
<ast.Global object at 0x7da20c992290>
if call[name[len], parameter[name[_washing_regex]]] begin[:]
return[name[_washing_regex]]
variable[washing_regex] assign[=] list[[<ast.Tuple object at 0x7da20c99... | keyword[def] identifier[get_washing_regex] ():
literal[string]
keyword[global] identifier[_washing_regex]
keyword[if] identifier[len] ( identifier[_washing_regex] ):
keyword[return] identifier[_washing_regex]
identifier[washing_regex] =[
( identifier[re] . identifier[... | def get_washing_regex():
"""Return a washing regex list."""
global _washing_regex
if len(_washing_regex):
return _washing_regex # depends on [control=['if'], data=[]]
# Replace non and anti with non- and anti-. This allows a better
# detection of keywords such as nonabelian.
# Remove al... |
def CountHuntResults(self,
hunt_id,
with_tag=None,
with_type=None,
cursor=None):
"""Counts hunt results of a given hunt using given query options."""
hunt_id_int = db_utils.HuntIDToInt(hunt_id)
query = "SELECT COUNT... | def function[CountHuntResults, parameter[self, hunt_id, with_tag, with_type, cursor]]:
constant[Counts hunt results of a given hunt using given query options.]
variable[hunt_id_int] assign[=] call[name[db_utils].HuntIDToInt, parameter[name[hunt_id]]]
variable[query] assign[=] constant[SELECT COU... | keyword[def] identifier[CountHuntResults] ( identifier[self] ,
identifier[hunt_id] ,
identifier[with_tag] = keyword[None] ,
identifier[with_type] = keyword[None] ,
identifier[cursor] = keyword[None] ):
literal[string]
identifier[hunt_id_int] = identifier[db_utils] . identifier[HuntIDToInt] ( identifier... | def CountHuntResults(self, hunt_id, with_tag=None, with_type=None, cursor=None):
"""Counts hunt results of a given hunt using given query options."""
hunt_id_int = db_utils.HuntIDToInt(hunt_id)
query = 'SELECT COUNT(*) FROM flow_results WHERE hunt_id = %s '
args = [hunt_id_int]
if with_tag is not No... |
def join(self, url):
"""Join URLs
Construct a full (“absolute”) URL by combining a “base URL”
(self) with another URL (url).
Informally, this uses components of the base URL, in
particular the addressing scheme, the network location and
(part of) the path, to provide mi... | def function[join, parameter[self, url]]:
constant[Join URLs
Construct a full (“absolute”) URL by combining a “base URL”
(self) with another URL (url).
Informally, this uses components of the base URL, in
particular the addressing scheme, the network location and
(part ... | keyword[def] identifier[join] ( identifier[self] , identifier[url] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[url] , identifier[URL] ):
keyword[raise] identifier[TypeError] ( literal[string] )
keyword[return] identifier[URL] ( ... | def join(self, url):
"""Join URLs
Construct a full (“absolute”) URL by combining a “base URL”
(self) with another URL (url).
Informally, this uses components of the base URL, in
particular the addressing scheme, the network location and
(part of) the path, to provide missin... |
def pathOp_do(self, d_msg, **kwargs):
"""
Entry point for path-based push/pull calls.
Essentially, this method is the central dispatching nexus to various
specialized push operations.
"""
d_meta = d_msg['meta']
b_OK = True
d_... | def function[pathOp_do, parameter[self, d_msg]]:
constant[
Entry point for path-based push/pull calls.
Essentially, this method is the central dispatching nexus to various
specialized push operations.
]
variable[d_meta] assign[=] call[name[d_msg]][constant[meta]]
... | keyword[def] identifier[pathOp_do] ( identifier[self] , identifier[d_msg] ,** identifier[kwargs] ):
literal[string]
identifier[d_meta] = identifier[d_msg] [ literal[string] ]
identifier[b_OK] = keyword[True]
identifier[d_ret] ={}
identifier[str_action] = literal[string... | def pathOp_do(self, d_msg, **kwargs):
"""
Entry point for path-based push/pull calls.
Essentially, this method is the central dispatching nexus to various
specialized push operations.
"""
d_meta = d_msg['meta']
b_OK = True
d_ret = {}
str_action = 'pull'
for (k, ... |
def indent_lines(lines, output, branch_method, leaf_method, pass_syntax, flush_left_syntax, flush_left_empty_line,
indentation_method, get_block):
"""Returns None.
The way this function produces output is by adding strings to the
list that's passed in as the second parameter.
Paramete... | def function[indent_lines, parameter[lines, output, branch_method, leaf_method, pass_syntax, flush_left_syntax, flush_left_empty_line, indentation_method, get_block]]:
constant[Returns None.
The way this function produces output is by adding strings to the
list that's passed in as the second parameter.... | keyword[def] identifier[indent_lines] ( identifier[lines] , identifier[output] , identifier[branch_method] , identifier[leaf_method] , identifier[pass_syntax] , identifier[flush_left_syntax] , identifier[flush_left_empty_line] ,
identifier[indentation_method] , identifier[get_block] ):
literal[string]
ide... | def indent_lines(lines, output, branch_method, leaf_method, pass_syntax, flush_left_syntax, flush_left_empty_line, indentation_method, get_block):
"""Returns None.
The way this function produces output is by adding strings to the
list that's passed in as the second parameter.
Parameters
----------... |
def _accented_vowel_to_numbered(vowel):
"""Convert an accented Pinyin vowel to a numbered Pinyin vowel."""
for numbered_vowel, accented_vowel in _PINYIN_TONES.items():
if vowel == accented_vowel:
return tuple(numbered_vowel) | def function[_accented_vowel_to_numbered, parameter[vowel]]:
constant[Convert an accented Pinyin vowel to a numbered Pinyin vowel.]
for taget[tuple[[<ast.Name object at 0x7da18fe90d00>, <ast.Name object at 0x7da18fe91360>]]] in starred[call[name[_PINYIN_TONES].items, parameter[]]] begin[:]
... | keyword[def] identifier[_accented_vowel_to_numbered] ( identifier[vowel] ):
literal[string]
keyword[for] identifier[numbered_vowel] , identifier[accented_vowel] keyword[in] identifier[_PINYIN_TONES] . identifier[items] ():
keyword[if] identifier[vowel] == identifier[accented_vowel] :
... | def _accented_vowel_to_numbered(vowel):
"""Convert an accented Pinyin vowel to a numbered Pinyin vowel."""
for (numbered_vowel, accented_vowel) in _PINYIN_TONES.items():
if vowel == accented_vowel:
return tuple(numbered_vowel) # depends on [control=['if'], data=[]] # depends on [control=['... |
def function(self, x, y, amp, alpha, beta, center_x, center_y):
"""
returns Moffat profile
"""
x_shift = x - center_x
y_shift = y - center_y
return amp * (1. + (x_shift**2+y_shift**2)/alpha**2)**(-beta) | def function[function, parameter[self, x, y, amp, alpha, beta, center_x, center_y]]:
constant[
returns Moffat profile
]
variable[x_shift] assign[=] binary_operation[name[x] - name[center_x]]
variable[y_shift] assign[=] binary_operation[name[y] - name[center_y]]
return[binary_... | keyword[def] identifier[function] ( identifier[self] , identifier[x] , identifier[y] , identifier[amp] , identifier[alpha] , identifier[beta] , identifier[center_x] , identifier[center_y] ):
literal[string]
identifier[x_shift] = identifier[x] - identifier[center_x]
identifier[y_shift] = i... | def function(self, x, y, amp, alpha, beta, center_x, center_y):
"""
returns Moffat profile
"""
x_shift = x - center_x
y_shift = y - center_y
return amp * (1.0 + (x_shift ** 2 + y_shift ** 2) / alpha ** 2) ** (-beta) |
def application(cls, f):
"""Decorate a function as responder that accepts the request as first
argument. This works like the :func:`responder` decorator but the
function is passed the request object as first argument and the
request object will be closed automatically::
@Re... | def function[application, parameter[cls, f]]:
constant[Decorate a function as responder that accepts the request as first
argument. This works like the :func:`responder` decorator but the
function is passed the request object as first argument and the
request object will be closed autom... | keyword[def] identifier[application] ( identifier[cls] , identifier[f] ):
literal[string]
keyword[def] identifier[application] (* identifier[args] ):
identifier[request] = identifier[cls] ( identifier[args] [- literal[int] ])
k... | def application(cls, f):
"""Decorate a function as responder that accepts the request as first
argument. This works like the :func:`responder` decorator but the
function is passed the request object as first argument and the
request object will be closed automatically::
@Reques... |
def deepcopy(original_obj):
"""
Creates a deep copy of an object with no crossed referenced lists or dicts,
useful when loading from yaml as anchors generate those cross-referenced
dicts and lists
Args:
original_obj(object): Object to deep copy
Return:
object: deep copy of the ... | def function[deepcopy, parameter[original_obj]]:
constant[
Creates a deep copy of an object with no crossed referenced lists or dicts,
useful when loading from yaml as anchors generate those cross-referenced
dicts and lists
Args:
original_obj(object): Object to deep copy
Return:
... | keyword[def] identifier[deepcopy] ( identifier[original_obj] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[original_obj] , identifier[list] ):
keyword[return] identifier[list] ( identifier[deepcopy] ( identifier[item] ) keyword[for] identifier[item] keyword[in] identifier... | def deepcopy(original_obj):
"""
Creates a deep copy of an object with no crossed referenced lists or dicts,
useful when loading from yaml as anchors generate those cross-referenced
dicts and lists
Args:
original_obj(object): Object to deep copy
Return:
object: deep copy of the ... |
def _transform_data(self, X):
"""Binarize the data for each column separately."""
if self._binarizers == []:
raise NotFittedError()
if self.binarize is not None:
X = binarize(X, threshold=self.binarize)
if len(self._binarizers) != X.shape[1]:
raise ... | def function[_transform_data, parameter[self, X]]:
constant[Binarize the data for each column separately.]
if compare[name[self]._binarizers equal[==] list[[]]] begin[:]
<ast.Raise object at 0x7da18c4ccbb0>
if compare[name[self].binarize is_not constant[None]] begin[:]
va... | keyword[def] identifier[_transform_data] ( identifier[self] , identifier[X] ):
literal[string]
keyword[if] identifier[self] . identifier[_binarizers] ==[]:
keyword[raise] identifier[NotFittedError] ()
keyword[if] identifier[self] . identifier[binarize] keyword[is] keywo... | def _transform_data(self, X):
"""Binarize the data for each column separately."""
if self._binarizers == []:
raise NotFittedError() # depends on [control=['if'], data=[]]
if self.binarize is not None:
X = binarize(X, threshold=self.binarize) # depends on [control=['if'], data=[]]
if le... |
def get_tfidf(self, term, document, normalized=False):
"""
Returns the Term-Frequency Inverse-Document-Frequency value for the given
term in the specified document. If normalized is True, term frequency will
be divided by the document length.
"""
tf = self.get_term_freque... | def function[get_tfidf, parameter[self, term, document, normalized]]:
constant[
Returns the Term-Frequency Inverse-Document-Frequency value for the given
term in the specified document. If normalized is True, term frequency will
be divided by the document length.
]
variab... | keyword[def] identifier[get_tfidf] ( identifier[self] , identifier[term] , identifier[document] , identifier[normalized] = keyword[False] ):
literal[string]
identifier[tf] = identifier[self] . identifier[get_term_frequency] ( identifier[term] , identifier[document] )
keyword[if] ... | def get_tfidf(self, term, document, normalized=False):
"""
Returns the Term-Frequency Inverse-Document-Frequency value for the given
term in the specified document. If normalized is True, term frequency will
be divided by the document length.
"""
tf = self.get_term_frequency(term... |
def _calibrate_quantized_sym(qsym, th_dict):
"""Given a dictionary containing the thresholds for quantizing the layers,
set the thresholds into the quantized symbol as the params of requantize operators.
"""
if th_dict is None or len(th_dict) == 0:
return qsym
num_layer_outputs = len(th_dict... | def function[_calibrate_quantized_sym, parameter[qsym, th_dict]]:
constant[Given a dictionary containing the thresholds for quantizing the layers,
set the thresholds into the quantized symbol as the params of requantize operators.
]
if <ast.BoolOp object at 0x7da1b204dd50> begin[:]
retur... | keyword[def] identifier[_calibrate_quantized_sym] ( identifier[qsym] , identifier[th_dict] ):
literal[string]
keyword[if] identifier[th_dict] keyword[is] keyword[None] keyword[or] identifier[len] ( identifier[th_dict] )== literal[int] :
keyword[return] identifier[qsym]
identifier[num_l... | def _calibrate_quantized_sym(qsym, th_dict):
"""Given a dictionary containing the thresholds for quantizing the layers,
set the thresholds into the quantized symbol as the params of requantize operators.
"""
if th_dict is None or len(th_dict) == 0:
return qsym # depends on [control=['if'], data... |
def _create_index(self, table_name, index_columns):
"""
Creates an index over multiple columns of a given table.
Parameters
----------
table_name : str
index_columns : iterable of str
Which columns should be indexed
"""
logger.info(
... | def function[_create_index, parameter[self, table_name, index_columns]]:
constant[
Creates an index over multiple columns of a given table.
Parameters
----------
table_name : str
index_columns : iterable of str
Which columns should be indexed
]
... | keyword[def] identifier[_create_index] ( identifier[self] , identifier[table_name] , identifier[index_columns] ):
literal[string]
identifier[logger] . identifier[info] (
literal[string] ,
identifier[table_name] ,
literal[string] . identifier[join] ( identifier[index_colu... | def _create_index(self, table_name, index_columns):
"""
Creates an index over multiple columns of a given table.
Parameters
----------
table_name : str
index_columns : iterable of str
Which columns should be indexed
"""
logger.info('Creating index on... |
def B(self):
'''
Point whose coordinates are (maxX,minY,origin.z), Point.
'''
return Point(self.maxX, self.minY, self.origin.z) | def function[B, parameter[self]]:
constant[
Point whose coordinates are (maxX,minY,origin.z), Point.
]
return[call[name[Point], parameter[name[self].maxX, name[self].minY, name[self].origin.z]]] | keyword[def] identifier[B] ( identifier[self] ):
literal[string]
keyword[return] identifier[Point] ( identifier[self] . identifier[maxX] , identifier[self] . identifier[minY] , identifier[self] . identifier[origin] . identifier[z] ) | def B(self):
"""
Point whose coordinates are (maxX,minY,origin.z), Point.
"""
return Point(self.maxX, self.minY, self.origin.z) |
def drop_neutral_categories_from_corpus(self):
'''
Returns
-------
PriorFactory
'''
neutral_categories = self._get_neutral_categories()
self.term_doc_mat = self.term_doc_mat.remove_categories(neutral_categories)
self._reindex_priors()
return self | def function[drop_neutral_categories_from_corpus, parameter[self]]:
constant[
Returns
-------
PriorFactory
]
variable[neutral_categories] assign[=] call[name[self]._get_neutral_categories, parameter[]]
name[self].term_doc_mat assign[=] call[name[self].term_doc_mat.remove_categories, para... | keyword[def] identifier[drop_neutral_categories_from_corpus] ( identifier[self] ):
literal[string]
identifier[neutral_categories] = identifier[self] . identifier[_get_neutral_categories] ()
identifier[self] . identifier[term_doc_mat] = identifier[self] . identifier[term_doc_mat] . identifier[remove_categori... | def drop_neutral_categories_from_corpus(self):
"""
Returns
-------
PriorFactory
"""
neutral_categories = self._get_neutral_categories()
self.term_doc_mat = self.term_doc_mat.remove_categories(neutral_categories)
self._reindex_priors()
return self |
def decimal_day_to_day_hour_min_sec(
self,
daysFloat):
"""*Convert a day from decimal format to hours mins and sec*
Precision should be respected.
**Key Arguments:**
- ``daysFloat`` -- the day as a decimal.
**Return:**
- ``daysInt`` -- ... | def function[decimal_day_to_day_hour_min_sec, parameter[self, daysFloat]]:
constant[*Convert a day from decimal format to hours mins and sec*
Precision should be respected.
**Key Arguments:**
- ``daysFloat`` -- the day as a decimal.
**Return:**
- ``daysInt`` -... | keyword[def] identifier[decimal_day_to_day_hour_min_sec] (
identifier[self] ,
identifier[daysFloat] ):
literal[string]
identifier[self] . identifier[log] . identifier[info] (
literal[string] )
identifier[daysInt] = identifier[int] ( identifier[daysFloat] )
identifier[h... | def decimal_day_to_day_hour_min_sec(self, daysFloat):
"""*Convert a day from decimal format to hours mins and sec*
Precision should be respected.
**Key Arguments:**
- ``daysFloat`` -- the day as a decimal.
**Return:**
- ``daysInt`` -- day as an integer
... |
def _create_decode_layer(self):
"""Create the decoding layer of the network.
Returns
-------
self
"""
with tf.name_scope("decoder"):
activation = tf.add(
tf.matmul(self.encode, tf.transpose(self.W_)),
self.bv_
)
... | def function[_create_decode_layer, parameter[self]]:
constant[Create the decoding layer of the network.
Returns
-------
self
]
with call[name[tf].name_scope, parameter[constant[decoder]]] begin[:]
variable[activation] assign[=] call[name[tf].add, paramet... | keyword[def] identifier[_create_decode_layer] ( identifier[self] ):
literal[string]
keyword[with] identifier[tf] . identifier[name_scope] ( literal[string] ):
identifier[activation] = identifier[tf] . identifier[add] (
identifier[tf] . identifier[matmul] ( identifier[sel... | def _create_decode_layer(self):
"""Create the decoding layer of the network.
Returns
-------
self
"""
with tf.name_scope('decoder'):
activation = tf.add(tf.matmul(self.encode, tf.transpose(self.W_)), self.bv_)
if self.dec_act_func:
self.reconstructio... |
def from_str(cls, human_readable_str, decimal=False, bits=False):
"""attempt to parse a size in bytes from a human-readable string."""
divisor = 1000 if decimal else 1024
num = []
c = ""
for c in human_readable_str:
if c not in cls.digits:
break
... | def function[from_str, parameter[cls, human_readable_str, decimal, bits]]:
constant[attempt to parse a size in bytes from a human-readable string.]
variable[divisor] assign[=] <ast.IfExp object at 0x7da1b034af50>
variable[num] assign[=] list[[]]
variable[c] assign[=] constant[]
f... | keyword[def] identifier[from_str] ( identifier[cls] , identifier[human_readable_str] , identifier[decimal] = keyword[False] , identifier[bits] = keyword[False] ):
literal[string]
identifier[divisor] = literal[int] keyword[if] identifier[decimal] keyword[else] literal[int]
identifier[n... | def from_str(cls, human_readable_str, decimal=False, bits=False):
"""attempt to parse a size in bytes from a human-readable string."""
divisor = 1000 if decimal else 1024
num = []
c = ''
for c in human_readable_str:
if c not in cls.digits:
break # depends on [control=['if'], dat... |
def subspace_detector_plot(detector, stachans, size, **kwargs):
"""
Plotting for the subspace detector class.
Plot the output basis vectors for the detector at the given dimension.
Corresponds to the first n horizontal vectors of the V matrix.
:type detector: :class:`eqcorrscan.core.subspace.Dete... | def function[subspace_detector_plot, parameter[detector, stachans, size]]:
constant[
Plotting for the subspace detector class.
Plot the output basis vectors for the detector at the given dimension.
Corresponds to the first n horizontal vectors of the V matrix.
:type detector: :class:`eqcorrsc... | keyword[def] identifier[subspace_detector_plot] ( identifier[detector] , identifier[stachans] , identifier[size] ,** identifier[kwargs] ):
literal[string]
keyword[import] identifier[matplotlib] . identifier[pyplot] keyword[as] identifier[plt]
keyword[if] identifier[stachans] == literal[string] k... | def subspace_detector_plot(detector, stachans, size, **kwargs):
"""
Plotting for the subspace detector class.
Plot the output basis vectors for the detector at the given dimension.
Corresponds to the first n horizontal vectors of the V matrix.
:type detector: :class:`eqcorrscan.core.subspace.Dete... |
def dtypes_summary(df):
""" Takes in a dataframe and returns a dataframe with
information on the data-types present in each column.
Parameters:
df - DataFrame
Dataframe to summarize
"""
output_df = pd.DataFrame([])
row_count = df.shape[0]
row_indexes = ['rows_numerical','rows_str... | def function[dtypes_summary, parameter[df]]:
constant[ Takes in a dataframe and returns a dataframe with
information on the data-types present in each column.
Parameters:
df - DataFrame
Dataframe to summarize
]
variable[output_df] assign[=] call[name[pd].DataFrame, parameter[list... | keyword[def] identifier[dtypes_summary] ( identifier[df] ):
literal[string]
identifier[output_df] = identifier[pd] . identifier[DataFrame] ([])
identifier[row_count] = identifier[df] . identifier[shape] [ literal[int] ]
identifier[row_indexes] =[ literal[string] , literal[string] , literal[string... | def dtypes_summary(df):
""" Takes in a dataframe and returns a dataframe with
information on the data-types present in each column.
Parameters:
df - DataFrame
Dataframe to summarize
"""
output_df = pd.DataFrame([])
row_count = df.shape[0]
row_indexes = ['rows_numerical', 'rows_st... |
def create_subparsers(self, parser):
""" get config for subparser and create commands"""
subparsers = parser.add_subparsers()
for name in self.config['subparsers']:
subparser = subparsers.add_parser(name)
self.create_commands(self.config['subparsers'][name], subparser) | def function[create_subparsers, parameter[self, parser]]:
constant[ get config for subparser and create commands]
variable[subparsers] assign[=] call[name[parser].add_subparsers, parameter[]]
for taget[name[name]] in starred[call[name[self].config][constant[subparsers]]] begin[:]
... | keyword[def] identifier[create_subparsers] ( identifier[self] , identifier[parser] ):
literal[string]
identifier[subparsers] = identifier[parser] . identifier[add_subparsers] ()
keyword[for] identifier[name] keyword[in] identifier[self] . identifier[config] [ literal[string] ]:
... | def create_subparsers(self, parser):
""" get config for subparser and create commands"""
subparsers = parser.add_subparsers()
for name in self.config['subparsers']:
subparser = subparsers.add_parser(name)
self.create_commands(self.config['subparsers'][name], subparser) # depends on [control... |
def add_task(self, cor, name=None, finalizer=None, stop_timeout=1.0, parent=None):
"""Schedule a task to run on the background event loop.
This method will start the given coroutine as a task and keep track
of it so that it can be properly shutdown which the event loop is
stopped.
... | def function[add_task, parameter[self, cor, name, finalizer, stop_timeout, parent]]:
constant[Schedule a task to run on the background event loop.
This method will start the given coroutine as a task and keep track
of it so that it can be properly shutdown which the event loop is
stopp... | keyword[def] identifier[add_task] ( identifier[self] , identifier[cor] , identifier[name] = keyword[None] , identifier[finalizer] = keyword[None] , identifier[stop_timeout] = literal[int] , identifier[parent] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[stopping] :... | def add_task(self, cor, name=None, finalizer=None, stop_timeout=1.0, parent=None):
"""Schedule a task to run on the background event loop.
This method will start the given coroutine as a task and keep track
of it so that it can be properly shutdown which the event loop is
stopped.
... |
def sext(self, width):
"""Sign-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits).
"""
width = operator.index(width)
if width < self._width:
raise ValueError('sign extending to a smaller wi... | def function[sext, parameter[self, width]]:
constant[Sign-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits).
]
variable[width] assign[=] call[name[operator].index, parameter[name[width]]]
if compare[n... | keyword[def] identifier[sext] ( identifier[self] , identifier[width] ):
literal[string]
identifier[width] = identifier[operator] . identifier[index] ( identifier[width] )
keyword[if] identifier[width] < identifier[self] . identifier[_width] :
keyword[raise] identifier[ValueE... | def sext(self, width):
"""Sign-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits).
"""
width = operator.index(width)
if width < self._width:
raise ValueError('sign extending to a smaller width') # depends... |
def wcs_pix_transform(ct, i, format=0):
"""Computes the WCS corrected pixel value given a coordinate
transformation and the raw pixel value.
Input:
ct coordinate transformation. instance of coord_tran.
i raw pixel intensity.
format format string (optional).
Returns:
WCS cor... | def function[wcs_pix_transform, parameter[ct, i, format]]:
constant[Computes the WCS corrected pixel value given a coordinate
transformation and the raw pixel value.
Input:
ct coordinate transformation. instance of coord_tran.
i raw pixel intensity.
format format string (optiona... | keyword[def] identifier[wcs_pix_transform] ( identifier[ct] , identifier[i] , identifier[format] = literal[int] ):
literal[string]
identifier[z1] = identifier[float] ( identifier[ct] . identifier[z1] )
identifier[z2] = identifier[float] ( identifier[ct] . identifier[z2] )
identifier[i] = identifi... | def wcs_pix_transform(ct, i, format=0):
"""Computes the WCS corrected pixel value given a coordinate
transformation and the raw pixel value.
Input:
ct coordinate transformation. instance of coord_tran.
i raw pixel intensity.
format format string (optional).
Returns:
WCS cor... |
def latch_config_variables(self):
"""Latch the current value of all config variables as python objects.
This function will capture the current value of all config variables
at the time that this method is called. It must be called after
start() has been called so that any default value... | def function[latch_config_variables, parameter[self]]:
constant[Latch the current value of all config variables as python objects.
This function will capture the current value of all config variables
at the time that this method is called. It must be called after
start() has been calle... | keyword[def] identifier[latch_config_variables] ( identifier[self] ):
literal[string]
keyword[return] { identifier[desc] . identifier[name] : identifier[desc] . identifier[latch] () keyword[for] identifier[desc] keyword[in] identifier[self] . identifier[_config_variables] . identifier[values] (... | def latch_config_variables(self):
"""Latch the current value of all config variables as python objects.
This function will capture the current value of all config variables
at the time that this method is called. It must be called after
start() has been called so that any default values in... |
def handle_fk_field(self, obj, field):
"""
Called to handle a ForeignKey (we need to treat them slightly
differently from regular fields).
"""
self._start_relational_field(field)
related = getattr(obj, field.name)
if related is not None:
if self.use_na... | def function[handle_fk_field, parameter[self, obj, field]]:
constant[
Called to handle a ForeignKey (we need to treat them slightly
differently from regular fields).
]
call[name[self]._start_relational_field, parameter[name[field]]]
variable[related] assign[=] call[name[g... | keyword[def] identifier[handle_fk_field] ( identifier[self] , identifier[obj] , identifier[field] ):
literal[string]
identifier[self] . identifier[_start_relational_field] ( identifier[field] )
identifier[related] = identifier[getattr] ( identifier[obj] , identifier[field] . identifier[nam... | def handle_fk_field(self, obj, field):
"""
Called to handle a ForeignKey (we need to treat them slightly
differently from regular fields).
"""
self._start_relational_field(field)
related = getattr(obj, field.name)
if related is not None:
if self.use_natural_keys and hasat... |
def xyz2lonlat(x,y,z):
"""
Convert x,y,z representation of points *on the unit sphere* of the
spherical triangulation to lon / lat (radians).
Note - no check is made here that (x,y,z) are unit vectors
"""
xs = np.array(x)
ys = np.array(y)
zs = np.array(z)
lons = np.arctan2(ys, xs)... | def function[xyz2lonlat, parameter[x, y, z]]:
constant[
Convert x,y,z representation of points *on the unit sphere* of the
spherical triangulation to lon / lat (radians).
Note - no check is made here that (x,y,z) are unit vectors
]
variable[xs] assign[=] call[name[np].array, parameter[n... | keyword[def] identifier[xyz2lonlat] ( identifier[x] , identifier[y] , identifier[z] ):
literal[string]
identifier[xs] = identifier[np] . identifier[array] ( identifier[x] )
identifier[ys] = identifier[np] . identifier[array] ( identifier[y] )
identifier[zs] = identifier[np] . identifier[array] (... | def xyz2lonlat(x, y, z):
"""
Convert x,y,z representation of points *on the unit sphere* of the
spherical triangulation to lon / lat (radians).
Note - no check is made here that (x,y,z) are unit vectors
"""
xs = np.array(x)
ys = np.array(y)
zs = np.array(z)
lons = np.arctan2(ys, xs)... |
def section(self, dept, course_number, sect_number):
"""Return a single section object for the given section. All arguments
should be strings. Throws a `ValueError` if the section is not found.
>>> lgst101_bfs = r.course('lgst', '101', '301')
"""
section_id = dept + course_numbe... | def function[section, parameter[self, dept, course_number, sect_number]]:
constant[Return a single section object for the given section. All arguments
should be strings. Throws a `ValueError` if the section is not found.
>>> lgst101_bfs = r.course('lgst', '101', '301')
]
variabl... | keyword[def] identifier[section] ( identifier[self] , identifier[dept] , identifier[course_number] , identifier[sect_number] ):
literal[string]
identifier[section_id] = identifier[dept] + identifier[course_number] + identifier[sect_number]
identifier[sections] = identifier[self] . identif... | def section(self, dept, course_number, sect_number):
"""Return a single section object for the given section. All arguments
should be strings. Throws a `ValueError` if the section is not found.
>>> lgst101_bfs = r.course('lgst', '101', '301')
"""
section_id = dept + course_number + sect... |
def convert(model, name=None, initial_types=None, doc_string='', target_opset=None,
targeted_onnx=onnx.__version__, custom_conversion_functions=None, custom_shape_calculators=None):
'''
This function converts the specified CoreML model into its ONNX counterpart. Some information such as the produced... | def function[convert, parameter[model, name, initial_types, doc_string, target_opset, targeted_onnx, custom_conversion_functions, custom_shape_calculators]]:
constant[
This function converts the specified CoreML model into its ONNX counterpart. Some information such as the produced
ONNX model name can b... | keyword[def] identifier[convert] ( identifier[model] , identifier[name] = keyword[None] , identifier[initial_types] = keyword[None] , identifier[doc_string] = literal[string] , identifier[target_opset] = keyword[None] ,
identifier[targeted_onnx] = identifier[onnx] . identifier[__version__] , identifier[custom_conver... | def convert(model, name=None, initial_types=None, doc_string='', target_opset=None, targeted_onnx=onnx.__version__, custom_conversion_functions=None, custom_shape_calculators=None):
"""
This function converts the specified CoreML model into its ONNX counterpart. Some information such as the produced
ONNX mo... |
def set_currency(self, currency_id):
"""
Set transaction currency code from given currency id, e.g. set 840 from 'USD'
"""
try:
self.currency = currency_codes[currency_id]
self.IsoMessage.FieldData(49, self.currency)
self.rebuild()
except KeyEr... | def function[set_currency, parameter[self, currency_id]]:
constant[
Set transaction currency code from given currency id, e.g. set 840 from 'USD'
]
<ast.Try object at 0x7da20e954940> | keyword[def] identifier[set_currency] ( identifier[self] , identifier[currency_id] ):
literal[string]
keyword[try] :
identifier[self] . identifier[currency] = identifier[currency_codes] [ identifier[currency_id] ]
identifier[self] . identifier[IsoMessage] . identifier[Fiel... | def set_currency(self, currency_id):
"""
Set transaction currency code from given currency id, e.g. set 840 from 'USD'
"""
try:
self.currency = currency_codes[currency_id]
self.IsoMessage.FieldData(49, self.currency)
self.rebuild() # depends on [control=['try'], data=[]]... |
def get(self):
""" get method """
try:
cluster = self.get_argument_cluster()
role = self.get_argument_role()
environ = self.get_argument_environ()
topology_name = self.get_argument_topology()
container = self.get_argument(constants.PARAM_CONTAINER)
path = self.get_argument(co... | def function[get, parameter[self]]:
constant[ get method ]
<ast.Try object at 0x7da20c76eaa0> | keyword[def] identifier[get] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[cluster] = identifier[self] . identifier[get_argument_cluster] ()
identifier[role] = identifier[self] . identifier[get_argument_role] ()
identifier[environ] = identifier[self] . identifier[get_... | def get(self):
""" get method """
try:
cluster = self.get_argument_cluster()
role = self.get_argument_role()
environ = self.get_argument_environ()
topology_name = self.get_argument_topology()
container = self.get_argument(constants.PARAM_CONTAINER)
path = self.get... |
def add_attributes(self, data, type):
""" add required attributes """
for attr, ancestry in type.attributes():
name = '_%s' % attr.name
value = attr.get_default()
setattr(data, name, value) | def function[add_attributes, parameter[self, data, type]]:
constant[ add required attributes ]
for taget[tuple[[<ast.Name object at 0x7da2054a5510>, <ast.Name object at 0x7da2054a5150>]]] in starred[call[name[type].attributes, parameter[]]] begin[:]
variable[name] assign[=] binary_operat... | keyword[def] identifier[add_attributes] ( identifier[self] , identifier[data] , identifier[type] ):
literal[string]
keyword[for] identifier[attr] , identifier[ancestry] keyword[in] identifier[type] . identifier[attributes] ():
identifier[name] = literal[string] % identifier[attr] . ... | def add_attributes(self, data, type):
""" add required attributes """
for (attr, ancestry) in type.attributes():
name = '_%s' % attr.name
value = attr.get_default()
setattr(data, name, value) # depends on [control=['for'], data=[]] |
def confd_state_loaded_data_models_data_model_namespace(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
loaded_data_models = ET.SubElement(confd_state, "l... | def function[confd_state_loaded_data_models_data_model_namespace, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[confd_state] assign[=] call[name[ET].SubElement, parameter[name[config], constant[con... | keyword[def] identifier[confd_state_loaded_data_models_data_model_namespace] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[confd_state] = identifier[ET] . identifier[SubElement] ( identi... | def confd_state_loaded_data_models_data_model_namespace(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
confd_state = ET.SubElement(config, 'confd-state', xmlns='http://tail-f.com/yang/confd-monitoring')
loaded_data_models = ET.SubElement(confd_state, 'loaded-data-model... |
def postprocess(self):
"""Submit a postprocessing script after collation"""
assert self.postscript
envmod.setup()
envmod.module('load', 'pbs')
cmd = 'qsub {script}'.format(script=self.postscript)
cmd = shlex.split(cmd)
rc = sp.call(cmd)
assert rc == 0, '... | def function[postprocess, parameter[self]]:
constant[Submit a postprocessing script after collation]
assert[name[self].postscript]
call[name[envmod].setup, parameter[]]
call[name[envmod].module, parameter[constant[load], constant[pbs]]]
variable[cmd] assign[=] call[constant[qsub {scr... | keyword[def] identifier[postprocess] ( identifier[self] ):
literal[string]
keyword[assert] identifier[self] . identifier[postscript]
identifier[envmod] . identifier[setup] ()
identifier[envmod] . identifier[module] ( literal[string] , literal[string] )
identifier[cmd] ... | def postprocess(self):
"""Submit a postprocessing script after collation"""
assert self.postscript
envmod.setup()
envmod.module('load', 'pbs')
cmd = 'qsub {script}'.format(script=self.postscript)
cmd = shlex.split(cmd)
rc = sp.call(cmd)
assert rc == 0, 'Postprocessing script submission f... |
def get_minions():
'''
Return a list of minion identifiers from a request of the view.
'''
options = _get_options(ret=None)
# Make sure the views are valid, which includes the minions..
if not ensure_views():
return []
# Make the request for the view..
_response = _request("GET... | def function[get_minions, parameter[]]:
constant[
Return a list of minion identifiers from a request of the view.
]
variable[options] assign[=] call[name[_get_options], parameter[]]
if <ast.UnaryOp object at 0x7da1b23462f0> begin[:]
return[list[[]]]
variable[_response] as... | keyword[def] identifier[get_minions] ():
literal[string]
identifier[options] = identifier[_get_options] ( identifier[ret] = keyword[None] )
keyword[if] keyword[not] identifier[ensure_views] ():
keyword[return] []
identifier[_response] = identifier[_request] ( literal[st... | def get_minions():
"""
Return a list of minion identifiers from a request of the view.
"""
options = _get_options(ret=None)
# Make sure the views are valid, which includes the minions..
if not ensure_views():
return [] # depends on [control=['if'], data=[]]
# Make the request for th... |
def mean_length(infile, limit=None):
'''Returns the mean length of the sequences in the input file. By default uses all sequences. To limit to the first N sequences, use limit=N'''
total = 0
count = 0
seq_reader = sequences.file_reader(infile)
for seq in seq_reader:
total += len(seq)
... | def function[mean_length, parameter[infile, limit]]:
constant[Returns the mean length of the sequences in the input file. By default uses all sequences. To limit to the first N sequences, use limit=N]
variable[total] assign[=] constant[0]
variable[count] assign[=] constant[0]
variable[se... | keyword[def] identifier[mean_length] ( identifier[infile] , identifier[limit] = keyword[None] ):
literal[string]
identifier[total] = literal[int]
identifier[count] = literal[int]
identifier[seq_reader] = identifier[sequences] . identifier[file_reader] ( identifier[infile] )
keyword[for] i... | def mean_length(infile, limit=None):
"""Returns the mean length of the sequences in the input file. By default uses all sequences. To limit to the first N sequences, use limit=N"""
total = 0
count = 0
seq_reader = sequences.file_reader(infile)
for seq in seq_reader:
total += len(seq)
... |
def append_flipped_images(self):
"""Only flip boxes coordinates, images will be flipped when loading into network"""
logger.info('%s append flipped images to roidb' % self._name)
roidb_flipped = []
for roi_rec in self._roidb:
boxes = roi_rec['boxes'].copy()
oldx1 ... | def function[append_flipped_images, parameter[self]]:
constant[Only flip boxes coordinates, images will be flipped when loading into network]
call[name[logger].info, parameter[binary_operation[constant[%s append flipped images to roidb] <ast.Mod object at 0x7da2590d6920> name[self]._name]]]
vari... | keyword[def] identifier[append_flipped_images] ( identifier[self] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] % identifier[self] . identifier[_name] )
identifier[roidb_flipped] =[]
keyword[for] identifier[roi_rec] keyword[in] identifier[self] . id... | def append_flipped_images(self):
"""Only flip boxes coordinates, images will be flipped when loading into network"""
logger.info('%s append flipped images to roidb' % self._name)
roidb_flipped = []
for roi_rec in self._roidb:
boxes = roi_rec['boxes'].copy()
oldx1 = boxes[:, 0].copy()
... |
def get_assessment_taken_ids_by_bank(self, bank_id):
"""Gets the list of ``AssessmentTaken`` ``Ids`` associated with a ``Bank``.
arg: bank_id (osid.id.Id): ``Id`` of the ``Bank``
return: (osid.id.IdList) - list of related assessment taken
``Ids``
raise: NotFound - `... | def function[get_assessment_taken_ids_by_bank, parameter[self, bank_id]]:
constant[Gets the list of ``AssessmentTaken`` ``Ids`` associated with a ``Bank``.
arg: bank_id (osid.id.Id): ``Id`` of the ``Bank``
return: (osid.id.IdList) - list of related assessment taken
``Ids``
... | keyword[def] identifier[get_assessment_taken_ids_by_bank] ( identifier[self] , identifier[bank_id] ):
literal[string]
identifier[id_list] =[]
keyword[for] identifier[assessment_taken] keyword[in] identifier[self] . identifier[get_assessments_taken_by_bank] ( identifier... | def get_assessment_taken_ids_by_bank(self, bank_id):
"""Gets the list of ``AssessmentTaken`` ``Ids`` associated with a ``Bank``.
arg: bank_id (osid.id.Id): ``Id`` of the ``Bank``
return: (osid.id.IdList) - list of related assessment taken
``Ids``
raise: NotFound - ``ban... |
def _parse_ergodic_cutoff(self):
"""Get a numeric value from the ergodic_cutoff input,
which can be 'on' or 'off'.
"""
ec_is_str = isinstance(self.ergodic_cutoff, str)
if ec_is_str and self.ergodic_cutoff.lower() == 'on':
if self.sliding_window:
return... | def function[_parse_ergodic_cutoff, parameter[self]]:
constant[Get a numeric value from the ergodic_cutoff input,
which can be 'on' or 'off'.
]
variable[ec_is_str] assign[=] call[name[isinstance], parameter[name[self].ergodic_cutoff, name[str]]]
if <ast.BoolOp object at 0x7da1b07... | keyword[def] identifier[_parse_ergodic_cutoff] ( identifier[self] ):
literal[string]
identifier[ec_is_str] = identifier[isinstance] ( identifier[self] . identifier[ergodic_cutoff] , identifier[str] )
keyword[if] identifier[ec_is_str] keyword[and] identifier[self] . identifier[ergodic_cu... | def _parse_ergodic_cutoff(self):
"""Get a numeric value from the ergodic_cutoff input,
which can be 'on' or 'off'.
"""
ec_is_str = isinstance(self.ergodic_cutoff, str)
if ec_is_str and self.ergodic_cutoff.lower() == 'on':
if self.sliding_window:
return 1.0 / self.lag_time... |
def golowtran(c1: Dict[str, Any]) -> xarray.Dataset:
"""directly run Fortran code"""
# %% default parameters
c1.setdefault('time', None)
defp = ('h1', 'h2', 'angle', 'im', 'iseasn', 'ird1', 'range_km', 'zmdl', 'p', 't')
for p in defp:
c1.setdefault(p, 0)
c1.setdefault('wmol', [0]*12)
# %% ... | def function[golowtran, parameter[c1]]:
constant[directly run Fortran code]
call[name[c1].setdefault, parameter[constant[time], constant[None]]]
variable[defp] assign[=] tuple[[<ast.Constant object at 0x7da20cabfbb0>, <ast.Constant object at 0x7da20cabfeb0>, <ast.Constant object at 0x7da20cabee6... | keyword[def] identifier[golowtran] ( identifier[c1] : identifier[Dict] [ identifier[str] , identifier[Any] ])-> identifier[xarray] . identifier[Dataset] :
literal[string]
identifier[c1] . identifier[setdefault] ( literal[string] , keyword[None] )
identifier[defp] =( literal[string] , literal[str... | def golowtran(c1: Dict[str, Any]) -> xarray.Dataset:
"""directly run Fortran code"""
# %% default parameters
c1.setdefault('time', None)
defp = ('h1', 'h2', 'angle', 'im', 'iseasn', 'ird1', 'range_km', 'zmdl', 'p', 't')
for p in defp:
c1.setdefault(p, 0) # depends on [control=['for'], data=... |
def open(self):
'''
Open the channel for communication.
'''
args = Writer()
args.write_shortstr('')
self.send_frame(MethodFrame(self.channel_id, 20, 10, args))
self.channel.add_synchronous_cb(self._recv_open_ok) | def function[open, parameter[self]]:
constant[
Open the channel for communication.
]
variable[args] assign[=] call[name[Writer], parameter[]]
call[name[args].write_shortstr, parameter[constant[]]]
call[name[self].send_frame, parameter[call[name[MethodFrame], parameter[nam... | keyword[def] identifier[open] ( identifier[self] ):
literal[string]
identifier[args] = identifier[Writer] ()
identifier[args] . identifier[write_shortstr] ( literal[string] )
identifier[self] . identifier[send_frame] ( identifier[MethodFrame] ( identifier[self] . identifier[channe... | def open(self):
"""
Open the channel for communication.
"""
args = Writer()
args.write_shortstr('')
self.send_frame(MethodFrame(self.channel_id, 20, 10, args))
self.channel.add_synchronous_cb(self._recv_open_ok) |
def do_time(self, params):
"""
\x1b[1mNAME\x1b[0m
time - Measures elapsed seconds after running commands
\x1b[1mSYNOPSIS\x1b[0m
time <cmd1> <cmd2> ... <cmdN>
\x1b[1mEXAMPLES\x1b[0m
> time 'loop 10 0 "create /foo_ bar ephemeral=false sequence=true"'
Took 0.05585 seconds
... | def function[do_time, parameter[self, params]]:
constant[
[1mNAME[0m
time - Measures elapsed seconds after running commands
[1mSYNOPSIS[0m
time <cmd1> <cmd2> ... <cmdN>
[1mEXAMPLES[0m
> time 'loop 10 0 "create /foo_ bar ephemeral=false sequence=true"'
Took 0.05585 seconds... | keyword[def] identifier[do_time] ( identifier[self] , identifier[params] ):
literal[string]
identifier[start] = identifier[time] . identifier[time] ()
keyword[for] identifier[cmd] keyword[in] identifier[params] . identifier[cmds] :
keyword[try] :
identifier... | def do_time(self, params):
"""
\x1b[1mNAME\x1b[0m
time - Measures elapsed seconds after running commands
\x1b[1mSYNOPSIS\x1b[0m
time <cmd1> <cmd2> ... <cmdN>
\x1b[1mEXAMPLES\x1b[0m
> time 'loop 10 0 "create /foo_ bar ephemeral=false sequence=true"'
Took 0.05585 seconds
"""
... |
def is_url(value, **kwargs):
"""Indicate whether ``value`` is a URL.
.. note::
URL validation is...complicated. The methodology that we have
adopted here is *generally* compliant with
`RFC 1738 <https://tools.ietf.org/html/rfc1738>`_,
`RFC 6761 <https://tools.ietf.org/html/rfc6761>`_,
... | def function[is_url, parameter[value]]:
constant[Indicate whether ``value`` is a URL.
.. note::
URL validation is...complicated. The methodology that we have
adopted here is *generally* compliant with
`RFC 1738 <https://tools.ietf.org/html/rfc1738>`_,
`RFC 6761 <https://tools.ietf.... | keyword[def] identifier[is_url] ( identifier[value] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
identifier[value] = identifier[validators] . identifier[url] ( identifier[value] ,** identifier[kwargs] )
keyword[except] identifier[SyntaxError] keyword[as] identifier[error] :
... | def is_url(value, **kwargs):
"""Indicate whether ``value`` is a URL.
.. note::
URL validation is...complicated. The methodology that we have
adopted here is *generally* compliant with
`RFC 1738 <https://tools.ietf.org/html/rfc1738>`_,
`RFC 6761 <https://tools.ietf.org/html/rfc6761>`_,
... |
def exit(self, code=None, msg=None):
"""Application exit method with proper exit code
The method will run the Python standard sys.exit() with the exit code
previously defined via :py:meth:`~tcex.tcex.TcEx.exit_code` or provided
during the call of this method.
Args:
... | def function[exit, parameter[self, code, msg]]:
constant[Application exit method with proper exit code
The method will run the Python standard sys.exit() with the exit code
previously defined via :py:meth:`~tcex.tcex.TcEx.exit_code` or provided
during the call of this method.
A... | keyword[def] identifier[exit] ( identifier[self] , identifier[code] = keyword[None] , identifier[msg] = keyword[None] ):
literal[string]
keyword[if] identifier[msg] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[code] keyword[in] [ literal[int] , literal... | def exit(self, code=None, msg=None):
"""Application exit method with proper exit code
The method will run the Python standard sys.exit() with the exit code
previously defined via :py:meth:`~tcex.tcex.TcEx.exit_code` or provided
during the call of this method.
Args:
code... |
def _rebuild_key_ids(self):
"""Rebuild the internal key to index mapping."""
self._key_ids = collections.defaultdict(list)
for i, x in enumerate(self._pairs):
self._key_ids[x[0]].append(i) | def function[_rebuild_key_ids, parameter[self]]:
constant[Rebuild the internal key to index mapping.]
name[self]._key_ids assign[=] call[name[collections].defaultdict, parameter[name[list]]]
for taget[tuple[[<ast.Name object at 0x7da1b26ac730>, <ast.Name object at 0x7da1b26adab0>]]] in starred[c... | keyword[def] identifier[_rebuild_key_ids] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_key_ids] = identifier[collections] . identifier[defaultdict] ( identifier[list] )
keyword[for] identifier[i] , identifier[x] keyword[in] identifier[enumerate] ( identifier[self... | def _rebuild_key_ids(self):
"""Rebuild the internal key to index mapping."""
self._key_ids = collections.defaultdict(list)
for (i, x) in enumerate(self._pairs):
self._key_ids[x[0]].append(i) # depends on [control=['for'], data=[]] |
def load_or_create_config(self, filename, config=None):
"""Loads a config from disk. Defaults to a random config if none is specified"""
os.makedirs(os.path.dirname(os.path.expanduser(filename)), exist_ok=True)
if os.path.exists(filename):
return self.load(filename)
if(conf... | def function[load_or_create_config, parameter[self, filename, config]]:
constant[Loads a config from disk. Defaults to a random config if none is specified]
call[name[os].makedirs, parameter[call[name[os].path.dirname, parameter[call[name[os].path.expanduser, parameter[name[filename]]]]]]]
if c... | keyword[def] identifier[load_or_create_config] ( identifier[self] , identifier[filename] , identifier[config] = keyword[None] ):
literal[string]
identifier[os] . identifier[makedirs] ( identifier[os] . identifier[path] . identifier[dirname] ( identifier[os] . identifier[path] . identifier[expanduse... | def load_or_create_config(self, filename, config=None):
"""Loads a config from disk. Defaults to a random config if none is specified"""
os.makedirs(os.path.dirname(os.path.expanduser(filename)), exist_ok=True)
if os.path.exists(filename):
return self.load(filename) # depends on [control=['if'], d... |
def summary_stats(data):
"""
Returns a :class:`~bandicoot.helper.maths.SummaryStats` object
containing statistics on the given distribution.
Examples
--------
>>> summary_stats([0, 1])
SummaryStats(mean=0.5, std=0.5, min=0.0, max=1.0, median=0.5, skewness=0.0, kurtosis=1.0, distribution=[0,... | def function[summary_stats, parameter[data]]:
constant[
Returns a :class:`~bandicoot.helper.maths.SummaryStats` object
containing statistics on the given distribution.
Examples
--------
>>> summary_stats([0, 1])
SummaryStats(mean=0.5, std=0.5, min=0.0, max=1.0, median=0.5, skewness=0.0,... | keyword[def] identifier[summary_stats] ( identifier[data] ):
literal[string]
keyword[if] identifier[data] keyword[is] keyword[None] :
identifier[data] =[]
identifier[data] = identifier[sorted] ( identifier[data] )
keyword[if] identifier[len] ( identifier[data] )< literal[int] :
... | def summary_stats(data):
"""
Returns a :class:`~bandicoot.helper.maths.SummaryStats` object
containing statistics on the given distribution.
Examples
--------
>>> summary_stats([0, 1])
SummaryStats(mean=0.5, std=0.5, min=0.0, max=1.0, median=0.5, skewness=0.0, kurtosis=1.0, distribution=[0,... |
def _format_terse(tcolor, comps, ret, colors, tabular):
'''
Terse formatting of a message.
'''
result = 'Clean'
if ret['changes']:
result = 'Changed'
if ret['result'] is False:
result = 'Failed'
elif ret['result'] is None:
result = 'Differs'
if tabular is True:
... | def function[_format_terse, parameter[tcolor, comps, ret, colors, tabular]]:
constant[
Terse formatting of a message.
]
variable[result] assign[=] constant[Clean]
if call[name[ret]][constant[changes]] begin[:]
variable[result] assign[=] constant[Changed]
if compar... | keyword[def] identifier[_format_terse] ( identifier[tcolor] , identifier[comps] , identifier[ret] , identifier[colors] , identifier[tabular] ):
literal[string]
identifier[result] = literal[string]
keyword[if] identifier[ret] [ literal[string] ]:
identifier[result] = literal[string]
ke... | def _format_terse(tcolor, comps, ret, colors, tabular):
"""
Terse formatting of a message.
"""
result = 'Clean'
if ret['changes']:
result = 'Changed' # depends on [control=['if'], data=[]]
if ret['result'] is False:
result = 'Failed' # depends on [control=['if'], data=[]]
e... |
def crtGauss2D(varSizeX, varSizeY, varPosX, varPosY, varSd):
"""Create 2D Gaussian kernel.
Parameters
----------
varSizeX : int, positive
Width of the visual field.
varSizeY : int, positive
Height of the visual field..
varPosX : int, positive
X position of centre of 2D G... | def function[crtGauss2D, parameter[varSizeX, varSizeY, varPosX, varPosY, varSd]]:
constant[Create 2D Gaussian kernel.
Parameters
----------
varSizeX : int, positive
Width of the visual field.
varSizeY : int, positive
Height of the visual field..
varPosX : int, positive
... | keyword[def] identifier[crtGauss2D] ( identifier[varSizeX] , identifier[varSizeY] , identifier[varPosX] , identifier[varPosY] , identifier[varSd] ):
literal[string]
identifier[varSizeX] = identifier[int] ( identifier[varSizeX] )
identifier[varSizeY] = identifier[int] ( identifier[varSizeY] )
... | def crtGauss2D(varSizeX, varSizeY, varPosX, varPosY, varSd):
"""Create 2D Gaussian kernel.
Parameters
----------
varSizeX : int, positive
Width of the visual field.
varSizeY : int, positive
Height of the visual field..
varPosX : int, positive
X position of centre of 2D G... |
def full_electronic_structure(self):
"""
Full electronic structure as tuple.
E.g., The electronic structure for Fe is represented as:
[(1, "s", 2), (2, "s", 2), (2, "p", 6), (3, "s", 2), (3, "p", 6),
(3, "d", 6), (4, "s", 2)]
"""
estr = self._data["Electronic stru... | def function[full_electronic_structure, parameter[self]]:
constant[
Full electronic structure as tuple.
E.g., The electronic structure for Fe is represented as:
[(1, "s", 2), (2, "s", 2), (2, "p", 6), (3, "s", 2), (3, "p", 6),
(3, "d", 6), (4, "s", 2)]
]
variable[... | keyword[def] identifier[full_electronic_structure] ( identifier[self] ):
literal[string]
identifier[estr] = identifier[self] . identifier[_data] [ literal[string] ]
keyword[def] identifier[parse_orbital] ( identifier[orbstr] ):
identifier[m] = identifier[re] . identifier[mat... | def full_electronic_structure(self):
"""
Full electronic structure as tuple.
E.g., The electronic structure for Fe is represented as:
[(1, "s", 2), (2, "s", 2), (2, "p", 6), (3, "s", 2), (3, "p", 6),
(3, "d", 6), (4, "s", 2)]
"""
estr = self._data['Electronic structure']
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.