code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def ReadFD(
self,
Channel):
"""
Reads a CAN message from the receive queue of a FD capable PCAN Channel
Remarks:
The return value of this method is a 3-touple, where
the first value is the result (TPCANStatus) of the method.
The order of the valu... | def function[ReadFD, parameter[self, Channel]]:
constant[
Reads a CAN message from the receive queue of a FD capable PCAN Channel
Remarks:
The return value of this method is a 3-touple, where
the first value is the result (TPCANStatus) of the method.
The order of... | keyword[def] identifier[ReadFD] (
identifier[self] ,
identifier[Channel] ):
literal[string]
keyword[try] :
keyword[if] identifier[platform] . identifier[system] ()== literal[string] :
identifier[msg] = identifier[TPCANMsgFDMac] ()
keyword[else] :
... | def ReadFD(self, Channel):
"""
Reads a CAN message from the receive queue of a FD capable PCAN Channel
Remarks:
The return value of this method is a 3-touple, where
the first value is the result (TPCANStatus) of the method.
The order of the values are:
[0]:... |
def _upload_client(self, localfile: str, remotefile: str, overwrite: bool = True, permission: str = '', **kwargs):
"""
This method uploads a local file to the SAS servers file system.
localfile - path to the local file to upload
remotefile - path to remote file to create or overwrite
ove... | def function[_upload_client, parameter[self, localfile, remotefile, overwrite, permission]]:
constant[
This method uploads a local file to the SAS servers file system.
localfile - path to the local file to upload
remotefile - path to remote file to create or overwrite
overwrite - over... | keyword[def] identifier[_upload_client] ( identifier[self] , identifier[localfile] : identifier[str] , identifier[remotefile] : identifier[str] , identifier[overwrite] : identifier[bool] = keyword[True] , identifier[permission] : identifier[str] = literal[string] ,** identifier[kwargs] ):
literal[string]
... | def _upload_client(self, localfile: str, remotefile: str, overwrite: bool=True, permission: str='', **kwargs):
"""
This method uploads a local file to the SAS servers file system.
localfile - path to the local file to upload
remotefile - path to remote file to create or overwrite
overwrite... |
def with_joined(cls, *paths):
"""
Eagerload for simple cases where we need to just
joined load some relations
In strings syntax, you can split relations with dot
due to this SQLAlchemy feature: https://goo.gl/yM2DLX
:type paths: *List[str] | *List[Inst... | def function[with_joined, parameter[cls]]:
constant[
Eagerload for simple cases where we need to just
joined load some relations
In strings syntax, you can split relations with dot
due to this SQLAlchemy feature: https://goo.gl/yM2DLX
:type paths: *List[str] ... | keyword[def] identifier[with_joined] ( identifier[cls] ,* identifier[paths] ):
literal[string]
identifier[options] =[ identifier[joinedload] ( identifier[path] ) keyword[for] identifier[path] keyword[in] identifier[paths] ]
keyword[return] identifier[cls] . identifier[query] . ident... | def with_joined(cls, *paths):
"""
Eagerload for simple cases where we need to just
joined load some relations
In strings syntax, you can split relations with dot
due to this SQLAlchemy feature: https://goo.gl/yM2DLX
:type paths: *List[str] | *List[InstrumentedAtt... |
def update(self, indices):
"""Updates counts based on indices. The algorithm tracks the index change at i and
update global counts for all indices beyond i with local counts tracked so far.
"""
# Initialize various lists for the first time based on length of indices.
if self._pre... | def function[update, parameter[self, indices]]:
constant[Updates counts based on indices. The algorithm tracks the index change at i and
update global counts for all indices beyond i with local counts tracked so far.
]
if compare[name[self]._prev_indices is constant[None]] begin[:]
... | keyword[def] identifier[update] ( identifier[self] , identifier[indices] ):
literal[string]
keyword[if] identifier[self] . identifier[_prev_indices] keyword[is] keyword[None] :
identifier[self] . identifier[_prev_indices] = identifier[indices]
id... | def update(self, indices):
"""Updates counts based on indices. The algorithm tracks the index change at i and
update global counts for all indices beyond i with local counts tracked so far.
"""
# Initialize various lists for the first time based on length of indices.
if self._prev_indices is... |
def to_abivars(self):
"""Returns a dictionary with the abinit variables."""
abivars = dict(
gwcalctyp=self.gwcalctyp,
ecuteps=self.ecuteps,
ecutsigx=self.ecutsigx,
symsigma=self.symsigma,
gw_qprange=self.gw_qprange,
gwpara=self.gwpa... | def function[to_abivars, parameter[self]]:
constant[Returns a dictionary with the abinit variables.]
variable[abivars] assign[=] call[name[dict], parameter[]]
if name[self].use_ppmodel begin[:]
call[name[abivars].update, parameter[call[name[self].ppmodel.to_abivars, parameter[]]]... | keyword[def] identifier[to_abivars] ( identifier[self] ):
literal[string]
identifier[abivars] = identifier[dict] (
identifier[gwcalctyp] = identifier[self] . identifier[gwcalctyp] ,
identifier[ecuteps] = identifier[self] . identifier[ecuteps] ,
identifier[ecutsigx] = iden... | def to_abivars(self):
"""Returns a dictionary with the abinit variables."""
#"ecutwfn" : self.ecutwfn,
#"kptgw" : self.kptgw,
#"nkptgw" : self.nkptgw,
#"bdgw" : self.bdgw,
abivars = dict(gwcalctyp=self.gwcalctyp, ecuteps=self.ecuteps, ecutsigx=self.ecutsigx, symsigma=self.symsigma, gw_... |
def follow_target_encode(self, timestamp, est_capabilities, lat, lon, alt, vel, acc, attitude_q, rates, position_cov, custom_state):
'''
current motion information from a designated system
timestamp : Timestamp in milliseconds since system boot (uint64_t)... | def function[follow_target_encode, parameter[self, timestamp, est_capabilities, lat, lon, alt, vel, acc, attitude_q, rates, position_cov, custom_state]]:
constant[
current motion information from a designated system
timestamp : Timestamp in milliseconds since sys... | keyword[def] identifier[follow_target_encode] ( identifier[self] , identifier[timestamp] , identifier[est_capabilities] , identifier[lat] , identifier[lon] , identifier[alt] , identifier[vel] , identifier[acc] , identifier[attitude_q] , identifier[rates] , identifier[position_cov] , identifier[custom_state] ):
... | def follow_target_encode(self, timestamp, est_capabilities, lat, lon, alt, vel, acc, attitude_q, rates, position_cov, custom_state):
"""
current motion information from a designated system
timestamp : Timestamp in milliseconds since system boot (uint64_t)
... |
def tag(name, tag_name):
"""
Tag the named metric with the given tag.
"""
with LOCK:
# just to check if <name> exists
metric(name)
TAGS.setdefault(tag_name, set()).add(name) | def function[tag, parameter[name, tag_name]]:
constant[
Tag the named metric with the given tag.
]
with name[LOCK] begin[:]
call[name[metric], parameter[name[name]]]
call[call[name[TAGS].setdefault, parameter[name[tag_name], call[name[set], parameter[]]]].add, par... | keyword[def] identifier[tag] ( identifier[name] , identifier[tag_name] ):
literal[string]
keyword[with] identifier[LOCK] :
identifier[metric] ( identifier[name] )
identifier[TAGS] . identifier[setdefault] ( identifier[tag_name] , identifier[set] ()). identifier[add] ( identifier[n... | def tag(name, tag_name):
"""
Tag the named metric with the given tag.
"""
with LOCK:
# just to check if <name> exists
metric(name)
TAGS.setdefault(tag_name, set()).add(name) # depends on [control=['with'], data=[]] |
def set_ip(self, inter_type, inter, ip_addr):
"""
Set IP address of a L3 interface.
Args:
inter_type: The type of interface you want to configure. Ex.
tengigabitethernet, gigabitethernet, fortygigabitethernet.
inter: The ID for the interface you want to c... | def function[set_ip, parameter[self, inter_type, inter, ip_addr]]:
constant[
Set IP address of a L3 interface.
Args:
inter_type: The type of interface you want to configure. Ex.
tengigabitethernet, gigabitethernet, fortygigabitethernet.
inter: The ID for ... | keyword[def] identifier[set_ip] ( identifier[self] , identifier[inter_type] , identifier[inter] , identifier[ip_addr] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[interface] = identifier[ET] . identifier[SubElement] ( identifie... | def set_ip(self, inter_type, inter, ip_addr):
"""
Set IP address of a L3 interface.
Args:
inter_type: The type of interface you want to configure. Ex.
tengigabitethernet, gigabitethernet, fortygigabitethernet.
inter: The ID for the interface you want to confi... |
def _get_menu_width(self, max_width, complete_state):
"""
Return the width of the main column.
"""
return min(max_width, max(self.MIN_WIDTH, max(get_cwidth(c.display)
for c in complete_state.current_completions) + 2)) | def function[_get_menu_width, parameter[self, max_width, complete_state]]:
constant[
Return the width of the main column.
]
return[call[name[min], parameter[name[max_width], call[name[max], parameter[name[self].MIN_WIDTH, binary_operation[call[name[max], parameter[<ast.GeneratorExp object at... | keyword[def] identifier[_get_menu_width] ( identifier[self] , identifier[max_width] , identifier[complete_state] ):
literal[string]
keyword[return] identifier[min] ( identifier[max_width] , identifier[max] ( identifier[self] . identifier[MIN_WIDTH] , identifier[max] ( identifier[get_cwidth] ( iden... | def _get_menu_width(self, max_width, complete_state):
"""
Return the width of the main column.
"""
return min(max_width, max(self.MIN_WIDTH, max((get_cwidth(c.display) for c in complete_state.current_completions)) + 2)) |
def new_body(name=None, pos=None, **kwargs):
"""
Creates a body element with attributes specified by @**kwargs.
Args:
name (str): body name.
pos: 3d position of the body frame.
"""
if name is not None:
kwargs["name"] = name
if pos is not None:
kwargs["pos"] = arr... | def function[new_body, parameter[name, pos]]:
constant[
Creates a body element with attributes specified by @**kwargs.
Args:
name (str): body name.
pos: 3d position of the body frame.
]
if compare[name[name] is_not constant[None]] begin[:]
call[name[kwargs]][... | keyword[def] identifier[new_body] ( identifier[name] = keyword[None] , identifier[pos] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[name] keyword[is] keyword[not] keyword[None] :
identifier[kwargs] [ literal[string] ]= identifier[name]
keyword[if] ide... | def new_body(name=None, pos=None, **kwargs):
"""
Creates a body element with attributes specified by @**kwargs.
Args:
name (str): body name.
pos: 3d position of the body frame.
"""
if name is not None:
kwargs['name'] = name # depends on [control=['if'], data=['name']]
i... |
def getBitmapFromRect(self, x, y, w, h):
""" Capture the specified area of the (virtual) screen. """
min_x, min_y, screen_width, screen_height = self._getVirtualScreenRect()
img = self._getVirtualScreenBitmap() # TODO
# Limit the coordinates to the virtual screen
# Then offset so... | def function[getBitmapFromRect, parameter[self, x, y, w, h]]:
constant[ Capture the specified area of the (virtual) screen. ]
<ast.Tuple object at 0x7da18dc9b790> assign[=] call[name[self]._getVirtualScreenRect, parameter[]]
variable[img] assign[=] call[name[self]._getVirtualScreenBitmap, parame... | keyword[def] identifier[getBitmapFromRect] ( identifier[self] , identifier[x] , identifier[y] , identifier[w] , identifier[h] ):
literal[string]
identifier[min_x] , identifier[min_y] , identifier[screen_width] , identifier[screen_height] = identifier[self] . identifier[_getVirtualScreenRect] ()
... | def getBitmapFromRect(self, x, y, w, h):
""" Capture the specified area of the (virtual) screen. """
(min_x, min_y, screen_width, screen_height) = self._getVirtualScreenRect()
img = self._getVirtualScreenBitmap() # TODO
# Limit the coordinates to the virtual screen
# Then offset so 0,0 is the top l... |
def calculate_size(name, items):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += INT_SIZE_IN_BYTES
for items_item in items:
data_size += calculate_size_data(items_item)
return data_size | def function[calculate_size, parameter[name, items]]:
constant[ Calculates the request payload size]
variable[data_size] assign[=] constant[0]
<ast.AugAssign object at 0x7da204620130>
<ast.AugAssign object at 0x7da204622dd0>
for taget[name[items_item]] in starred[name[items]] begin[:]
... | keyword[def] identifier[calculate_size] ( identifier[name] , identifier[items] ):
literal[string]
identifier[data_size] = literal[int]
identifier[data_size] += identifier[calculate_size_str] ( identifier[name] )
identifier[data_size] += identifier[INT_SIZE_IN_BYTES]
keyword[for] identifie... | def calculate_size(name, items):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += INT_SIZE_IN_BYTES
for items_item in items:
data_size += calculate_size_data(items_item) # depends on [control=['for'], data=['items_item']]
return... |
def contains(haystack, needle):
"""
py3 contains
:param haystack:
:param needle:
:return:
"""
if sys.version_info[0] < 3:
return needle in haystack
else:
return to_bytes(needle) in to_bytes(haystack) | def function[contains, parameter[haystack, needle]]:
constant[
py3 contains
:param haystack:
:param needle:
:return:
]
if compare[call[name[sys].version_info][constant[0]] less[<] constant[3]] begin[:]
return[compare[name[needle] in name[haystack]]] | keyword[def] identifier[contains] ( identifier[haystack] , identifier[needle] ):
literal[string]
keyword[if] identifier[sys] . identifier[version_info] [ literal[int] ]< literal[int] :
keyword[return] identifier[needle] keyword[in] identifier[haystack]
keyword[else] :
keyword[re... | def contains(haystack, needle):
"""
py3 contains
:param haystack:
:param needle:
:return:
"""
if sys.version_info[0] < 3:
return needle in haystack # depends on [control=['if'], data=[]]
else:
return to_bytes(needle) in to_bytes(haystack) |
def create_graph_html(js_template, css_template, html_template=None):
""" Create HTML code block given the graph Javascript and CSS. """
if html_template is None:
html_template = read_lib('html', 'graph')
# Create div ID for the graph and give it to the JS and CSS templates so
# they can refere... | def function[create_graph_html, parameter[js_template, css_template, html_template]]:
constant[ Create HTML code block given the graph Javascript and CSS. ]
if compare[name[html_template] is constant[None]] begin[:]
variable[html_template] assign[=] call[name[read_lib], parameter[constan... | keyword[def] identifier[create_graph_html] ( identifier[js_template] , identifier[css_template] , identifier[html_template] = keyword[None] ):
literal[string]
keyword[if] identifier[html_template] keyword[is] keyword[None] :
identifier[html_template] = identifier[read_lib] ( literal[string] , l... | def create_graph_html(js_template, css_template, html_template=None):
""" Create HTML code block given the graph Javascript and CSS. """
if html_template is None:
html_template = read_lib('html', 'graph') # depends on [control=['if'], data=['html_template']]
# Create div ID for the graph and give i... |
def unregister(self, recipe):
"""
Unregisters a given recipe class.
"""
recipe = self.get_recipe_instance_from_class(recipe)
if recipe.slug in self._registry:
del self._registry[recipe.slug] | def function[unregister, parameter[self, recipe]]:
constant[
Unregisters a given recipe class.
]
variable[recipe] assign[=] call[name[self].get_recipe_instance_from_class, parameter[name[recipe]]]
if compare[name[recipe].slug in name[self]._registry] begin[:]
<ast.Delete ... | keyword[def] identifier[unregister] ( identifier[self] , identifier[recipe] ):
literal[string]
identifier[recipe] = identifier[self] . identifier[get_recipe_instance_from_class] ( identifier[recipe] )
keyword[if] identifier[recipe] . identifier[slug] keyword[in] identifier[self] . ident... | def unregister(self, recipe):
"""
Unregisters a given recipe class.
"""
recipe = self.get_recipe_instance_from_class(recipe)
if recipe.slug in self._registry:
del self._registry[recipe.slug] # depends on [control=['if'], data=[]] |
def get_share_acl(self, share_name, timeout=None):
'''
Gets the permissions for the specified share.
:param str share_name:
Name of existing share.
:param int timeout:
The timeout parameter is expressed in seconds.
:return: A dictionary of access policies... | def function[get_share_acl, parameter[self, share_name, timeout]]:
constant[
Gets the permissions for the specified share.
:param str share_name:
Name of existing share.
:param int timeout:
The timeout parameter is expressed in seconds.
:return: A diction... | keyword[def] identifier[get_share_acl] ( identifier[self] , identifier[share_name] , identifier[timeout] = keyword[None] ):
literal[string]
identifier[_validate_not_none] ( literal[string] , identifier[share_name] )
identifier[request] = identifier[HTTPRequest] ()
identifier[reque... | def get_share_acl(self, share_name, timeout=None):
"""
Gets the permissions for the specified share.
:param str share_name:
Name of existing share.
:param int timeout:
The timeout parameter is expressed in seconds.
:return: A dictionary of access policies ass... |
def set_subnet_name(name):
'''
Set the local subnet name
:param str name: The new local subnet name
.. note::
Spaces are changed to dashes. Other special characters are removed.
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
... | def function[set_subnet_name, parameter[name]]:
constant[
Set the local subnet name
:param str name: The new local subnet name
.. note::
Spaces are changed to dashes. Other special characters are removed.
:return: True if successful, False if not
:rtype: bool
CLI Example:
... | keyword[def] identifier[set_subnet_name] ( identifier[name] ):
literal[string]
identifier[cmd] = literal[string] . identifier[format] ( identifier[name] )
identifier[__utils__] [ literal[string] ]( identifier[cmd] )
keyword[return] identifier[__utils__] [ literal[string] ](
identifier[name... | def set_subnet_name(name):
"""
Set the local subnet name
:param str name: The new local subnet name
.. note::
Spaces are changed to dashes. Other special characters are removed.
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
... |
def distance(self, method='haversine'):
"""Calculate distances between locations in segments.
Args:
method (str): Method used to calculate distance
Returns:
list of list of float: Groups of distance between points in
segments
"""
distance... | def function[distance, parameter[self, method]]:
constant[Calculate distances between locations in segments.
Args:
method (str): Method used to calculate distance
Returns:
list of list of float: Groups of distance between points in
segments
]
... | keyword[def] identifier[distance] ( identifier[self] , identifier[method] = literal[string] ):
literal[string]
identifier[distances] =[]
keyword[for] identifier[segment] keyword[in] identifier[self] :
keyword[if] identifier[len] ( identifier[segment] )< literal[int] :
... | def distance(self, method='haversine'):
"""Calculate distances between locations in segments.
Args:
method (str): Method used to calculate distance
Returns:
list of list of float: Groups of distance between points in
segments
"""
distances = []
... |
def anim(self, duration, offset=0, timestep=1,
label=None, unit=None,
time_fn=param.Dynamic.time_fn):
"""
duration: The temporal duration to animate in the units
defined on the global time function.
offset: The temporal offset from which the animation is
... | def function[anim, parameter[self, duration, offset, timestep, label, unit, time_fn]]:
constant[
duration: The temporal duration to animate in the units
defined on the global time function.
offset: The temporal offset from which the animation is
generated given the supplied patt... | keyword[def] identifier[anim] ( identifier[self] , identifier[duration] , identifier[offset] = literal[int] , identifier[timestep] = literal[int] ,
identifier[label] = keyword[None] , identifier[unit] = keyword[None] ,
identifier[time_fn] = identifier[param] . identifier[Dynamic] . identifier[time_fn] ):
l... | def anim(self, duration, offset=0, timestep=1, label=None, unit=None, time_fn=param.Dynamic.time_fn):
"""
duration: The temporal duration to animate in the units
defined on the global time function.
offset: The temporal offset from which the animation is
generated given the supplied... |
def get_configuration_dict(self, secret_attrs=False):
"""Generic configuration, may be overridden by type-specific version"""
rd = {'name': self.name,
'path': self.path,
'git_dir': self.git_dir,
'assumed_doc_version': self.assumed_doc_version,
'doc... | def function[get_configuration_dict, parameter[self, secret_attrs]]:
constant[Generic configuration, may be overridden by type-specific version]
variable[rd] assign[=] dictionary[[<ast.Constant object at 0x7da20c993b20>, <ast.Constant object at 0x7da20c9927a0>, <ast.Constant object at 0x7da20c992290>, <... | keyword[def] identifier[get_configuration_dict] ( identifier[self] , identifier[secret_attrs] = keyword[False] ):
literal[string]
identifier[rd] ={ literal[string] : identifier[self] . identifier[name] ,
literal[string] : identifier[self] . identifier[path] ,
literal[string] : ide... | def get_configuration_dict(self, secret_attrs=False):
"""Generic configuration, may be overridden by type-specific version"""
rd = {'name': self.name, 'path': self.path, 'git_dir': self.git_dir, 'assumed_doc_version': self.assumed_doc_version, 'doc_dir': self.doc_dir, 'git_ssh': self.git_ssh}
if secret_attr... |
def get_setter(cls, prop_name, # @NoSelf
user_setter=None, setter_takes_name=False,
user_getter=None, getter_takes_name=False):
"""The setter follows the rules of the getter. First search
for property variable, then logical custom getter/setter pair
met... | def function[get_setter, parameter[cls, prop_name, user_setter, setter_takes_name, user_getter, getter_takes_name]]:
constant[The setter follows the rules of the getter. First search
for property variable, then logical custom getter/setter pair
methods]
variable[_inner_setter] assign... | keyword[def] identifier[get_setter] ( identifier[cls] , identifier[prop_name] ,
identifier[user_setter] = keyword[None] , identifier[setter_takes_name] = keyword[False] ,
identifier[user_getter] = keyword[None] , identifier[getter_takes_name] = keyword[False] ):
literal[string]
identifier[_inner... | def get_setter(cls, prop_name, user_setter=None, setter_takes_name=False, user_getter=None, getter_takes_name=False): # @NoSelf
'The setter follows the rules of the getter. First search\n for property variable, then logical custom getter/setter pair\n methods'
_inner_setter = ObservableProper... |
def unique_justseen(iterable, key=None):
"List unique elements, preserving order. Remember only the element just seen."
# unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
# unique_justseen('ABBCcAD', str.lower) --> A B C A D
try:
# PY2 support
from itertools import imap as map
exce... | def function[unique_justseen, parameter[iterable, key]]:
constant[List unique elements, preserving order. Remember only the element just seen.]
<ast.Try object at 0x7da1afea4d30>
return[call[name[map], parameter[name[next], call[name[map], parameter[call[name[operator].itemgetter, parameter[constant[1]]... | keyword[def] identifier[unique_justseen] ( identifier[iterable] , identifier[key] = keyword[None] ):
literal[string]
keyword[try] :
keyword[from] identifier[itertools] keyword[import] identifier[imap] keyword[as] identifier[map]
keyword[except] identifier[ImportError] :
... | def unique_justseen(iterable, key=None):
"""List unique elements, preserving order. Remember only the element just seen."""
# unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
# unique_justseen('ABBCcAD', str.lower) --> A B C A D
try:
# PY2 support
from itertools import imap as map # d... |
def update_fw_db_result(self, tenant_id, os_status=None, dcnm_status=None,
dev_status=None):
"""Update the FW DB Result and commit it in DB.
Calls the service object routine to commit the result of a FW
operation in to DB
"""
serv_obj = self.get_servi... | def function[update_fw_db_result, parameter[self, tenant_id, os_status, dcnm_status, dev_status]]:
constant[Update the FW DB Result and commit it in DB.
Calls the service object routine to commit the result of a FW
operation in to DB
]
variable[serv_obj] assign[=] call[name[self... | keyword[def] identifier[update_fw_db_result] ( identifier[self] , identifier[tenant_id] , identifier[os_status] = keyword[None] , identifier[dcnm_status] = keyword[None] ,
identifier[dev_status] = keyword[None] ):
literal[string]
identifier[serv_obj] = identifier[self] . identifier[get_service_obj... | def update_fw_db_result(self, tenant_id, os_status=None, dcnm_status=None, dev_status=None):
"""Update the FW DB Result and commit it in DB.
Calls the service object routine to commit the result of a FW
operation in to DB
"""
serv_obj = self.get_service_obj(tenant_id)
serv_obj.updat... |
def coalesce_execution_steps(execution_plan):
'''Groups execution steps by solid, in topological order of the solids.'''
solid_order = _coalesce_solid_order(execution_plan)
steps = defaultdict(list)
for solid_name, solid_steps in itertools.groupby(
execution_plan.topological_steps(), lambda x... | def function[coalesce_execution_steps, parameter[execution_plan]]:
constant[Groups execution steps by solid, in topological order of the solids.]
variable[solid_order] assign[=] call[name[_coalesce_solid_order], parameter[name[execution_plan]]]
variable[steps] assign[=] call[name[defaultdict], p... | keyword[def] identifier[coalesce_execution_steps] ( identifier[execution_plan] ):
literal[string]
identifier[solid_order] = identifier[_coalesce_solid_order] ( identifier[execution_plan] )
identifier[steps] = identifier[defaultdict] ( identifier[list] )
keyword[for] identifier[solid_name] , i... | def coalesce_execution_steps(execution_plan):
"""Groups execution steps by solid, in topological order of the solids."""
solid_order = _coalesce_solid_order(execution_plan)
steps = defaultdict(list)
for (solid_name, solid_steps) in itertools.groupby(execution_plan.topological_steps(), lambda x: x.solid_... |
def find_category(self, parent_alias, title):
"""Searches parent category children for the given title (case independent).
:param str parent_alias:
:param str title:
:rtype: Category|None
:return: None if not found; otherwise - found Category
"""
found = None
... | def function[find_category, parameter[self, parent_alias, title]]:
constant[Searches parent category children for the given title (case independent).
:param str parent_alias:
:param str title:
:rtype: Category|None
:return: None if not found; otherwise - found Category
]... | keyword[def] identifier[find_category] ( identifier[self] , identifier[parent_alias] , identifier[title] ):
literal[string]
identifier[found] = keyword[None]
identifier[child_ids] = identifier[self] . identifier[get_child_ids] ( identifier[parent_alias] )
keyword[for] identifier... | def find_category(self, parent_alias, title):
"""Searches parent category children for the given title (case independent).
:param str parent_alias:
:param str title:
:rtype: Category|None
:return: None if not found; otherwise - found Category
"""
found = None
child_i... |
def _expand(self, pos):
"""Splits sublists that are more than double the load level.
Updates the index when the sublist length is less than double the load
level. This requires incrementing the nodes in a traversal from the
leaf node to the root. For an example traversal see self._loc.
... | def function[_expand, parameter[self, pos]]:
constant[Splits sublists that are more than double the load level.
Updates the index when the sublist length is less than double the load
level. This requires incrementing the nodes in a traversal from the
leaf node to the root. For an exampl... | keyword[def] identifier[_expand] ( identifier[self] , identifier[pos] ):
literal[string]
identifier[_lists] = identifier[self] . identifier[_lists]
identifier[_keys] = identifier[self] . identifier[_keys]
identifier[_index] = identifier[self] . identifier[_index]
keyw... | def _expand(self, pos):
"""Splits sublists that are more than double the load level.
Updates the index when the sublist length is less than double the load
level. This requires incrementing the nodes in a traversal from the
leaf node to the root. For an example traversal see self._loc.
... |
def _generate_security_groups(config_key):
"""Read config file and generate security group dict by environment.
Args:
config_key (str): Configuration file key
Returns:
dict: of environments in {'env1': ['group1', 'group2']} format
"""
raw_default_groups = validate_key_values(CONFIG... | def function[_generate_security_groups, parameter[config_key]]:
constant[Read config file and generate security group dict by environment.
Args:
config_key (str): Configuration file key
Returns:
dict: of environments in {'env1': ['group1', 'group2']} format
]
variable[raw_d... | keyword[def] identifier[_generate_security_groups] ( identifier[config_key] ):
literal[string]
identifier[raw_default_groups] = identifier[validate_key_values] ( identifier[CONFIG] , literal[string] , identifier[config_key] , identifier[default] = literal[string] )
identifier[default_groups] = identif... | def _generate_security_groups(config_key):
"""Read config file and generate security group dict by environment.
Args:
config_key (str): Configuration file key
Returns:
dict: of environments in {'env1': ['group1', 'group2']} format
"""
raw_default_groups = validate_key_values(CONFIG... |
def from_bin(bin_array):
"""
Convert binary array back a nonnegative integer. The array length is
the bit width. The first input index holds the MSB and the last holds the LSB.
"""
width = len(bin_array)
bin_wgts = 2**np.arange(width-1,-1,-1)
return int(np.dot(bin_array,bin_wgts)) | def function[from_bin, parameter[bin_array]]:
constant[
Convert binary array back a nonnegative integer. The array length is
the bit width. The first input index holds the MSB and the last holds the LSB.
]
variable[width] assign[=] call[name[len], parameter[name[bin_array]]]
variabl... | keyword[def] identifier[from_bin] ( identifier[bin_array] ):
literal[string]
identifier[width] = identifier[len] ( identifier[bin_array] )
identifier[bin_wgts] = literal[int] ** identifier[np] . identifier[arange] ( identifier[width] - literal[int] ,- literal[int] ,- literal[int] )
keyword[return... | def from_bin(bin_array):
"""
Convert binary array back a nonnegative integer. The array length is
the bit width. The first input index holds the MSB and the last holds the LSB.
"""
width = len(bin_array)
bin_wgts = 2 ** np.arange(width - 1, -1, -1)
return int(np.dot(bin_array, bin_wgts)) |
def _format_lat(self, lat):
''' Format latitude to fit the image name '''
if self.ppd in [4, 8, 16, 32, 64]:
latcenter = '000N'
elif self.ppd in [128]:
if lat < 0:
latcenter = '450S'
else:
latcenter = '450N'
return lat... | def function[_format_lat, parameter[self, lat]]:
constant[ Format latitude to fit the image name ]
if compare[name[self].ppd in list[[<ast.Constant object at 0x7da18fe915a0>, <ast.Constant object at 0x7da18fe922c0>, <ast.Constant object at 0x7da18fe90ac0>, <ast.Constant object at 0x7da18fe91d20>, <ast.C... | keyword[def] identifier[_format_lat] ( identifier[self] , identifier[lat] ):
literal[string]
keyword[if] identifier[self] . identifier[ppd] keyword[in] [ literal[int] , literal[int] , literal[int] , literal[int] , literal[int] ]:
identifier[latcenter] = literal[string]
key... | def _format_lat(self, lat):
""" Format latitude to fit the image name """
if self.ppd in [4, 8, 16, 32, 64]:
latcenter = '000N' # depends on [control=['if'], data=[]]
elif self.ppd in [128]:
if lat < 0:
latcenter = '450S' # depends on [control=['if'], data=[]]
else:
... |
def is_auth(nodes):
'''
Check if nodes are already authorized
nodes
a list of nodes to be checked for authorization to the cluster
CLI Example:
.. code-block:: bash
salt '*' pcs.is_auth nodes='[node1.example.org node2.example.org]'
'''
cmd = ['pcs', 'cluster', 'auth']
... | def function[is_auth, parameter[nodes]]:
constant[
Check if nodes are already authorized
nodes
a list of nodes to be checked for authorization to the cluster
CLI Example:
.. code-block:: bash
salt '*' pcs.is_auth nodes='[node1.example.org node2.example.org]'
]
var... | keyword[def] identifier[is_auth] ( identifier[nodes] ):
literal[string]
identifier[cmd] =[ literal[string] , literal[string] , literal[string] ]
identifier[cmd] += identifier[nodes]
keyword[return] identifier[__salt__] [ literal[string] ]( identifier[cmd] , identifier[stdin] = literal[string] ... | def is_auth(nodes):
"""
Check if nodes are already authorized
nodes
a list of nodes to be checked for authorization to the cluster
CLI Example:
.. code-block:: bash
salt '*' pcs.is_auth nodes='[node1.example.org node2.example.org]'
"""
cmd = ['pcs', 'cluster', 'auth']
... |
def completion():
"""Output completion (to be eval'd).
For bash or zsh, add the following to your .bashrc or .zshrc:
eval "$(doitlive completion)"
For fish, add the following to ~/.config/fish/completions/doitlive.fish:
eval (doitlive completion)
"""
shell = env.get("SHELL", None... | def function[completion, parameter[]]:
constant[Output completion (to be eval'd).
For bash or zsh, add the following to your .bashrc or .zshrc:
eval "$(doitlive completion)"
For fish, add the following to ~/.config/fish/completions/doitlive.fish:
eval (doitlive completion)
]
... | keyword[def] identifier[completion] ():
literal[string]
identifier[shell] = identifier[env] . identifier[get] ( literal[string] , keyword[None] )
keyword[if] identifier[env] . identifier[get] ( literal[string] , keyword[None] ):
identifier[echo] (
identifier[click_completion] . iden... | def completion():
"""Output completion (to be eval'd).
For bash or zsh, add the following to your .bashrc or .zshrc:
eval "$(doitlive completion)"
For fish, add the following to ~/.config/fish/completions/doitlive.fish:
eval (doitlive completion)
"""
shell = env.get('SHELL', None... |
def build_joblist(jobgraph):
"""Returns a list of jobs, from a passed jobgraph."""
jobset = set()
for job in jobgraph:
jobset = populate_jobset(job, jobset, depth=1)
return list(jobset) | def function[build_joblist, parameter[jobgraph]]:
constant[Returns a list of jobs, from a passed jobgraph.]
variable[jobset] assign[=] call[name[set], parameter[]]
for taget[name[job]] in starred[name[jobgraph]] begin[:]
variable[jobset] assign[=] call[name[populate_jobset], para... | keyword[def] identifier[build_joblist] ( identifier[jobgraph] ):
literal[string]
identifier[jobset] = identifier[set] ()
keyword[for] identifier[job] keyword[in] identifier[jobgraph] :
identifier[jobset] = identifier[populate_jobset] ( identifier[job] , identifier[jobset] , identifier[dept... | def build_joblist(jobgraph):
"""Returns a list of jobs, from a passed jobgraph."""
jobset = set()
for job in jobgraph:
jobset = populate_jobset(job, jobset, depth=1) # depends on [control=['for'], data=['job']]
return list(jobset) |
def parse_stream(cls, iterable):
"""
Parse a stream of messages into a stream of L{Task} instances.
:param iterable: An iterable of serialized Eliot message dictionaries.
:return: An iterable of parsed L{Task} instances. Remaining
incomplete L{Task} will be returned when th... | def function[parse_stream, parameter[cls, iterable]]:
constant[
Parse a stream of messages into a stream of L{Task} instances.
:param iterable: An iterable of serialized Eliot message dictionaries.
:return: An iterable of parsed L{Task} instances. Remaining
incomplete L{Tas... | keyword[def] identifier[parse_stream] ( identifier[cls] , identifier[iterable] ):
literal[string]
identifier[parser] = identifier[Parser] ()
keyword[for] identifier[message_dict] keyword[in] identifier[iterable] :
identifier[completed] , identifier[parser] = identifier[pars... | def parse_stream(cls, iterable):
"""
Parse a stream of messages into a stream of L{Task} instances.
:param iterable: An iterable of serialized Eliot message dictionaries.
:return: An iterable of parsed L{Task} instances. Remaining
incomplete L{Task} will be returned when the in... |
def _find_newest_ckpt(ckpt_dir):
"""Returns path to most recently modified checkpoint."""
full_paths = [
os.path.join(ckpt_dir, fname) for fname in os.listdir(ckpt_dir)
if fname.startswith("experiment_state") and fname.endswith(".json")
]
return max(full_paths) | def function[_find_newest_ckpt, parameter[ckpt_dir]]:
constant[Returns path to most recently modified checkpoint.]
variable[full_paths] assign[=] <ast.ListComp object at 0x7da18eb572b0>
return[call[name[max], parameter[name[full_paths]]]] | keyword[def] identifier[_find_newest_ckpt] ( identifier[ckpt_dir] ):
literal[string]
identifier[full_paths] =[
identifier[os] . identifier[path] . identifier[join] ( identifier[ckpt_dir] , identifier[fname] ) keyword[for] identifier[fname] keyword[in] identifier[os] . identifier[listdir] ( identifi... | def _find_newest_ckpt(ckpt_dir):
"""Returns path to most recently modified checkpoint."""
full_paths = [os.path.join(ckpt_dir, fname) for fname in os.listdir(ckpt_dir) if fname.startswith('experiment_state') and fname.endswith('.json')]
return max(full_paths) |
def make_pilothole_cutter(self):
"""
Make a solid to subtract from an interfacing solid to bore a pilot-hole.
"""
# get pilothole ratio
# note: not done in .initialize_parameters() because this would cause
# the thread's profile to be created at initialisation (by def... | def function[make_pilothole_cutter, parameter[self]]:
constant[
Make a solid to subtract from an interfacing solid to bore a pilot-hole.
]
variable[pilothole_radius] assign[=] name[self].pilothole_radius
if compare[name[pilothole_radius] is constant[None]] begin[:]
... | keyword[def] identifier[make_pilothole_cutter] ( identifier[self] ):
literal[string]
identifier[pilothole_radius] = identifier[self] . identifier[pilothole_radius]
keyword[if] identifier[pilothole_radius] keyword[is] keyword[None] :
( identifier[i... | def make_pilothole_cutter(self):
"""
Make a solid to subtract from an interfacing solid to bore a pilot-hole.
"""
# get pilothole ratio
# note: not done in .initialize_parameters() because this would cause
# the thread's profile to be created at initialisation (by default).
pilot... |
def delete_from(self, basic_block):
""" Removes the basic_block ptr from the list for "comes_from"
if it exists. It also sets self.prev to None if it is basic_block.
"""
if basic_block is None:
return
if self.lock:
return
self.lock = True
... | def function[delete_from, parameter[self, basic_block]]:
constant[ Removes the basic_block ptr from the list for "comes_from"
if it exists. It also sets self.prev to None if it is basic_block.
]
if compare[name[basic_block] is constant[None]] begin[:]
return[None]
if name... | keyword[def] identifier[delete_from] ( identifier[self] , identifier[basic_block] ):
literal[string]
keyword[if] identifier[basic_block] keyword[is] keyword[None] :
keyword[return]
keyword[if] identifier[self] . identifier[lock] :
keyword[return]
... | def delete_from(self, basic_block):
""" Removes the basic_block ptr from the list for "comes_from"
if it exists. It also sets self.prev to None if it is basic_block.
"""
if basic_block is None:
return # depends on [control=['if'], data=[]]
if self.lock:
return # depends on ... |
def add_logger(self, cb, level='NORMAL', filters='ALL'):
'''Add a callback to receive log events from this component.
@param cb The callback function to receive log events. It must have the
signature cb(name, time, source, level, message), where name is the
name of the component... | def function[add_logger, parameter[self, cb, level, filters]]:
constant[Add a callback to receive log events from this component.
@param cb The callback function to receive log events. It must have the
signature cb(name, time, source, level, message), where name is the
name of t... | keyword[def] identifier[add_logger] ( identifier[self] , identifier[cb] , identifier[level] = literal[string] , identifier[filters] = literal[string] ):
literal[string]
keyword[with] identifier[self] . identifier[_mutex] :
identifier[obs] = identifier[sdo] . identifier[RTCLogger] ( id... | def add_logger(self, cb, level='NORMAL', filters='ALL'):
"""Add a callback to receive log events from this component.
@param cb The callback function to receive log events. It must have the
signature cb(name, time, source, level, message), where name is the
name of the component the... |
def get_by_id_or_404(self, id, **kwargs):
"""Gets by a instance instance r raises a 404 is one isn't found."""
obj = self.get_by_id(id=id, **kwargs)
if obj:
return obj
raise Http404 | def function[get_by_id_or_404, parameter[self, id]]:
constant[Gets by a instance instance r raises a 404 is one isn't found.]
variable[obj] assign[=] call[name[self].get_by_id, parameter[]]
if name[obj] begin[:]
return[name[obj]]
<ast.Raise object at 0x7da18bccafe0> | keyword[def] identifier[get_by_id_or_404] ( identifier[self] , identifier[id] ,** identifier[kwargs] ):
literal[string]
identifier[obj] = identifier[self] . identifier[get_by_id] ( identifier[id] = identifier[id] ,** identifier[kwargs] )
keyword[if] identifier[obj] :
keyword... | def get_by_id_or_404(self, id, **kwargs):
"""Gets by a instance instance r raises a 404 is one isn't found."""
obj = self.get_by_id(id=id, **kwargs)
if obj:
return obj # depends on [control=['if'], data=[]]
raise Http404 |
def _format_exception_message(e):
"""
Formats the specified exception.
"""
# Prevent duplication of "AppError" in places that print "AppError"
# and then this formatted string
if isinstance(e, dxpy.AppError):
return _safe_unicode(e)
if USING_PYTHON2:
return unicode(e.__class_... | def function[_format_exception_message, parameter[e]]:
constant[
Formats the specified exception.
]
if call[name[isinstance], parameter[name[e], name[dxpy].AppError]] begin[:]
return[call[name[_safe_unicode], parameter[name[e]]]]
if name[USING_PYTHON2] begin[:]
return[bin... | keyword[def] identifier[_format_exception_message] ( identifier[e] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[e] , identifier[dxpy] . identifier[AppError] ):
keyword[return] identifier[_safe_unicode] ( identifier[e] )
keyword[if] identifier[USING_PYTHON2] ... | def _format_exception_message(e):
"""
Formats the specified exception.
"""
# Prevent duplication of "AppError" in places that print "AppError"
# and then this formatted string
if isinstance(e, dxpy.AppError):
return _safe_unicode(e) # depends on [control=['if'], data=[]]
if USING_PY... |
def _extract_alphabet(self, grammar):
"""
Extract an alphabet from the given grammar.
"""
alphabet = set([])
for terminal in grammar.Terminals:
alphabet |= set([x for x in terminal])
self.alphabet = list(alphabet) | def function[_extract_alphabet, parameter[self, grammar]]:
constant[
Extract an alphabet from the given grammar.
]
variable[alphabet] assign[=] call[name[set], parameter[list[[]]]]
for taget[name[terminal]] in starred[name[grammar].Terminals] begin[:]
<ast.AugAssign objec... | keyword[def] identifier[_extract_alphabet] ( identifier[self] , identifier[grammar] ):
literal[string]
identifier[alphabet] = identifier[set] ([])
keyword[for] identifier[terminal] keyword[in] identifier[grammar] . identifier[Terminals] :
identifier[alphabet] |= identifier[... | def _extract_alphabet(self, grammar):
"""
Extract an alphabet from the given grammar.
"""
alphabet = set([])
for terminal in grammar.Terminals:
alphabet |= set([x for x in terminal]) # depends on [control=['for'], data=['terminal']]
self.alphabet = list(alphabet) |
def _idToStr(self, x):
"""
Convert VCD id in int to string
"""
if x < 0:
sign = -1
elif x == 0:
return self._idChars[0]
else:
sign = 1
x *= sign
digits = []
while x:
digits.append(self._idChars[x % se... | def function[_idToStr, parameter[self, x]]:
constant[
Convert VCD id in int to string
]
if compare[name[x] less[<] constant[0]] begin[:]
variable[sign] assign[=] <ast.UnaryOp object at 0x7da2047e9120>
<ast.AugAssign object at 0x7da2047eada0>
variable[digits] a... | keyword[def] identifier[_idToStr] ( identifier[self] , identifier[x] ):
literal[string]
keyword[if] identifier[x] < literal[int] :
identifier[sign] =- literal[int]
keyword[elif] identifier[x] == literal[int] :
keyword[return] identifier[self] . identifier[_idC... | def _idToStr(self, x):
"""
Convert VCD id in int to string
"""
if x < 0:
sign = -1 # depends on [control=['if'], data=[]]
elif x == 0:
return self._idChars[0] # depends on [control=['if'], data=[]]
else:
sign = 1
x *= sign
digits = []
while x:
... |
def update_token_tempfile(token):
"""
Example of function for token update
"""
with open(tmp, 'w') as f:
f.write(json.dumps(token, indent=4)) | def function[update_token_tempfile, parameter[token]]:
constant[
Example of function for token update
]
with call[name[open], parameter[name[tmp], constant[w]]] begin[:]
call[name[f].write, parameter[call[name[json].dumps, parameter[name[token]]]]] | keyword[def] identifier[update_token_tempfile] ( identifier[token] ):
literal[string]
keyword[with] identifier[open] ( identifier[tmp] , literal[string] ) keyword[as] identifier[f] :
identifier[f] . identifier[write] ( identifier[json] . identifier[dumps] ( identifier[token] , identifier[indent]... | def update_token_tempfile(token):
"""
Example of function for token update
"""
with open(tmp, 'w') as f:
f.write(json.dumps(token, indent=4)) # depends on [control=['with'], data=['f']] |
def tacacs_server_host_protocol(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
tacacs_server = ET.SubElement(config, "tacacs-server", xmlns="urn:brocade.com:mgmt:brocade-aaa")
host = ET.SubElement(tacacs_server, "host")
hostname_key = ET.SubElem... | def function[tacacs_server_host_protocol, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[tacacs_server] assign[=] call[name[ET].SubElement, parameter[name[config], constant[tacacs-server]]]
... | keyword[def] identifier[tacacs_server_host_protocol] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[tacacs_server] = identifier[ET] . identifier[SubElement] ( identifier[config] , literal... | def tacacs_server_host_protocol(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
tacacs_server = ET.SubElement(config, 'tacacs-server', xmlns='urn:brocade.com:mgmt:brocade-aaa')
host = ET.SubElement(tacacs_server, 'host')
hostname_key = ET.SubElement(host, 'hostname'... |
def match_reg(self, reg):
"""match the given regular expression object to the current text
position.
if a match occurs, update the current text and line position.
"""
mp = self.match_position
match = reg.match(self.text, self.match_position)
if match:
... | def function[match_reg, parameter[self, reg]]:
constant[match the given regular expression object to the current text
position.
if a match occurs, update the current text and line position.
]
variable[mp] assign[=] name[self].match_position
variable[match] assign[=] cal... | keyword[def] identifier[match_reg] ( identifier[self] , identifier[reg] ):
literal[string]
identifier[mp] = identifier[self] . identifier[match_position]
identifier[match] = identifier[reg] . identifier[match] ( identifier[self] . identifier[text] , identifier[self] . identifier[match_p... | def match_reg(self, reg):
"""match the given regular expression object to the current text
position.
if a match occurs, update the current text and line position.
"""
mp = self.match_position
match = reg.match(self.text, self.match_position)
if match:
(start, end) = mat... |
def populate_classes(self, metamodel):
'''
Populate a *metamodel* with classes previously encountered from input.
'''
for stmt in self.statements:
if isinstance(stmt, CreateClassStmt):
metamodel.define_class(stmt.kind, stmt.attributes) | def function[populate_classes, parameter[self, metamodel]]:
constant[
Populate a *metamodel* with classes previously encountered from input.
]
for taget[name[stmt]] in starred[name[self].statements] begin[:]
if call[name[isinstance], parameter[name[stmt], name[CreateClass... | keyword[def] identifier[populate_classes] ( identifier[self] , identifier[metamodel] ):
literal[string]
keyword[for] identifier[stmt] keyword[in] identifier[self] . identifier[statements] :
keyword[if] identifier[isinstance] ( identifier[stmt] , identifier[CreateClassStmt] ):
... | def populate_classes(self, metamodel):
"""
Populate a *metamodel* with classes previously encountered from input.
"""
for stmt in self.statements:
if isinstance(stmt, CreateClassStmt):
metamodel.define_class(stmt.kind, stmt.attributes) # depends on [control=['if'], data=[]] ... |
def update(self, **attrs):
""" Method for `Update Data Stream <https://m2x.att.com/developer/documentation/v2/device#Create-Update-Data-Stream>`_ endpoint.
:param attrs: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The Stream bei... | def function[update, parameter[self]]:
constant[ Method for `Update Data Stream <https://m2x.att.com/developer/documentation/v2/device#Create-Update-Data-Stream>`_ endpoint.
:param attrs: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:retu... | keyword[def] identifier[update] ( identifier[self] ,** identifier[attrs] ):
literal[string]
identifier[self] . identifier[data] . identifier[update] ( identifier[self] . identifier[item_update] ( identifier[self] . identifier[api] , identifier[self] . identifier[device] , identifier[self] . identif... | def update(self, **attrs):
""" Method for `Update Data Stream <https://m2x.att.com/developer/documentation/v2/device#Create-Update-Data-Stream>`_ endpoint.
:param attrs: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The Stream being u... |
def _extract_one_pair(body):
"""
Extract one language-text pair from a :class:`~.LanguageMap`.
This is used for tracking.
"""
if not body:
return None, None
try:
return None, body[None]
except KeyError:
return min(body.items(), key=lambda x: x[0]) | def function[_extract_one_pair, parameter[body]]:
constant[
Extract one language-text pair from a :class:`~.LanguageMap`.
This is used for tracking.
]
if <ast.UnaryOp object at 0x7da2047eb010> begin[:]
return[tuple[[<ast.Constant object at 0x7da2047eb1c0>, <ast.Constant object at 0x... | keyword[def] identifier[_extract_one_pair] ( identifier[body] ):
literal[string]
keyword[if] keyword[not] identifier[body] :
keyword[return] keyword[None] , keyword[None]
keyword[try] :
keyword[return] keyword[None] , identifier[body] [ keyword[None] ]
keyword[except] ide... | def _extract_one_pair(body):
"""
Extract one language-text pair from a :class:`~.LanguageMap`.
This is used for tracking.
"""
if not body:
return (None, None) # depends on [control=['if'], data=[]]
try:
return (None, body[None]) # depends on [control=['try'], data=[]]
exce... |
def add_pass(self, name, opt_pass, before=None, after=None):
"""Add an optimization pass to the optimizer.
Optimization passes have a name that allows them
to be enabled or disabled by name. By default all
optimization passed are enabled and unordered. You can
explicitly speci... | def function[add_pass, parameter[self, name, opt_pass, before, after]]:
constant[Add an optimization pass to the optimizer.
Optimization passes have a name that allows them
to be enabled or disabled by name. By default all
optimization passed are enabled and unordered. You can
... | keyword[def] identifier[add_pass] ( identifier[self] , identifier[name] , identifier[opt_pass] , identifier[before] = keyword[None] , identifier[after] = keyword[None] ):
literal[string]
keyword[if] identifier[before] keyword[is] keyword[None] :
identifier[before] =[]
keyw... | def add_pass(self, name, opt_pass, before=None, after=None):
"""Add an optimization pass to the optimizer.
Optimization passes have a name that allows them
to be enabled or disabled by name. By default all
optimization passed are enabled and unordered. You can
explicitly specify p... |
def _exclusive_lock(path):
"""A simple wrapper for fcntl exclusive lock."""
_create_file_dirs(path)
fd = os.open(path, os.O_WRONLY | os.O_CREAT, 0o600)
try:
retries_left = _LOCK_RETRIES
success = False
while retries_left > 0:
# try to acquire the lock in a loop
... | def function[_exclusive_lock, parameter[path]]:
constant[A simple wrapper for fcntl exclusive lock.]
call[name[_create_file_dirs], parameter[name[path]]]
variable[fd] assign[=] call[name[os].open, parameter[name[path], binary_operation[name[os].O_WRONLY <ast.BitOr object at 0x7da2590d6aa0> name[... | keyword[def] identifier[_exclusive_lock] ( identifier[path] ):
literal[string]
identifier[_create_file_dirs] ( identifier[path] )
identifier[fd] = identifier[os] . identifier[open] ( identifier[path] , identifier[os] . identifier[O_WRONLY] | identifier[os] . identifier[O_CREAT] , literal[int] )
... | def _exclusive_lock(path):
"""A simple wrapper for fcntl exclusive lock."""
_create_file_dirs(path)
fd = os.open(path, os.O_WRONLY | os.O_CREAT, 384)
try:
retries_left = _LOCK_RETRIES
success = False
while retries_left > 0:
# try to acquire the lock in a loop
... |
def dt_is_leap_year(x):
"""Check whether a year is a leap year.
:returns: an expression which evaluates to True if a year is a leap year, and to False otherwise.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:3... | def function[dt_is_leap_year, parameter[x]]:
constant[Check whether a year is a leap year.
:returns: an expression which evaluates to True if a year is a leap year, and to False otherwise.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02... | keyword[def] identifier[dt_is_leap_year] ( identifier[x] ):
literal[string]
keyword[import] identifier[pandas] keyword[as] identifier[pd]
keyword[return] identifier[pd] . identifier[Series] ( identifier[x] ). identifier[dt] . identifier[is_leap_year] . identifier[values] | def dt_is_leap_year(x):
"""Check whether a year is a leap year.
:returns: an expression which evaluates to True if a year is a leap year, and to False otherwise.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:3... |
def runGetReference(self, id_):
"""
Runs a getReference request for the specified ID.
"""
compoundId = datamodel.ReferenceCompoundId.parse(id_)
referenceSet = self.getDataRepository().getReferenceSet(
compoundId.reference_set_id)
reference = referenceSet.getRe... | def function[runGetReference, parameter[self, id_]]:
constant[
Runs a getReference request for the specified ID.
]
variable[compoundId] assign[=] call[name[datamodel].ReferenceCompoundId.parse, parameter[name[id_]]]
variable[referenceSet] assign[=] call[call[name[self].getDataRep... | keyword[def] identifier[runGetReference] ( identifier[self] , identifier[id_] ):
literal[string]
identifier[compoundId] = identifier[datamodel] . identifier[ReferenceCompoundId] . identifier[parse] ( identifier[id_] )
identifier[referenceSet] = identifier[self] . identifier[getDataReposito... | def runGetReference(self, id_):
"""
Runs a getReference request for the specified ID.
"""
compoundId = datamodel.ReferenceCompoundId.parse(id_)
referenceSet = self.getDataRepository().getReferenceSet(compoundId.reference_set_id)
reference = referenceSet.getReference(id_)
return self.... |
def word(ctx, text, number, by_spaces=False):
"""
Extracts the nth word from the given text string
"""
return word_slice(ctx, text, number, conversions.to_integer(number, ctx) + 1, by_spaces) | def function[word, parameter[ctx, text, number, by_spaces]]:
constant[
Extracts the nth word from the given text string
]
return[call[name[word_slice], parameter[name[ctx], name[text], name[number], binary_operation[call[name[conversions].to_integer, parameter[name[number], name[ctx]]] + constant[1]... | keyword[def] identifier[word] ( identifier[ctx] , identifier[text] , identifier[number] , identifier[by_spaces] = keyword[False] ):
literal[string]
keyword[return] identifier[word_slice] ( identifier[ctx] , identifier[text] , identifier[number] , identifier[conversions] . identifier[to_integer] ( identifi... | def word(ctx, text, number, by_spaces=False):
"""
Extracts the nth word from the given text string
"""
return word_slice(ctx, text, number, conversions.to_integer(number, ctx) + 1, by_spaces) |
def _reversebytes(self, start, end):
"""Reverse bytes in-place."""
# Make the start occur on a byte boundary
# TODO: We could be cleverer here to avoid changing the offset.
newoffset = 8 - (start % 8)
if newoffset == 8:
newoffset = 0
self._datastore = offsetco... | def function[_reversebytes, parameter[self, start, end]]:
constant[Reverse bytes in-place.]
variable[newoffset] assign[=] binary_operation[constant[8] - binary_operation[name[start] <ast.Mod object at 0x7da2590d6920> constant[8]]]
if compare[name[newoffset] equal[==] constant[8]] begin[:]
... | keyword[def] identifier[_reversebytes] ( identifier[self] , identifier[start] , identifier[end] ):
literal[string]
identifier[newoffset] = literal[int] -( identifier[start] % literal[int] )
keyword[if] identifier[newoffset] == literal[int] :
identifier[newof... | def _reversebytes(self, start, end):
"""Reverse bytes in-place."""
# Make the start occur on a byte boundary
# TODO: We could be cleverer here to avoid changing the offset.
newoffset = 8 - start % 8
if newoffset == 8:
newoffset = 0 # depends on [control=['if'], data=['newoffset']]
self.... |
def _json_to_supported(response_body):
"""
Returns a list of Supported objects
"""
data = json.loads(response_body)
supported = []
for supported_data in data.get("supportedList", []):
supported.append(Supported().from_json(
supported_data))
return supported | def function[_json_to_supported, parameter[response_body]]:
constant[
Returns a list of Supported objects
]
variable[data] assign[=] call[name[json].loads, parameter[name[response_body]]]
variable[supported] assign[=] list[[]]
for taget[name[supported_data]] in starred[call[name[... | keyword[def] identifier[_json_to_supported] ( identifier[response_body] ):
literal[string]
identifier[data] = identifier[json] . identifier[loads] ( identifier[response_body] )
identifier[supported] =[]
keyword[for] identifier[supported_data] keyword[in] identifier[data] . identifier[get] ( li... | def _json_to_supported(response_body):
"""
Returns a list of Supported objects
"""
data = json.loads(response_body)
supported = []
for supported_data in data.get('supportedList', []):
supported.append(Supported().from_json(supported_data)) # depends on [control=['for'], data=['supported... |
def stat_smt_query(func: Callable):
"""Measures statistics for annotated smt query check function"""
stat_store = SolverStatistics()
def function_wrapper(*args, **kwargs):
if not stat_store.enabled:
return func(*args, **kwargs)
stat_store.query_count += 1
begin = time()... | def function[stat_smt_query, parameter[func]]:
constant[Measures statistics for annotated smt query check function]
variable[stat_store] assign[=] call[name[SolverStatistics], parameter[]]
def function[function_wrapper, parameter[]]:
if <ast.UnaryOp object at 0x7da1b1d351e0> begi... | keyword[def] identifier[stat_smt_query] ( identifier[func] : identifier[Callable] ):
literal[string]
identifier[stat_store] = identifier[SolverStatistics] ()
keyword[def] identifier[function_wrapper] (* identifier[args] ,** identifier[kwargs] ):
keyword[if] keyword[not] identifier[stat_st... | def stat_smt_query(func: Callable):
"""Measures statistics for annotated smt query check function"""
stat_store = SolverStatistics()
def function_wrapper(*args, **kwargs):
if not stat_store.enabled:
return func(*args, **kwargs) # depends on [control=['if'], data=[]]
stat_store.... |
def write_graphml(docgraph, output_file):
"""
takes a document graph, converts it into GraphML format and writes it to
a file.
"""
dg_copy = deepcopy(docgraph)
layerset2str(dg_copy)
attriblist2str(dg_copy)
remove_root_metadata(dg_copy)
nx_write_graphml(dg_copy, output_file) | def function[write_graphml, parameter[docgraph, output_file]]:
constant[
takes a document graph, converts it into GraphML format and writes it to
a file.
]
variable[dg_copy] assign[=] call[name[deepcopy], parameter[name[docgraph]]]
call[name[layerset2str], parameter[name[dg_copy]]]
... | keyword[def] identifier[write_graphml] ( identifier[docgraph] , identifier[output_file] ):
literal[string]
identifier[dg_copy] = identifier[deepcopy] ( identifier[docgraph] )
identifier[layerset2str] ( identifier[dg_copy] )
identifier[attriblist2str] ( identifier[dg_copy] )
identifier[remove... | def write_graphml(docgraph, output_file):
"""
takes a document graph, converts it into GraphML format and writes it to
a file.
"""
dg_copy = deepcopy(docgraph)
layerset2str(dg_copy)
attriblist2str(dg_copy)
remove_root_metadata(dg_copy)
nx_write_graphml(dg_copy, output_file) |
def to_abook(card, section, book, bookfile=None):
"""Converts a vCard to Abook"""
book[section] = {}
book[section]['name'] = card.fn.value
if hasattr(card, 'email'):
book[section]['email'] = ','.join([e.value for e in card.email_list])
if hasattr(card, 'adr'):
... | def function[to_abook, parameter[card, section, book, bookfile]]:
constant[Converts a vCard to Abook]
call[name[book]][name[section]] assign[=] dictionary[[], []]
call[call[name[book]][name[section]]][constant[name]] assign[=] name[card].fn.value
if call[name[hasattr], parameter[name[car... | keyword[def] identifier[to_abook] ( identifier[card] , identifier[section] , identifier[book] , identifier[bookfile] = keyword[None] ):
literal[string]
identifier[book] [ identifier[section] ]={}
identifier[book] [ identifier[section] ][ literal[string] ]= identifier[card] . identifier[fn]... | def to_abook(card, section, book, bookfile=None):
"""Converts a vCard to Abook"""
book[section] = {}
book[section]['name'] = card.fn.value
if hasattr(card, 'email'):
book[section]['email'] = ','.join([e.value for e in card.email_list]) # depends on [control=['if'], data=[]]
if hasattr(card,... |
def loadSignalFromWav(inputSignalFile, calibrationRealWorldValue=None, calibrationSignalFile=None, start=None,
end=None) -> Signal:
""" reads a wav file into a Signal and scales the input so that the sample are expressed in real world values
(as defined by the calibration signal).
:par... | def function[loadSignalFromWav, parameter[inputSignalFile, calibrationRealWorldValue, calibrationSignalFile, start, end]]:
constant[ reads a wav file into a Signal and scales the input so that the sample are expressed in real world values
(as defined by the calibration signal).
:param inputSignalFile: a... | keyword[def] identifier[loadSignalFromWav] ( identifier[inputSignalFile] , identifier[calibrationRealWorldValue] = keyword[None] , identifier[calibrationSignalFile] = keyword[None] , identifier[start] = keyword[None] ,
identifier[end] = keyword[None] )-> identifier[Signal] :
literal[string]
identifier[inp... | def loadSignalFromWav(inputSignalFile, calibrationRealWorldValue=None, calibrationSignalFile=None, start=None, end=None) -> Signal:
""" reads a wav file into a Signal and scales the input so that the sample are expressed in real world values
(as defined by the calibration signal).
:param inputSignalFile: a ... |
def parse_stream(response):
"""
take stream from docker-py lib and display it to the user.
this also builds a stream list and returns it.
"""
stream_data = []
stream = stdout
for data in response:
if data:
try:
data = data.decode('utf-8')
exc... | def function[parse_stream, parameter[response]]:
constant[
take stream from docker-py lib and display it to the user.
this also builds a stream list and returns it.
]
variable[stream_data] assign[=] list[[]]
variable[stream] assign[=] name[stdout]
for taget[name[data]] in st... | keyword[def] identifier[parse_stream] ( identifier[response] ):
literal[string]
identifier[stream_data] =[]
identifier[stream] = identifier[stdout]
keyword[for] identifier[data] keyword[in] identifier[response] :
keyword[if] identifier[data] :
keyword[try] :
... | def parse_stream(response):
"""
take stream from docker-py lib and display it to the user.
this also builds a stream list and returns it.
"""
stream_data = []
stream = stdout
for data in response:
if data:
try:
data = data.decode('utf-8') # depends on [c... |
def build_filename(self, binary):
"""Return the proposed filename with extension for the binary."""
try:
# Get exact timestamp of the build to build the local file name
folder = self.builds[self.build_index]
timestamp = re.search(r'([\d\-]+)-\D.*', folder).group(1)
... | def function[build_filename, parameter[self, binary]]:
constant[Return the proposed filename with extension for the binary.]
<ast.Try object at 0x7da1b12538b0>
return[binary_operation[constant[%(TIMESTAMP)s-%(BRANCH)s-%(NAME)s] <ast.Mod object at 0x7da2590d6920> dictionary[[<ast.Constant object at 0x7da... | keyword[def] identifier[build_filename] ( identifier[self] , identifier[binary] ):
literal[string]
keyword[try] :
identifier[folder] = identifier[self] . identifier[builds] [ identifier[self] . identifier[build_index] ]
identifier[timestamp] = identifier[re] . ide... | def build_filename(self, binary):
"""Return the proposed filename with extension for the binary."""
try:
# Get exact timestamp of the build to build the local file name
folder = self.builds[self.build_index]
timestamp = re.search('([\\d\\-]+)-\\D.*', folder).group(1) # depends on [contr... |
def _parseDOM(istack):
"""
Recursively go through element array and create DOM.
Args:
istack (list): List of :class:`.HTMLElement` objects.
Returns:
list: DOM tree as list.
"""
ostack = []
end_tag_index = 0
def neither_nonpair_or_end_or_comment(el):
return not ... | def function[_parseDOM, parameter[istack]]:
constant[
Recursively go through element array and create DOM.
Args:
istack (list): List of :class:`.HTMLElement` objects.
Returns:
list: DOM tree as list.
]
variable[ostack] assign[=] list[[]]
variable[end_tag_index] ... | keyword[def] identifier[_parseDOM] ( identifier[istack] ):
literal[string]
identifier[ostack] =[]
identifier[end_tag_index] = literal[int]
keyword[def] identifier[neither_nonpair_or_end_or_comment] ( identifier[el] ):
keyword[return] keyword[not] ( identifier[el] . identifier[isNonPa... | def _parseDOM(istack):
"""
Recursively go through element array and create DOM.
Args:
istack (list): List of :class:`.HTMLElement` objects.
Returns:
list: DOM tree as list.
"""
ostack = []
end_tag_index = 0
def neither_nonpair_or_end_or_comment(el):
return not ... |
def _get_struct_cxformwithalpha(self):
"""Get the values for the CXFORMWITHALPHA record."""
obj = _make_object("CXformWithAlpha")
bc = BitConsumer(self._src)
obj.HasAddTerms = bc.u_get(1)
obj.HasMultTerms = bc.u_get(1)
obj.NBits = nbits = bc.u_get(4)
if obj.HasM... | def function[_get_struct_cxformwithalpha, parameter[self]]:
constant[Get the values for the CXFORMWITHALPHA record.]
variable[obj] assign[=] call[name[_make_object], parameter[constant[CXformWithAlpha]]]
variable[bc] assign[=] call[name[BitConsumer], parameter[name[self]._src]]
name[obj]... | keyword[def] identifier[_get_struct_cxformwithalpha] ( identifier[self] ):
literal[string]
identifier[obj] = identifier[_make_object] ( literal[string] )
identifier[bc] = identifier[BitConsumer] ( identifier[self] . identifier[_src] )
identifier[obj] . identifier[HasAddTerms] = i... | def _get_struct_cxformwithalpha(self):
"""Get the values for the CXFORMWITHALPHA record."""
obj = _make_object('CXformWithAlpha')
bc = BitConsumer(self._src)
obj.HasAddTerms = bc.u_get(1)
obj.HasMultTerms = bc.u_get(1)
obj.NBits = nbits = bc.u_get(4)
if obj.HasMultTerms:
obj.RedMultT... |
def log_message(logger, message=""):
"""
Decorator to log a message before executing a function
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
_log_message(logger, func.__name__, message)
result = func(*args, **kwargs)
return resul... | def function[log_message, parameter[logger, message]]:
constant[
Decorator to log a message before executing a function
]
def function[decorator, parameter[func]]:
def function[wrapper, parameter[]]:
call[name[_log_message], parameter[name[logger], name[fu... | keyword[def] identifier[log_message] ( identifier[logger] , identifier[message] = literal[string] ):
literal[string]
keyword[def] identifier[decorator] ( identifier[func] ):
@ identifier[wraps] ( identifier[func] )
keyword[def] identifier[wrapper] (* identifier[args] ,** identifier[kwarg... | def log_message(logger, message=''):
"""
Decorator to log a message before executing a function
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
_log_message(logger, func.__name__, message)
result = func(*args, **kwargs)
return res... |
def get_remote_connection_headers(cls, parsed_url, keep_alive=False):
"""
Get headers for remote request.
:Args:
- parsed_url - The parsed url
- keep_alive (Boolean) - Is this a keep-alive connection (default: False)
"""
system = platform.system().lower()
... | def function[get_remote_connection_headers, parameter[cls, parsed_url, keep_alive]]:
constant[
Get headers for remote request.
:Args:
- parsed_url - The parsed url
- keep_alive (Boolean) - Is this a keep-alive connection (default: False)
]
variable[system] assi... | keyword[def] identifier[get_remote_connection_headers] ( identifier[cls] , identifier[parsed_url] , identifier[keep_alive] = keyword[False] ):
literal[string]
identifier[system] = identifier[platform] . identifier[system] (). identifier[lower] ()
keyword[if] identifier[system] == literal... | def get_remote_connection_headers(cls, parsed_url, keep_alive=False):
"""
Get headers for remote request.
:Args:
- parsed_url - The parsed url
- keep_alive (Boolean) - Is this a keep-alive connection (default: False)
"""
system = platform.system().lower()
if system... |
def drive_rotational_speed_rpm(self):
"""Gets the set of rotational speed of the HDD drives"""
drv_rot_speed_rpm = set()
for member in self.get_members():
if member.rotational_speed_rpm is not None:
drv_rot_speed_rpm.add(member.rotational_speed_rpm)
return drv... | def function[drive_rotational_speed_rpm, parameter[self]]:
constant[Gets the set of rotational speed of the HDD drives]
variable[drv_rot_speed_rpm] assign[=] call[name[set], parameter[]]
for taget[name[member]] in starred[call[name[self].get_members, parameter[]]] begin[:]
if com... | keyword[def] identifier[drive_rotational_speed_rpm] ( identifier[self] ):
literal[string]
identifier[drv_rot_speed_rpm] = identifier[set] ()
keyword[for] identifier[member] keyword[in] identifier[self] . identifier[get_members] ():
keyword[if] identifier[member] . identifi... | def drive_rotational_speed_rpm(self):
"""Gets the set of rotational speed of the HDD drives"""
drv_rot_speed_rpm = set()
for member in self.get_members():
if member.rotational_speed_rpm is not None:
drv_rot_speed_rpm.add(member.rotational_speed_rpm) # depends on [control=['if'], data=[]... |
def _add_onchain_locksroot_to_channel_settled_state_changes(
raiden: RaidenService,
storage: SQLiteStorage,
) -> None:
""" Adds `our_onchain_locksroot` and `partner_onchain_locksroot` to
ContractReceiveChannelSettled. """
batch_size = 50
batch_query = storage.batch_query_state_changes(
... | def function[_add_onchain_locksroot_to_channel_settled_state_changes, parameter[raiden, storage]]:
constant[ Adds `our_onchain_locksroot` and `partner_onchain_locksroot` to
ContractReceiveChannelSettled. ]
variable[batch_size] assign[=] constant[50]
variable[batch_query] assign[=] call[name[... | keyword[def] identifier[_add_onchain_locksroot_to_channel_settled_state_changes] (
identifier[raiden] : identifier[RaidenService] ,
identifier[storage] : identifier[SQLiteStorage] ,
)-> keyword[None] :
literal[string]
identifier[batch_size] = literal[int]
identifier[batch_query] = identifier[storag... | def _add_onchain_locksroot_to_channel_settled_state_changes(raiden: RaidenService, storage: SQLiteStorage) -> None:
""" Adds `our_onchain_locksroot` and `partner_onchain_locksroot` to
ContractReceiveChannelSettled. """
batch_size = 50
batch_query = storage.batch_query_state_changes(batch_size=batch_size... |
def choices(self):
"""Gets the experiment choices"""
if self._choices == None:
self._choices = [ExperimentChoice(self, choice_name) for choice_name in self.choice_names]
return self._choices | def function[choices, parameter[self]]:
constant[Gets the experiment choices]
if compare[name[self]._choices equal[==] constant[None]] begin[:]
name[self]._choices assign[=] <ast.ListComp object at 0x7da1b0b72a40>
return[name[self]._choices] | keyword[def] identifier[choices] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_choices] == keyword[None] :
identifier[self] . identifier[_choices] =[ identifier[ExperimentChoice] ( identifier[self] , identifier[choice_name] ) keyword[for] identifie... | def choices(self):
"""Gets the experiment choices"""
if self._choices == None:
self._choices = [ExperimentChoice(self, choice_name) for choice_name in self.choice_names] # depends on [control=['if'], data=[]]
return self._choices |
def gradient(poly):
"""
Gradient of a polynomial.
Args:
poly (Poly) : polynomial to take gradient of.
Returns:
(Poly) : The resulting gradient.
Examples:
>>> q0, q1, q2 = chaospy.variable(3)
>>> poly = 2*q0 + q1*q2
>>> print(chaospy.gradient(poly))
... | def function[gradient, parameter[poly]]:
constant[
Gradient of a polynomial.
Args:
poly (Poly) : polynomial to take gradient of.
Returns:
(Poly) : The resulting gradient.
Examples:
>>> q0, q1, q2 = chaospy.variable(3)
>>> poly = 2*q0 + q1*q2
>>> print(c... | keyword[def] identifier[gradient] ( identifier[poly] ):
literal[string]
keyword[return] identifier[differential] ( identifier[poly] , identifier[chaospy] . identifier[poly] . identifier[collection] . identifier[basis] ( literal[int] , literal[int] , identifier[poly] . identifier[dim] )) | def gradient(poly):
"""
Gradient of a polynomial.
Args:
poly (Poly) : polynomial to take gradient of.
Returns:
(Poly) : The resulting gradient.
Examples:
>>> q0, q1, q2 = chaospy.variable(3)
>>> poly = 2*q0 + q1*q2
>>> print(chaospy.gradient(poly))
... |
def convert_timestamp_to_epoch(cls, timestamp, tsformat):
"""Converts the given timestamp into a float representing UNIX-epochs.
:param string timestamp: Timestamp in the defined format.
:param string tsformat: Format of the given timestamp. This is used to convert the
timestamp ... | def function[convert_timestamp_to_epoch, parameter[cls, timestamp, tsformat]]:
constant[Converts the given timestamp into a float representing UNIX-epochs.
:param string timestamp: Timestamp in the defined format.
:param string tsformat: Format of the given timestamp. This is used to convert... | keyword[def] identifier[convert_timestamp_to_epoch] ( identifier[cls] , identifier[timestamp] , identifier[tsformat] ):
literal[string]
keyword[return] identifier[time] . identifier[mktime] ( identifier[time] . identifier[strptime] ( identifier[timestamp] , identifier[tsformat] )) | def convert_timestamp_to_epoch(cls, timestamp, tsformat):
"""Converts the given timestamp into a float representing UNIX-epochs.
:param string timestamp: Timestamp in the defined format.
:param string tsformat: Format of the given timestamp. This is used to convert the
timestamp into... |
def devices(self, value):
"""
{ "PathOnHost": "/dev/deviceName", "PathInContainer": "/dev/deviceName", "CgroupPermissions": "mrw"}
"""
if value is None:
self._devices = None
elif isinstance(value, list):
results = []
delimiter = ':'
... | def function[devices, parameter[self, value]]:
constant[
{ "PathOnHost": "/dev/deviceName", "PathInContainer": "/dev/deviceName", "CgroupPermissions": "mrw"}
]
if compare[name[value] is constant[None]] begin[:]
name[self]._devices assign[=] constant[None] | keyword[def] identifier[devices] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[None] :
identifier[self] . identifier[_devices] = keyword[None]
keyword[elif] identifier[isinstance] ( identifier[value] , identi... | def devices(self, value):
"""
{ "PathOnHost": "/dev/deviceName", "PathInContainer": "/dev/deviceName", "CgroupPermissions": "mrw"}
"""
if value is None:
self._devices = None # depends on [control=['if'], data=[]]
elif isinstance(value, list):
results = []
delimiter =... |
def artifact_mime_type(instance):
"""Ensure the 'mime_type' property of artifact objects comes from the
Template column in the IANA media type registry.
"""
for key, obj in instance['objects'].items():
if ('type' in obj and obj['type'] == 'artifact' and 'mime_type' in obj):
if enums.... | def function[artifact_mime_type, parameter[instance]]:
constant[Ensure the 'mime_type' property of artifact objects comes from the
Template column in the IANA media type registry.
]
for taget[tuple[[<ast.Name object at 0x7da1b0fd66b0>, <ast.Name object at 0x7da1b0fd4a60>]]] in starred[call[call[... | keyword[def] identifier[artifact_mime_type] ( identifier[instance] ):
literal[string]
keyword[for] identifier[key] , identifier[obj] keyword[in] identifier[instance] [ literal[string] ]. identifier[items] ():
keyword[if] ( literal[string] keyword[in] identifier[obj] keyword[and] identifier[... | def artifact_mime_type(instance):
"""Ensure the 'mime_type' property of artifact objects comes from the
Template column in the IANA media type registry.
"""
for (key, obj) in instance['objects'].items():
if 'type' in obj and obj['type'] == 'artifact' and ('mime_type' in obj):
if enum... |
def keys(self):
"""Return a copy of the flat dictionary's list of keys.
See the note for :meth:`flatdict.FlatDict.items`.
:rtype: list
"""
keys = []
for key, value in self._values.items():
if isinstance(value, (FlatDict, dict)):
nested = [sel... | def function[keys, parameter[self]]:
constant[Return a copy of the flat dictionary's list of keys.
See the note for :meth:`flatdict.FlatDict.items`.
:rtype: list
]
variable[keys] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da1b05b7b80>, <ast.Name object a... | keyword[def] identifier[keys] ( identifier[self] ):
literal[string]
identifier[keys] =[]
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[self] . identifier[_values] . identifier[items] ():
keyword[if] identifier[isinstance] ( identifier[value] ,( id... | def keys(self):
"""Return a copy of the flat dictionary's list of keys.
See the note for :meth:`flatdict.FlatDict.items`.
:rtype: list
"""
keys = []
for (key, value) in self._values.items():
if isinstance(value, (FlatDict, dict)):
nested = [self._delimiter.join(... |
def get_preferred_submodules():
"""
Get all submodules of the main scientific modules and others of our
interest
"""
# Path to the modules database
modules_path = get_conf_path('db')
# Modules database
modules_db = PickleShareDB(modules_path)
if 'submodules' in modules_d... | def function[get_preferred_submodules, parameter[]]:
constant[
Get all submodules of the main scientific modules and others of our
interest
]
variable[modules_path] assign[=] call[name[get_conf_path], parameter[constant[db]]]
variable[modules_db] assign[=] call[name[PickleShareDB], p... | keyword[def] identifier[get_preferred_submodules] ():
literal[string]
identifier[modules_path] = identifier[get_conf_path] ( literal[string] )
identifier[modules_db] = identifier[PickleShareDB] ( identifier[modules_path] )
keyword[if] literal[string] keyword[in] identifier[... | def get_preferred_submodules():
"""
Get all submodules of the main scientific modules and others of our
interest
""" # Path to the modules database
modules_path = get_conf_path('db') # Modules database
modules_db = PickleShareDB(modules_path)
if 'submodules' in modules_db:
return m... |
def start_proxy(self, port=None):
"""Start the mitmproxy
"""
self.runner.info_log("Starting proxy...")
# Get a random port that is available
if not port:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('0.0.0.0', 0))
sock.... | def function[start_proxy, parameter[self, port]]:
constant[Start the mitmproxy
]
call[name[self].runner.info_log, parameter[constant[Starting proxy...]]]
if <ast.UnaryOp object at 0x7da20c7c91b0> begin[:]
variable[sock] assign[=] call[name[socket].socket, parameter[name[s... | keyword[def] identifier[start_proxy] ( identifier[self] , identifier[port] = keyword[None] ):
literal[string]
identifier[self] . identifier[runner] . identifier[info_log] ( literal[string] )
keyword[if] keyword[not] identifier[port] :
identifier[sock] = identifier... | def start_proxy(self, port=None):
"""Start the mitmproxy
"""
self.runner.info_log('Starting proxy...')
# Get a random port that is available
if not port:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('0.0.0.0', 0))
sock.listen(5)
self.proxy_p... |
def is_default(self):
"""Return True if no active values, or if the active value is the default"""
if not self.get_applicable_values():
return True
if self.get_value().is_default:
return True
return False | def function[is_default, parameter[self]]:
constant[Return True if no active values, or if the active value is the default]
if <ast.UnaryOp object at 0x7da204565240> begin[:]
return[constant[True]]
if call[name[self].get_value, parameter[]].is_default begin[:]
return[constant[Tru... | keyword[def] identifier[is_default] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[get_applicable_values] ():
keyword[return] keyword[True]
keyword[if] identifier[self] . identifier[get_value] (). identifier[is_default] :
... | def is_default(self):
"""Return True if no active values, or if the active value is the default"""
if not self.get_applicable_values():
return True # depends on [control=['if'], data=[]]
if self.get_value().is_default:
return True # depends on [control=['if'], data=[]]
return False |
def add(self, key, val):
"""Adds a (name, value) pair, doesn't overwrite the value if it already
exists.
>>> headers = HTTPHeaderDict(foo='bar')
>>> headers.add('Foo', 'baz')
>>> headers['foo']
'bar, baz'
"""
key_lower = key.lower()
new_vals = [ke... | def function[add, parameter[self, key, val]]:
constant[Adds a (name, value) pair, doesn't overwrite the value if it already
exists.
>>> headers = HTTPHeaderDict(foo='bar')
>>> headers.add('Foo', 'baz')
>>> headers['foo']
'bar, baz'
]
variable[key_lower] a... | keyword[def] identifier[add] ( identifier[self] , identifier[key] , identifier[val] ):
literal[string]
identifier[key_lower] = identifier[key] . identifier[lower] ()
identifier[new_vals] =[ identifier[key] , identifier[val] ]
identifier[vals] = identifier[self] . identifi... | def add(self, key, val):
"""Adds a (name, value) pair, doesn't overwrite the value if it already
exists.
>>> headers = HTTPHeaderDict(foo='bar')
>>> headers.add('Foo', 'baz')
>>> headers['foo']
'bar, baz'
"""
key_lower = key.lower()
new_vals = [key, val]
... |
def fit_first_and_second_harmonics(phi, intensities):
"""
Fit the first and second harmonic function values to a set of
(angle, intensity) pairs.
This function is used to compute corrections for ellipse fitting:
.. math::
f(phi) = y0 + a1*\\sin(phi) + b1*\\cos(phi) + a2*\\sin(2*phi) +
... | def function[fit_first_and_second_harmonics, parameter[phi, intensities]]:
constant[
Fit the first and second harmonic function values to a set of
(angle, intensity) pairs.
This function is used to compute corrections for ellipse fitting:
.. math::
f(phi) = y0 + a1*\sin(phi) + b1*\cos... | keyword[def] identifier[fit_first_and_second_harmonics] ( identifier[phi] , identifier[intensities] ):
literal[string]
identifier[a1] = identifier[b1] = identifier[a2] = identifier[b2] = literal[int]
keyword[def] identifier[optimize_func] ( identifier[x] ):
keyword[return] identifier[fir... | def fit_first_and_second_harmonics(phi, intensities):
"""
Fit the first and second harmonic function values to a set of
(angle, intensity) pairs.
This function is used to compute corrections for ellipse fitting:
.. math::
f(phi) = y0 + a1*\\sin(phi) + b1*\\cos(phi) + a2*\\sin(2*phi) +
... |
def get(self, sid):
"""
Constructs a IpAccessControlListMappingContext
:param sid: A 34 character string that uniquely identifies the resource to fetch.
:returns: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingContext
:rtype: t... | def function[get, parameter[self, sid]]:
constant[
Constructs a IpAccessControlListMappingContext
:param sid: A 34 character string that uniquely identifies the resource to fetch.
:returns: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappi... | keyword[def] identifier[get] ( identifier[self] , identifier[sid] ):
literal[string]
keyword[return] identifier[IpAccessControlListMappingContext] (
identifier[self] . identifier[_version] ,
identifier[account_sid] = identifier[self] . identifier[_solution] [ literal[string] ],
... | def get(self, sid):
"""
Constructs a IpAccessControlListMappingContext
:param sid: A 34 character string that uniquely identifies the resource to fetch.
:returns: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingContext
:rtype: twili... |
def create_toolbutton(entries, parent=None):
"""Create a toolbutton.
Args:
entries: List of (label, slot) tuples.
Returns:
`QtGui.QToolBar`.
"""
btn = QtGui.QToolButton(parent)
menu = QtGui.QMenu()
actions = []
for label, slot in entries:
action = add_menu_acti... | def function[create_toolbutton, parameter[entries, parent]]:
constant[Create a toolbutton.
Args:
entries: List of (label, slot) tuples.
Returns:
`QtGui.QToolBar`.
]
variable[btn] assign[=] call[name[QtGui].QToolButton, parameter[name[parent]]]
variable[menu] assign[... | keyword[def] identifier[create_toolbutton] ( identifier[entries] , identifier[parent] = keyword[None] ):
literal[string]
identifier[btn] = identifier[QtGui] . identifier[QToolButton] ( identifier[parent] )
identifier[menu] = identifier[QtGui] . identifier[QMenu] ()
identifier[actions] =[]
k... | def create_toolbutton(entries, parent=None):
"""Create a toolbutton.
Args:
entries: List of (label, slot) tuples.
Returns:
`QtGui.QToolBar`.
"""
btn = QtGui.QToolButton(parent)
menu = QtGui.QMenu()
actions = []
for (label, slot) in entries:
action = add_menu_act... |
def get_subscriptions(self):
"""
:calls: `GET /users/:user/subscriptions <http://developer.github.com/v3/activity/watching>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository.Repository`
"""
return github.PaginatedList.PaginatedList(
gi... | def function[get_subscriptions, parameter[self]]:
constant[
:calls: `GET /users/:user/subscriptions <http://developer.github.com/v3/activity/watching>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository.Repository`
]
return[call[name[github].PaginatedLi... | keyword[def] identifier[get_subscriptions] ( identifier[self] ):
literal[string]
keyword[return] identifier[github] . identifier[PaginatedList] . identifier[PaginatedList] (
identifier[github] . identifier[Repository] . identifier[Repository] ,
identifier[self] . identifier[_requ... | def get_subscriptions(self):
"""
:calls: `GET /users/:user/subscriptions <http://developer.github.com/v3/activity/watching>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository.Repository`
"""
return github.PaginatedList.PaginatedList(github.Repository.Repos... |
def split_matrix(M, contigs):
"""Split multiple chromosome matrix
Split a labeled matrix with multiple chromosomes
into unlabeled single-chromosome matrices. Inter chromosomal
contacts are discarded.
Parameters
----------
M : array_like
The multiple chromosome matrix to be split
... | def function[split_matrix, parameter[M, contigs]]:
constant[Split multiple chromosome matrix
Split a labeled matrix with multiple chromosomes
into unlabeled single-chromosome matrices. Inter chromosomal
contacts are discarded.
Parameters
----------
M : array_like
The multiple ... | keyword[def] identifier[split_matrix] ( identifier[M] , identifier[contigs] ):
literal[string]
identifier[index] = literal[int]
keyword[for] identifier[_] , identifier[chunk] keyword[in] identifier[itertools] . identifier[groubpy] ( identifier[contigs] ):
identifier[l] = identifier[len] ... | def split_matrix(M, contigs):
"""Split multiple chromosome matrix
Split a labeled matrix with multiple chromosomes
into unlabeled single-chromosome matrices. Inter chromosomal
contacts are discarded.
Parameters
----------
M : array_like
The multiple chromosome matrix to be split
... |
def open(self, pathobj):
"""
Opens the remote file and returns a file-like object HTTPResponse
Given the nature of HTTP streaming, this object doesn't support
seek()
"""
url = str(pathobj)
raw, code = self.rest_get_stream(url, auth=pathobj.auth, verify=pathobj.ver... | def function[open, parameter[self, pathobj]]:
constant[
Opens the remote file and returns a file-like object HTTPResponse
Given the nature of HTTP streaming, this object doesn't support
seek()
]
variable[url] assign[=] call[name[str], parameter[name[pathobj]]]
<as... | keyword[def] identifier[open] ( identifier[self] , identifier[pathobj] ):
literal[string]
identifier[url] = identifier[str] ( identifier[pathobj] )
identifier[raw] , identifier[code] = identifier[self] . identifier[rest_get_stream] ( identifier[url] , identifier[auth] = identifier[pathobj]... | def open(self, pathobj):
"""
Opens the remote file and returns a file-like object HTTPResponse
Given the nature of HTTP streaming, this object doesn't support
seek()
"""
url = str(pathobj)
(raw, code) = self.rest_get_stream(url, auth=pathobj.auth, verify=pathobj.verify, cert=... |
def make_auto_deployable(self, stage, swagger=None):
"""
Sets up the resource such that it will triggers a re-deployment when Swagger changes
:param swagger: Dictionary containing the Swagger definition of the API
"""
if not swagger:
return
# CloudFormation ... | def function[make_auto_deployable, parameter[self, stage, swagger]]:
constant[
Sets up the resource such that it will triggers a re-deployment when Swagger changes
:param swagger: Dictionary containing the Swagger definition of the API
]
if <ast.UnaryOp object at 0x7da20c76f0a0>... | keyword[def] identifier[make_auto_deployable] ( identifier[self] , identifier[stage] , identifier[swagger] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[swagger] :
keyword[return]
id... | def make_auto_deployable(self, stage, swagger=None):
"""
Sets up the resource such that it will triggers a re-deployment when Swagger changes
:param swagger: Dictionary containing the Swagger definition of the API
"""
if not swagger:
return # depends on [control=['if'], data=[]... |
def off(self):
"""Turn off the alsa_sink sink.
This disconnects the sink from the relevant session events.
"""
spotifyconnect._session_instance.player.off(
spotifyconnect.PlayerEvent.MUSIC_DELIVERY, self._on_music_delivery)
assert spotifyconnect._session_instance.pla... | def function[off, parameter[self]]:
constant[Turn off the alsa_sink sink.
This disconnects the sink from the relevant session events.
]
call[name[spotifyconnect]._session_instance.player.off, parameter[name[spotifyconnect].PlayerEvent.MUSIC_DELIVERY, name[self]._on_music_delivery]]
... | keyword[def] identifier[off] ( identifier[self] ):
literal[string]
identifier[spotifyconnect] . identifier[_session_instance] . identifier[player] . identifier[off] (
identifier[spotifyconnect] . identifier[PlayerEvent] . identifier[MUSIC_DELIVERY] , identifier[self] . identifier[_on_music... | def off(self):
"""Turn off the alsa_sink sink.
This disconnects the sink from the relevant session events.
"""
spotifyconnect._session_instance.player.off(spotifyconnect.PlayerEvent.MUSIC_DELIVERY, self._on_music_delivery)
assert spotifyconnect._session_instance.player.num_listeners(spotify... |
def text_summary(tag, text):
"""Outputs a `Summary` protocol buffer with audio data.
Parameters
----------
tag : str
A name for the generated summary. Will also serve as a series name in TensorBoard.
text : str
Text data.
Returns
-------
A `Summary` ... | def function[text_summary, parameter[tag, text]]:
constant[Outputs a `Summary` protocol buffer with audio data.
Parameters
----------
tag : str
A name for the generated summary. Will also serve as a series name in TensorBoard.
text : str
Text data.
Returns
... | keyword[def] identifier[text_summary] ( identifier[tag] , identifier[text] ):
literal[string]
identifier[plugin_data] =[ identifier[SummaryMetadata] . identifier[PluginData] ( identifier[plugin_name] = literal[string] )]
identifier[smd] = identifier[SummaryMetadata] ( identifier[plugin_data] = identif... | def text_summary(tag, text):
"""Outputs a `Summary` protocol buffer with audio data.
Parameters
----------
tag : str
A name for the generated summary. Will also serve as a series name in TensorBoard.
text : str
Text data.
Returns
-------
A `Summary` ... |
def BLT(self, params):
"""
BLT label
Branch to the instruction at label if the N flag is not the same as the V flag
"""
label = self.get_one_parameter(self.ONE_PARAMETER, params)
self.check_arguments(label_exists=(label,))
# BLT label
def BLT_func():
... | def function[BLT, parameter[self, params]]:
constant[
BLT label
Branch to the instruction at label if the N flag is not the same as the V flag
]
variable[label] assign[=] call[name[self].get_one_parameter, parameter[name[self].ONE_PARAMETER, name[params]]]
call[name[self... | keyword[def] identifier[BLT] ( identifier[self] , identifier[params] ):
literal[string]
identifier[label] = identifier[self] . identifier[get_one_parameter] ( identifier[self] . identifier[ONE_PARAMETER] , identifier[params] )
identifier[self] . identifier[check_arguments] ( identifier[la... | def BLT(self, params):
"""
BLT label
Branch to the instruction at label if the N flag is not the same as the V flag
"""
label = self.get_one_parameter(self.ONE_PARAMETER, params)
self.check_arguments(label_exists=(label,))
# BLT label
def BLT_func():
if self.is_N_se... |
def get_image(vm_):
'''
Return the image object to use
'''
images = avail_images()
vm_image = config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
)
if not isinstance(vm_image, six.string_types):
vm_image = six.text_type(vm_image)
for image in image... | def function[get_image, parameter[vm_]]:
constant[
Return the image object to use
]
variable[images] assign[=] call[name[avail_images], parameter[]]
variable[vm_image] assign[=] call[name[config].get_cloud_config_value, parameter[constant[image], name[vm_], name[__opts__]]]
if <a... | keyword[def] identifier[get_image] ( identifier[vm_] ):
literal[string]
identifier[images] = identifier[avail_images] ()
identifier[vm_image] = identifier[config] . identifier[get_cloud_config_value] (
literal[string] , identifier[vm_] , identifier[__opts__] , identifier[search_global] = keyword[... | def get_image(vm_):
"""
Return the image object to use
"""
images = avail_images()
vm_image = config.get_cloud_config_value('image', vm_, __opts__, search_global=False)
if not isinstance(vm_image, six.string_types):
vm_image = six.text_type(vm_image) # depends on [control=['if'], data=[... |
def route_filter_get(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Get details about a specific route filter.
:param name: The name of the route table to query.
:param resource_group: The resource group name assigned to the
route filter.
CLI Example:
.. code-bl... | def function[route_filter_get, parameter[name, resource_group]]:
constant[
.. versionadded:: 2019.2.0
Get details about a specific route filter.
:param name: The name of the route table to query.
:param resource_group: The resource group name assigned to the
route filter.
CLI Exa... | keyword[def] identifier[route_filter_get] ( identifier[name] , identifier[resource_group] ,** identifier[kwargs] ):
literal[string]
identifier[expand] = identifier[kwargs] . identifier[get] ( literal[string] )
identifier[netconn] = identifier[__utils__] [ literal[string] ]( literal[string] ,** identi... | def route_filter_get(name, resource_group, **kwargs):
"""
.. versionadded:: 2019.2.0
Get details about a specific route filter.
:param name: The name of the route table to query.
:param resource_group: The resource group name assigned to the
route filter.
CLI Example:
.. code-bl... |
def Read(cls, usb, expected_cmds, timeout_ms=None, total_timeout_ms=None):
"""Receive a response from the device."""
total_timeout_ms = usb.Timeout(total_timeout_ms)
start = time.time()
while True:
msg = usb.BulkRead(24, timeout_ms)
cmd, arg0, arg1, data_length, d... | def function[Read, parameter[cls, usb, expected_cmds, timeout_ms, total_timeout_ms]]:
constant[Receive a response from the device.]
variable[total_timeout_ms] assign[=] call[name[usb].Timeout, parameter[name[total_timeout_ms]]]
variable[start] assign[=] call[name[time].time, parameter[]]
... | keyword[def] identifier[Read] ( identifier[cls] , identifier[usb] , identifier[expected_cmds] , identifier[timeout_ms] = keyword[None] , identifier[total_timeout_ms] = keyword[None] ):
literal[string]
identifier[total_timeout_ms] = identifier[usb] . identifier[Timeout] ( identifier[total_timeout_ms... | def Read(cls, usb, expected_cmds, timeout_ms=None, total_timeout_ms=None):
"""Receive a response from the device."""
total_timeout_ms = usb.Timeout(total_timeout_ms)
start = time.time()
while True:
msg = usb.BulkRead(24, timeout_ms)
(cmd, arg0, arg1, data_length, data_checksum) = cls.Unp... |
def create_dataframe(ensemble):
"""
Create a data frame from given nested lists of ensemble data
:param list ensemble: Ensemble data
:return obj: Dataframe
"""
logger_dataframes.info("enter ens_to_df")
# "Flatten" the nested lists. Bring all nested lists up to top-level. Output looks like [ ... | def function[create_dataframe, parameter[ensemble]]:
constant[
Create a data frame from given nested lists of ensemble data
:param list ensemble: Ensemble data
:return obj: Dataframe
]
call[name[logger_dataframes].info, parameter[constant[enter ens_to_df]]]
variable[ll] assign[=]... | keyword[def] identifier[create_dataframe] ( identifier[ensemble] ):
literal[string]
identifier[logger_dataframes] . identifier[info] ( literal[string] )
identifier[ll] = identifier[unwrap_arrays] ( identifier[ensemble] )
identifier[valid] = identifier[match_arr_lengths] ( identifier[ll]... | def create_dataframe(ensemble):
"""
Create a data frame from given nested lists of ensemble data
:param list ensemble: Ensemble data
:return obj: Dataframe
"""
logger_dataframes.info('enter ens_to_df')
# "Flatten" the nested lists. Bring all nested lists up to top-level. Output looks like [ ... |
def create(cls, title, owner, extra_data, description="", expires_at=None):
"""Create a new secret link."""
if isinstance(expires_at, date):
expires_at = datetime.combine(expires_at, datetime.min.time())
with db.session.begin_nested():
obj = cls(
owner=ow... | def function[create, parameter[cls, title, owner, extra_data, description, expires_at]]:
constant[Create a new secret link.]
if call[name[isinstance], parameter[name[expires_at], name[date]]] begin[:]
variable[expires_at] assign[=] call[name[datetime].combine, parameter[name[expires_at],... | keyword[def] identifier[create] ( identifier[cls] , identifier[title] , identifier[owner] , identifier[extra_data] , identifier[description] = literal[string] , identifier[expires_at] = keyword[None] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[expires_at] , identifier[date] ... | def create(cls, title, owner, extra_data, description='', expires_at=None):
"""Create a new secret link."""
if isinstance(expires_at, date):
expires_at = datetime.combine(expires_at, datetime.min.time()) # depends on [control=['if'], data=[]]
with db.session.begin_nested():
obj = cls(owner=... |
def labels():
"""
Path to labels file
"""
datapath = path.join(path.dirname(path.realpath(__file__)), path.pardir)
datapath = path.join(datapath, '../gzoo_data', 'train_solution.csv')
return path.normpath(datapath) | def function[labels, parameter[]]:
constant[
Path to labels file
]
variable[datapath] assign[=] call[name[path].join, parameter[call[name[path].dirname, parameter[call[name[path].realpath, parameter[name[__file__]]]]], name[path].pardir]]
variable[datapath] assign[=] call[name[path].join... | keyword[def] identifier[labels] ():
literal[string]
identifier[datapath] = identifier[path] . identifier[join] ( identifier[path] . identifier[dirname] ( identifier[path] . identifier[realpath] ( identifier[__file__] )), identifier[path] . identifier[pardir] )
identifier[datapath] = identifier[path] .... | def labels():
"""
Path to labels file
"""
datapath = path.join(path.dirname(path.realpath(__file__)), path.pardir)
datapath = path.join(datapath, '../gzoo_data', 'train_solution.csv')
return path.normpath(datapath) |
def _from_line(cls, repo, line, fetch_line):
"""Parse information from the given line as returned by git-fetch -v
and return a new FetchInfo object representing this information.
We can handle a line as follows
"%c %-*s %-*s -> %s%s"
Where c is either ' ', !, +, -, *, or =
... | def function[_from_line, parameter[cls, repo, line, fetch_line]]:
constant[Parse information from the given line as returned by git-fetch -v
and return a new FetchInfo object representing this information.
We can handle a line as follows
"%c %-*s %-*s -> %s%s"
Where c is either... | keyword[def] identifier[_from_line] ( identifier[cls] , identifier[repo] , identifier[line] , identifier[fetch_line] ):
literal[string]
identifier[match] = identifier[cls] . identifier[_re_fetch_result] . identifier[match] ( identifier[line] )
keyword[if] identifier[match] keyword[is] k... | def _from_line(cls, repo, line, fetch_line):
"""Parse information from the given line as returned by git-fetch -v
and return a new FetchInfo object representing this information.
We can handle a line as follows
"%c %-*s %-*s -> %s%s"
Where c is either ' ', !, +, -, *, or =
... |
def finder(self, figsize=(7,7), **kwargs):
'''
Plot a finder chart. This *does* create a new figure.
'''
try:
center = self.meta['center']
radius = self.meta['radius']
except KeyError:
return self.allskyfinder(**kwargs)
plt.figure(fig... | def function[finder, parameter[self, figsize]]:
constant[
Plot a finder chart. This *does* create a new figure.
]
<ast.Try object at 0x7da1b16a80a0>
call[name[plt].figure, parameter[]]
variable[scatter] assign[=] call[name[self].plot, parameter[]]
call[name[plt].xlabe... | keyword[def] identifier[finder] ( identifier[self] , identifier[figsize] =( literal[int] , literal[int] ),** identifier[kwargs] ):
literal[string]
keyword[try] :
identifier[center] = identifier[self] . identifier[meta] [ literal[string] ]
identifier[radius] = identifier[s... | def finder(self, figsize=(7, 7), **kwargs):
"""
Plot a finder chart. This *does* create a new figure.
"""
try:
center = self.meta['center']
radius = self.meta['radius'] # depends on [control=['try'], data=[]]
except KeyError:
return self.allskyfinder(**kwargs) # dep... |
def updateItem(self, instance, subKey, value):
"""Updates a child value. Must be called before the update has actually occurred."""
instanceId = statsId(instance)
container = _Stats.getContainerForObject(instanceId)
self._aggregate(instanceId, container, value, subKey) | def function[updateItem, parameter[self, instance, subKey, value]]:
constant[Updates a child value. Must be called before the update has actually occurred.]
variable[instanceId] assign[=] call[name[statsId], parameter[name[instance]]]
variable[container] assign[=] call[name[_Stats].getContainer... | keyword[def] identifier[updateItem] ( identifier[self] , identifier[instance] , identifier[subKey] , identifier[value] ):
literal[string]
identifier[instanceId] = identifier[statsId] ( identifier[instance] )
identifier[container] = identifier[_Stats] . identifier[getContainerForObject] ( identifier[i... | def updateItem(self, instance, subKey, value):
"""Updates a child value. Must be called before the update has actually occurred."""
instanceId = statsId(instance)
container = _Stats.getContainerForObject(instanceId)
self._aggregate(instanceId, container, value, subKey) |
def _create_values_table(self):
"""Create table lexem_type->{identificator->vocabulary},
and return it with sizes of an identificator as lexem_type->identificator_size"""
# number of existing character, and returned dicts
len_alph = len(self.alphabet)
identificators_table = {k:{... | def function[_create_values_table, parameter[self]]:
constant[Create table lexem_type->{identificator->vocabulary},
and return it with sizes of an identificator as lexem_type->identificator_size]
variable[len_alph] assign[=] call[name[len], parameter[name[self].alphabet]]
variable[ident... | keyword[def] identifier[_create_values_table] ( identifier[self] ):
literal[string]
identifier[len_alph] = identifier[len] ( identifier[self] . identifier[alphabet] )
identifier[identificators_table] ={ identifier[k] :{} keyword[for] identifier[k] keyword[in] identifier[self] .... | def _create_values_table(self):
"""Create table lexem_type->{identificator->vocabulary},
and return it with sizes of an identificator as lexem_type->identificator_size"""
# number of existing character, and returned dicts
len_alph = len(self.alphabet)
identificators_table = {k: {} for k in self... |
def from_image(cls, filename, components,
ignore=None,
col_offset=0.1,
row_offset=2):
"""
A slightly easier way to make legends from images.
Args:
filename (str)
components (list)
ignore (list): Colours... | def function[from_image, parameter[cls, filename, components, ignore, col_offset, row_offset]]:
constant[
A slightly easier way to make legends from images.
Args:
filename (str)
components (list)
ignore (list): Colours to ignore, e.g. "#FFFFFF" to ignore whit... | keyword[def] identifier[from_image] ( identifier[cls] , identifier[filename] , identifier[components] ,
identifier[ignore] = keyword[None] ,
identifier[col_offset] = literal[int] ,
identifier[row_offset] = literal[int] ):
literal[string]
keyword[if] identifier[ignore] keyword[is] keyword[None... | def from_image(cls, filename, components, ignore=None, col_offset=0.1, row_offset=2):
"""
A slightly easier way to make legends from images.
Args:
filename (str)
components (list)
ignore (list): Colours to ignore, e.g. "#FFFFFF" to ignore white.
col_o... |
def clear_if_finalized(
iteration: TransitionResult,
) -> TransitionResult[InitiatorPaymentState]:
""" Clear the initiator payment task if all transfers have been finalized
or expired. """
state = cast(InitiatorPaymentState, iteration.new_state)
if state is None:
return iteration
i... | def function[clear_if_finalized, parameter[iteration]]:
constant[ Clear the initiator payment task if all transfers have been finalized
or expired. ]
variable[state] assign[=] call[name[cast], parameter[name[InitiatorPaymentState], name[iteration].new_state]]
if compare[name[state] is consta... | keyword[def] identifier[clear_if_finalized] (
identifier[iteration] : identifier[TransitionResult] ,
)-> identifier[TransitionResult] [ identifier[InitiatorPaymentState] ]:
literal[string]
identifier[state] = identifier[cast] ( identifier[InitiatorPaymentState] , identifier[iteration] . identifier[new_sta... | def clear_if_finalized(iteration: TransitionResult) -> TransitionResult[InitiatorPaymentState]:
""" Clear the initiator payment task if all transfers have been finalized
or expired. """
state = cast(InitiatorPaymentState, iteration.new_state)
if state is None:
return iteration # depends on [con... |
def inj_mass_pdf(key, mass1, mass2, lomass, himass, lomass_2 = 0, himass_2 = 0):
'''Estimate the probability density based on the injection strategy
Parameters
----------
key: string
Injection strategy
mass1: array
First mass of the injections
mass2: array
... | def function[inj_mass_pdf, parameter[key, mass1, mass2, lomass, himass, lomass_2, himass_2]]:
constant[Estimate the probability density based on the injection strategy
Parameters
----------
key: string
Injection strategy
mass1: array
First mass of the injections
... | keyword[def] identifier[inj_mass_pdf] ( identifier[key] , identifier[mass1] , identifier[mass2] , identifier[lomass] , identifier[himass] , identifier[lomass_2] = literal[int] , identifier[himass_2] = literal[int] ):
literal[string]
identifier[mass1] , identifier[mass2] = identifier[np] . identifier[arra... | def inj_mass_pdf(key, mass1, mass2, lomass, himass, lomass_2=0, himass_2=0):
"""Estimate the probability density based on the injection strategy
Parameters
----------
key: string
Injection strategy
mass1: array
First mass of the injections
mass2: array
... |
def predict_proba(self, dataframe):
"""Predict probabilities using the model
:param dataframe: Dataframe against which to make predictions
"""
ret = numpy.ones((dataframe.shape[0], 2))
ret[:, 0] = (1 - self.mean)
ret[:, 1] = self.mean
return ret | def function[predict_proba, parameter[self, dataframe]]:
constant[Predict probabilities using the model
:param dataframe: Dataframe against which to make predictions
]
variable[ret] assign[=] call[name[numpy].ones, parameter[tuple[[<ast.Subscript object at 0x7da20c7cb940>, <ast.Constant ... | keyword[def] identifier[predict_proba] ( identifier[self] , identifier[dataframe] ):
literal[string]
identifier[ret] = identifier[numpy] . identifier[ones] (( identifier[dataframe] . identifier[shape] [ literal[int] ], literal[int] ))
identifier[ret] [:, literal[int] ]=( literal[int] - ide... | def predict_proba(self, dataframe):
"""Predict probabilities using the model
:param dataframe: Dataframe against which to make predictions
"""
ret = numpy.ones((dataframe.shape[0], 2))
ret[:, 0] = 1 - self.mean
ret[:, 1] = self.mean
return ret |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.