code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def add_transition(self, output,
probability_func=lambda index: np.ones(len(index), dtype=float),
triggered=Trigger.NOT_TRIGGERED):
"""Builds a transition from this state to the given state.
output : State
The end state after the transition.
... | def function[add_transition, parameter[self, output, probability_func, triggered]]:
constant[Builds a transition from this state to the given state.
output : State
The end state after the transition.
]
variable[t] assign[=] call[name[Transition], parameter[name[self], name[o... | keyword[def] identifier[add_transition] ( identifier[self] , identifier[output] ,
identifier[probability_func] = keyword[lambda] identifier[index] : identifier[np] . identifier[ones] ( identifier[len] ( identifier[index] ), identifier[dtype] = identifier[float] ),
identifier[triggered] = identifier[Trigger] . iden... | def add_transition(self, output, probability_func=lambda index: np.ones(len(index), dtype=float), triggered=Trigger.NOT_TRIGGERED):
"""Builds a transition from this state to the given state.
output : State
The end state after the transition.
"""
t = Transition(self, output, probabil... |
def post_message(self, channel_id, message, **kwargs):
"""
Send a message using the slack Event API.
Event messages should be used for more complex messages. See
https://api.slack.com/methods/chat.postMessage for details on arguments can be included
with your message.
W... | def function[post_message, parameter[self, channel_id, message]]:
constant[
Send a message using the slack Event API.
Event messages should be used for more complex messages. See
https://api.slack.com/methods/chat.postMessage for details on arguments can be included
with your me... | keyword[def] identifier[post_message] ( identifier[self] , identifier[channel_id] , identifier[message] ,** identifier[kwargs] ):
literal[string]
identifier[params] ={
literal[string] :{
literal[string] : identifier[message] ,
literal[string] : identifier[channel_id] ,
... | def post_message(self, channel_id, message, **kwargs):
"""
Send a message using the slack Event API.
Event messages should be used for more complex messages. See
https://api.slack.com/methods/chat.postMessage for details on arguments can be included
with your message.
When ... |
def interp(self, new_timestamps, interpolation_mode=0):
""" returns a new *Signal* interpolated using the *new_timestamps*
Parameters
----------
new_timestamps : np.array
timestamps used for interpolation
interpolation_mode : int
interpolation mode for in... | def function[interp, parameter[self, new_timestamps, interpolation_mode]]:
constant[ returns a new *Signal* interpolated using the *new_timestamps*
Parameters
----------
new_timestamps : np.array
timestamps used for interpolation
interpolation_mode : int
... | keyword[def] identifier[interp] ( identifier[self] , identifier[new_timestamps] , identifier[interpolation_mode] = literal[int] ):
literal[string]
keyword[if] keyword[not] identifier[len] ( identifier[self] . identifier[samples] ) keyword[or] keyword[not] identifier[len] ( identifier[new_timest... | def interp(self, new_timestamps, interpolation_mode=0):
""" returns a new *Signal* interpolated using the *new_timestamps*
Parameters
----------
new_timestamps : np.array
timestamps used for interpolation
interpolation_mode : int
interpolation mode for intege... |
def _adapt_param(self, key, val):
"""
Adapt the value if an adapter is defined.
"""
if key in self.param_adapters:
try:
return self.param_adapters[key](val)
except (AdaptError, AdaptErrors, TypeError, ValueError) as e:
if hasattr(e,... | def function[_adapt_param, parameter[self, key, val]]:
constant[
Adapt the value if an adapter is defined.
]
if compare[name[key] in name[self].param_adapters] begin[:]
<ast.Try object at 0x7da18fe90f10> | keyword[def] identifier[_adapt_param] ( identifier[self] , identifier[key] , identifier[val] ):
literal[string]
keyword[if] identifier[key] keyword[in] identifier[self] . identifier[param_adapters] :
keyword[try] :
keyword[return] identifier[self] . identifier[para... | def _adapt_param(self, key, val):
"""
Adapt the value if an adapter is defined.
"""
if key in self.param_adapters:
try:
return self.param_adapters[key](val) # depends on [control=['try'], data=[]]
except (AdaptError, AdaptErrors, TypeError, ValueError) as e:
... |
def from_json(value, native_datetimes=True):
"""
Deserializes the given value from JSON.
:param value: the value to deserialize
:type value: str
:param native_datetimes:
whether or not strings that look like dates/times should be
automatically cast to the native objects, or left as ... | def function[from_json, parameter[value, native_datetimes]]:
constant[
Deserializes the given value from JSON.
:param value: the value to deserialize
:type value: str
:param native_datetimes:
whether or not strings that look like dates/times should be
automatically cast to the n... | keyword[def] identifier[from_json] ( identifier[value] , identifier[native_datetimes] = keyword[True] ):
literal[string]
identifier[hook] = identifier[BasicJsonDecoder] ( identifier[native_datetimes] = identifier[native_datetimes] )
identifier[result] = identifier[json] . identifier[loads] ( identifi... | def from_json(value, native_datetimes=True):
"""
Deserializes the given value from JSON.
:param value: the value to deserialize
:type value: str
:param native_datetimes:
whether or not strings that look like dates/times should be
automatically cast to the native objects, or left as ... |
def on_clear(self, event):
"""
initialize window to allow user to empty the working directory
"""
dia = pmag_menu_dialogs.ClearWD(self.parent, self.parent.WD)
clear = dia.do_clear()
if clear:
print('-I- Clear data object')
self.parent.er_magic = bu... | def function[on_clear, parameter[self, event]]:
constant[
initialize window to allow user to empty the working directory
]
variable[dia] assign[=] call[name[pmag_menu_dialogs].ClearWD, parameter[name[self].parent, name[self].parent.WD]]
variable[clear] assign[=] call[name[dia].do... | keyword[def] identifier[on_clear] ( identifier[self] , identifier[event] ):
literal[string]
identifier[dia] = identifier[pmag_menu_dialogs] . identifier[ClearWD] ( identifier[self] . identifier[parent] , identifier[self] . identifier[parent] . identifier[WD] )
identifier[clear] = identifie... | def on_clear(self, event):
"""
initialize window to allow user to empty the working directory
"""
dia = pmag_menu_dialogs.ClearWD(self.parent, self.parent.WD)
clear = dia.do_clear()
if clear:
print('-I- Clear data object')
self.parent.er_magic = builder.ErMagicBuilder(sel... |
def rebuild_collection_tree(old_collection_ident, new_document_id_map, plpy):
"""Create a new tree for the collection based on the old tree.
This uses new document ids, replacing old ones.
"""
get_tree = plpy.prepare('''
WITH RECURSIVE t(node, parent, document, title, childorder, latest, path)
... | def function[rebuild_collection_tree, parameter[old_collection_ident, new_document_id_map, plpy]]:
constant[Create a new tree for the collection based on the old tree.
This uses new document ids, replacing old ones.
]
variable[get_tree] assign[=] call[name[plpy].prepare, parameter[constant[
... | keyword[def] identifier[rebuild_collection_tree] ( identifier[old_collection_ident] , identifier[new_document_id_map] , identifier[plpy] ):
literal[string]
identifier[get_tree] = identifier[plpy] . identifier[prepare] ( literal[string] ,( literal[string] ,))
keyword[def] identifier[get_old_tree] ():... | def rebuild_collection_tree(old_collection_ident, new_document_id_map, plpy):
"""Create a new tree for the collection based on the old tree.
This uses new document ids, replacing old ones.
"""
get_tree = plpy.prepare("\n WITH RECURSIVE t(node, parent, document, title, childorder, latest, path)\n ... |
def get_report(self):
""" describe the graph
:returns: report
:rtype: string
"""
ostr = ''
ostr += "Nodes: "+str(len(self.__nodes.keys()))+"\n"
ostr += "Edges: "+str(len(self.__edges.keys()))+"\n"
return ostr | def function[get_report, parameter[self]]:
constant[ describe the graph
:returns: report
:rtype: string
]
variable[ostr] assign[=] constant[]
<ast.AugAssign object at 0x7da1b0a66b90>
<ast.AugAssign object at 0x7da1b0a66e00>
return[name[ostr]] | keyword[def] identifier[get_report] ( identifier[self] ):
literal[string]
identifier[ostr] = literal[string]
identifier[ostr] += literal[string] + identifier[str] ( identifier[len] ( identifier[self] . identifier[__nodes] . identifier[keys] ()))+ literal[string]
identifier[ostr] += literal[stri... | def get_report(self):
""" describe the graph
:returns: report
:rtype: string
"""
ostr = ''
ostr += 'Nodes: ' + str(len(self.__nodes.keys())) + '\n'
ostr += 'Edges: ' + str(len(self.__edges.keys())) + '\n'
return ostr |
def addEntry(self):
"""Add the `Plot pyBAR data`. entry to `Dataset` menu.
"""
export_icon = QtGui.QIcon()
pixmap = QtGui.QPixmap(os.path.join(PLUGINSDIR,
'csv/icons/document-export.png'))
export_icon.addPixmap(pixmap, QtGui.QIcon.Norma... | def function[addEntry, parameter[self]]:
constant[Add the `Plot pyBAR data`. entry to `Dataset` menu.
]
variable[export_icon] assign[=] call[name[QtGui].QIcon, parameter[]]
variable[pixmap] assign[=] call[name[QtGui].QPixmap, parameter[call[name[os].path.join, parameter[name[PLUGINSDIR],... | keyword[def] identifier[addEntry] ( identifier[self] ):
literal[string]
identifier[export_icon] = identifier[QtGui] . identifier[QIcon] ()
identifier[pixmap] = identifier[QtGui] . identifier[QPixmap] ( identifier[os] . identifier[path] . identifier[join] ( identifier[PLUGINSDIR] ,
... | def addEntry(self):
"""Add the `Plot pyBAR data`. entry to `Dataset` menu.
"""
export_icon = QtGui.QIcon()
pixmap = QtGui.QPixmap(os.path.join(PLUGINSDIR, 'csv/icons/document-export.png'))
export_icon.addPixmap(pixmap, QtGui.QIcon.Normal, QtGui.QIcon.On)
self.plot_action = QtGui.QAction(tran... |
def ask_confirmation():
"""Ask for confirmation to the user. Return true if the user confirmed
the execution, false otherwise.
:returns: bool
"""
while True:
print("Do you want to restart these brokers? ", end="")
choice = input().lower()
if choice in ['yes', 'y']:
... | def function[ask_confirmation, parameter[]]:
constant[Ask for confirmation to the user. Return true if the user confirmed
the execution, false otherwise.
:returns: bool
]
while constant[True] begin[:]
call[name[print], parameter[constant[Do you want to restart these brokers?... | keyword[def] identifier[ask_confirmation] ():
literal[string]
keyword[while] keyword[True] :
identifier[print] ( literal[string] , identifier[end] = literal[string] )
identifier[choice] = identifier[input] (). identifier[lower] ()
keyword[if] identifier[choice] keyword[in] [ l... | def ask_confirmation():
"""Ask for confirmation to the user. Return true if the user confirmed
the execution, false otherwise.
:returns: bool
"""
while True:
print('Do you want to restart these brokers? ', end='')
choice = input().lower()
if choice in ['yes', 'y']:
... |
def _create(self):
""" Create new object on IxNetwork.
:return: IXN object reference.
"""
if 'name' in self._data:
obj_ref = self.api.add(self.obj_parent(), self.obj_type(), name=self.obj_name())
else:
obj_ref = self.api.add(self.obj_parent(), self.obj_t... | def function[_create, parameter[self]]:
constant[ Create new object on IxNetwork.
:return: IXN object reference.
]
if compare[constant[name] in name[self]._data] begin[:]
variable[obj_ref] assign[=] call[name[self].api.add, parameter[call[name[self].obj_parent, parameter... | keyword[def] identifier[_create] ( identifier[self] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[self] . identifier[_data] :
identifier[obj_ref] = identifier[self] . identifier[api] . identifier[add] ( identifier[self] . identifier[obj_parent] (), identifie... | def _create(self):
""" Create new object on IxNetwork.
:return: IXN object reference.
"""
if 'name' in self._data:
obj_ref = self.api.add(self.obj_parent(), self.obj_type(), name=self.obj_name()) # depends on [control=['if'], data=[]]
else:
obj_ref = self.api.add(self.obj_p... |
def getPlugins():
"""
Returns the list of valid ue4cli plugins
"""
# Retrieve the list of detected entry points in the ue4cli.plugins group
plugins = {
entry_point.name: entry_point.load()
for entry_point
in pkg_resources.iter_entry_points('ue4cli.plugins')
}
# Filter out any invalid plugin... | def function[getPlugins, parameter[]]:
constant[
Returns the list of valid ue4cli plugins
]
variable[plugins] assign[=] <ast.DictComp object at 0x7da18f00e080>
variable[plugins] assign[=] <ast.DictComp object at 0x7da18f00e980>
return[name[plugins]] | keyword[def] identifier[getPlugins] ():
literal[string]
identifier[plugins] ={
identifier[entry_point] . identifier[name] : identifier[entry_point] . identifier[load] ()
keyword[for] identifier[entry_point]
keyword[in] identifier[pkg_resources] . identifier[iter_entry_points] ( literal[string] ... | def getPlugins():
"""
Returns the list of valid ue4cli plugins
""" # Retrieve the list of detected entry points in the ue4cli.plugins group
plugins = {entry_point.name: entry_point.load() for entry_point in pkg_resources.iter_entry_points('ue4cli.plugins')} # Filter out any invalid plugins
plugins = {... |
def _make_cmd_list(cmd_list):
"""
Helper function to easily create the proper json formated string from a list of strs
:param cmd_list: list of strings
:return: str json formatted
"""
cmd = ''
for i in cmd_list:
cmd = cmd + '"' + i + '",'
cmd = cmd[:-1]
return cmd | def function[_make_cmd_list, parameter[cmd_list]]:
constant[
Helper function to easily create the proper json formated string from a list of strs
:param cmd_list: list of strings
:return: str json formatted
]
variable[cmd] assign[=] constant[]
for taget[name[i]] in starred[name[c... | keyword[def] identifier[_make_cmd_list] ( identifier[cmd_list] ):
literal[string]
identifier[cmd] = literal[string]
keyword[for] identifier[i] keyword[in] identifier[cmd_list] :
identifier[cmd] = identifier[cmd] + literal[string] + identifier[i] + literal[string]
identifier[cmd] = i... | def _make_cmd_list(cmd_list):
"""
Helper function to easily create the proper json formated string from a list of strs
:param cmd_list: list of strings
:return: str json formatted
"""
cmd = ''
for i in cmd_list:
cmd = cmd + '"' + i + '",' # depends on [control=['for'], data=['i']]
... |
def get_location(self,callb=None):
"""Convenience method to request the location from the device
This method will check whether the value has already been retrieved from the device,
if so, it will simply return it. If no, it will request the information from the device
and request that ... | def function[get_location, parameter[self, callb]]:
constant[Convenience method to request the location from the device
This method will check whether the value has already been retrieved from the device,
if so, it will simply return it. If no, it will request the information from the device
... | keyword[def] identifier[get_location] ( identifier[self] , identifier[callb] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[location] keyword[is] keyword[None] :
identifier[mypartial] = identifier[partial] ( identifier[self] . identifier[resp_set_locati... | def get_location(self, callb=None):
"""Convenience method to request the location from the device
This method will check whether the value has already been retrieved from the device,
if so, it will simply return it. If no, it will request the information from the device
and request that cal... |
def get_value(self, series, key):
"""
Fast lookup of value from 1-dimensional ndarray. Only use this if you
know what you're doing.
"""
# if we have something that is Index-like, then
# use this, e.g. DatetimeIndex
# Things like `Series._get_value` (via .at) pass... | def function[get_value, parameter[self, series, key]]:
constant[
Fast lookup of value from 1-dimensional ndarray. Only use this if you
know what you're doing.
]
variable[s] assign[=] call[name[getattr], parameter[name[series], constant[_values], name[series]]]
if <ast.Boo... | keyword[def] identifier[get_value] ( identifier[self] , identifier[series] , identifier[key] ):
literal[string]
identifier[s] = identifier[getattr] ( identifier[series] , literal[string] , identifier[series] )
keyword[if] identifier[isinstance] ( identifier[s] ... | def get_value(self, series, key):
"""
Fast lookup of value from 1-dimensional ndarray. Only use this if you
know what you're doing.
"""
# if we have something that is Index-like, then
# use this, e.g. DatetimeIndex
# Things like `Series._get_value` (via .at) pass the EA directly ... |
def get_interfaces_ip(self):
'''Return IP interface data.'''
def extract_ip_info(parsed_intf_dict):
'''
IPv4:
- Primary IP is in the '<ip>' tag. If no v4 is configured the return value is 'N/A'.
- Secondary IP's are in '<addr>'. If no secondaries, thi... | def function[get_interfaces_ip, parameter[self]]:
constant[Return IP interface data.]
def function[extract_ip_info, parameter[parsed_intf_dict]]:
constant[
IPv4:
- Primary IP is in the '<ip>' tag. If no v4 is configured the return value is 'N/A'.
-... | keyword[def] identifier[get_interfaces_ip] ( identifier[self] ):
literal[string]
keyword[def] identifier[extract_ip_info] ( identifier[parsed_intf_dict] ):
literal[string]
identifier[intf] = identifier[parsed_intf_dict] [ literal[string] ]
identifier[_ip_in... | def get_interfaces_ip(self):
"""Return IP interface data."""
def extract_ip_info(parsed_intf_dict):
"""
IPv4:
- Primary IP is in the '<ip>' tag. If no v4 is configured the return value is 'N/A'.
- Secondary IP's are in '<addr>'. If no secondaries, this field is n... |
def _relative_name(self, record_name):
"""Returns sub-domain of a domain name"""
# Handle None and empty strings as None
if not record_name:
return None
subdomain = super(Provider, self)._relative_name(record_name)
return subdomain if subdomain else None | def function[_relative_name, parameter[self, record_name]]:
constant[Returns sub-domain of a domain name]
if <ast.UnaryOp object at 0x7da1b1d22f20> begin[:]
return[constant[None]]
variable[subdomain] assign[=] call[call[name[super], parameter[name[Provider], name[self]]]._relative_name, ... | keyword[def] identifier[_relative_name] ( identifier[self] , identifier[record_name] ):
literal[string]
keyword[if] keyword[not] identifier[record_name] :
keyword[return] keyword[None]
identifier[subdomain] = identifier[super] ( identifier[Provider] , identifier[s... | def _relative_name(self, record_name):
"""Returns sub-domain of a domain name"""
# Handle None and empty strings as None
if not record_name:
return None # depends on [control=['if'], data=[]]
subdomain = super(Provider, self)._relative_name(record_name)
return subdomain if subdomain else No... |
def dumps(obj):
"""Outputs json with formatting edits + object handling."""
return json.dumps(obj, indent=4, sort_keys=True, cls=CustomEncoder) | def function[dumps, parameter[obj]]:
constant[Outputs json with formatting edits + object handling.]
return[call[name[json].dumps, parameter[name[obj]]]] | keyword[def] identifier[dumps] ( identifier[obj] ):
literal[string]
keyword[return] identifier[json] . identifier[dumps] ( identifier[obj] , identifier[indent] = literal[int] , identifier[sort_keys] = keyword[True] , identifier[cls] = identifier[CustomEncoder] ) | def dumps(obj):
"""Outputs json with formatting edits + object handling."""
return json.dumps(obj, indent=4, sort_keys=True, cls=CustomEncoder) |
def index(self, val, start=None, stop=None):
"""
Return the smallest *k* such that L[k] == val and i <= k < j`. Raises
ValueError if *val* is not present. *stop* defaults to the end of the
list. *start* defaults to the beginning. Negative indices are supported,
as for slice ind... | def function[index, parameter[self, val, start, stop]]:
constant[
Return the smallest *k* such that L[k] == val and i <= k < j`. Raises
ValueError if *val* is not present. *stop* defaults to the end of the
list. *start* defaults to the beginning. Negative indices are supported,
... | keyword[def] identifier[index] ( identifier[self] , identifier[val] , identifier[start] = keyword[None] , identifier[stop] = keyword[None] ):
literal[string]
identifier[_len] = identifier[self] . identifier[_len]
keyword[if] keyword[not] identifier[_len] :
keyword[raise] ... | def index(self, val, start=None, stop=None):
"""
Return the smallest *k* such that L[k] == val and i <= k < j`. Raises
ValueError if *val* is not present. *stop* defaults to the end of the
list. *start* defaults to the beginning. Negative indices are supported,
as for slice indices... |
def _allocate_from_v6_subnet(self, context, net_id, subnet,
port_id, reuse_after, ip_address=None,
**kwargs):
"""This attempts to allocate v6 addresses as per RFC2462 and RFC3041.
To accomodate this, we effectively treat all v6 assignmen... | def function[_allocate_from_v6_subnet, parameter[self, context, net_id, subnet, port_id, reuse_after, ip_address]]:
constant[This attempts to allocate v6 addresses as per RFC2462 and RFC3041.
To accomodate this, we effectively treat all v6 assignment as a
first time allocation utilizing the MAC... | keyword[def] identifier[_allocate_from_v6_subnet] ( identifier[self] , identifier[context] , identifier[net_id] , identifier[subnet] ,
identifier[port_id] , identifier[reuse_after] , identifier[ip_address] = keyword[None] ,
** identifier[kwargs] ):
literal[string]
identifier[LOG] . identifier[inf... | def _allocate_from_v6_subnet(self, context, net_id, subnet, port_id, reuse_after, ip_address=None, **kwargs):
"""This attempts to allocate v6 addresses as per RFC2462 and RFC3041.
To accomodate this, we effectively treat all v6 assignment as a
first time allocation utilizing the MAC address of the ... |
def expand_tamil(start,end):
""" expand uyir or mei-letter range etc.
i.e. அ-ஔ gets converted to அ,ஆ,இ,ஈ,உ,ஊ,எ,ஏ,ஐ,ஒ,ஓ,ஔ etc.
"""
# few sequences
for seq in [utf8.uyir_letters, utf8.grantha_mei_letters, \
utf8.grantha_agaram_letters]:
if is_containing_seq(start,end,seq):... | def function[expand_tamil, parameter[start, end]]:
constant[ expand uyir or mei-letter range etc.
i.e. அ-ஔ gets converted to அ,ஆ,இ,ஈ,உ,ஊ,எ,ஏ,ஐ,ஒ,ஓ,ஔ etc.
]
for taget[name[seq]] in starred[list[[<ast.Attribute object at 0x7da1b06982e0>, <ast.Attribute object at 0x7da1b06985e0>, <ast.Attribut... | keyword[def] identifier[expand_tamil] ( identifier[start] , identifier[end] ):
literal[string]
keyword[for] identifier[seq] keyword[in] [ identifier[utf8] . identifier[uyir_letters] , identifier[utf8] . identifier[grantha_mei_letters] , identifier[utf8] . identifier[grantha_agaram_letters] ]:
... | def expand_tamil(start, end):
""" expand uyir or mei-letter range etc.
i.e. அ-ஔ gets converted to அ,ஆ,இ,ஈ,உ,ஊ,எ,ஏ,ஐ,ஒ,ஓ,ஔ etc.
"""
# few sequences
for seq in [utf8.uyir_letters, utf8.grantha_mei_letters, utf8.grantha_agaram_letters]:
if is_containing_seq(start, end, seq):
re... |
def allPolygons(self):
"""
Return a list of all polygons in this BSP tree.
"""
polygons = self.polygons[:]
if self.front:
polygons.extend(self.front.allPolygons())
if self.back:
polygons.extend(self.back.allPolygons())
return polygons | def function[allPolygons, parameter[self]]:
constant[
Return a list of all polygons in this BSP tree.
]
variable[polygons] assign[=] call[name[self].polygons][<ast.Slice object at 0x7da18c4cd060>]
if name[self].front begin[:]
call[name[polygons].extend, parameter[... | keyword[def] identifier[allPolygons] ( identifier[self] ):
literal[string]
identifier[polygons] = identifier[self] . identifier[polygons] [:]
keyword[if] identifier[self] . identifier[front] :
identifier[polygons] . identifier[extend] ( identifier[self] . identifier[front] . ... | def allPolygons(self):
"""
Return a list of all polygons in this BSP tree.
"""
polygons = self.polygons[:]
if self.front:
polygons.extend(self.front.allPolygons()) # depends on [control=['if'], data=[]]
if self.back:
polygons.extend(self.back.allPolygons()) # depends on... |
def _isCompatible(self, other, reporter):
"""
This is the environment implementation of
:meth:`BaseGlyph.isCompatible`.
Subclasses may override this method.
"""
glyph1 = self
glyph2 = other
# contour count
if len(self.contours) != len(glyph2.conto... | def function[_isCompatible, parameter[self, other, reporter]]:
constant[
This is the environment implementation of
:meth:`BaseGlyph.isCompatible`.
Subclasses may override this method.
]
variable[glyph1] assign[=] name[self]
variable[glyph2] assign[=] name[other]
... | keyword[def] identifier[_isCompatible] ( identifier[self] , identifier[other] , identifier[reporter] ):
literal[string]
identifier[glyph1] = identifier[self]
identifier[glyph2] = identifier[other]
keyword[if] identifier[len] ( identifier[self] . identifier[contours] )!... | def _isCompatible(self, other, reporter):
"""
This is the environment implementation of
:meth:`BaseGlyph.isCompatible`.
Subclasses may override this method.
"""
glyph1 = self
glyph2 = other
# contour count
if len(self.contours) != len(glyph2.contours):
report... |
def read_chd_header(chd_file):
"""
read the .chd header file created when Vision Research software saves the images in a file format other than .cine
"""
with open(chd_file, "rb") as f:
header = {
"cinefileheader": cine.CINEFILEHEADER(),
"bitmapinfoheader": cine.BITMAPIN... | def function[read_chd_header, parameter[chd_file]]:
constant[
read the .chd header file created when Vision Research software saves the images in a file format other than .cine
]
with call[name[open], parameter[name[chd_file], constant[rb]]] begin[:]
variable[header] assign[=] di... | keyword[def] identifier[read_chd_header] ( identifier[chd_file] ):
literal[string]
keyword[with] identifier[open] ( identifier[chd_file] , literal[string] ) keyword[as] identifier[f] :
identifier[header] ={
literal[string] : identifier[cine] . identifier[CINEFILEHEADER] (),
li... | def read_chd_header(chd_file):
"""
read the .chd header file created when Vision Research software saves the images in a file format other than .cine
"""
with open(chd_file, 'rb') as f:
header = {'cinefileheader': cine.CINEFILEHEADER(), 'bitmapinfoheader': cine.BITMAPINFOHEADER(), 'setup': cine.... |
def check(self, action, page=None, lang=None, method=None):
"""Return ``True`` if the current user has permission on the page."""
if self.user.is_superuser:
return True
if action == 'change':
return self.has_change_permission(page, lang, method)
if action == 'de... | def function[check, parameter[self, action, page, lang, method]]:
constant[Return ``True`` if the current user has permission on the page.]
if name[self].user.is_superuser begin[:]
return[constant[True]]
if compare[name[action] equal[==] constant[change]] begin[:]
return[call[nam... | keyword[def] identifier[check] ( identifier[self] , identifier[action] , identifier[page] = keyword[None] , identifier[lang] = keyword[None] , identifier[method] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[user] . identifier[is_superuser] :
keyword[ret... | def check(self, action, page=None, lang=None, method=None):
"""Return ``True`` if the current user has permission on the page."""
if self.user.is_superuser:
return True # depends on [control=['if'], data=[]]
if action == 'change':
return self.has_change_permission(page, lang, method) # dep... |
def list_task_definitions(self):
"""
Filtering not implemented
"""
task_arns = []
for task_definition_list in self.task_definitions.values():
task_arns.extend(
[task_definition.arn for task_definition in task_definition_list])
return task_arns | def function[list_task_definitions, parameter[self]]:
constant[
Filtering not implemented
]
variable[task_arns] assign[=] list[[]]
for taget[name[task_definition_list]] in starred[call[name[self].task_definitions.values, parameter[]]] begin[:]
call[name[task_arns]... | keyword[def] identifier[list_task_definitions] ( identifier[self] ):
literal[string]
identifier[task_arns] =[]
keyword[for] identifier[task_definition_list] keyword[in] identifier[self] . identifier[task_definitions] . identifier[values] ():
identifier[task_arns] . identifi... | def list_task_definitions(self):
"""
Filtering not implemented
"""
task_arns = []
for task_definition_list in self.task_definitions.values():
task_arns.extend([task_definition.arn for task_definition in task_definition_list]) # depends on [control=['for'], data=['task_definition_lis... |
def parseTextModeTimeStr(timeStr):
""" Parses the specified SMS text mode time string
The time stamp format is "yy/MM/dd,hh:mm:ss±zz"
(yy = year, MM = month, dd = day, hh = hour, mm = minute, ss = second, zz = time zone
[Note: the unit of time zone is a quarter of an hour])
:param timeStr:... | def function[parseTextModeTimeStr, parameter[timeStr]]:
constant[ Parses the specified SMS text mode time string
The time stamp format is "yy/MM/dd,hh:mm:ss±zz"
(yy = year, MM = month, dd = day, hh = hour, mm = minute, ss = second, zz = time zone
[Note: the unit of time zone is a quarter of an ... | keyword[def] identifier[parseTextModeTimeStr] ( identifier[timeStr] ):
literal[string]
identifier[msgTime] = identifier[timeStr] [:- literal[int] ]
identifier[tzOffsetHours] = identifier[int] ( identifier[int] ( identifier[timeStr] [- literal[int] :])* literal[int] )
keyword[return] identifier[d... | def parseTextModeTimeStr(timeStr):
""" Parses the specified SMS text mode time string
The time stamp format is "yy/MM/dd,hh:mm:ss±zz"
(yy = year, MM = month, dd = day, hh = hour, mm = minute, ss = second, zz = time zone
[Note: the unit of time zone is a quarter of an hour])
:param timeStr:... |
def alias_authorization(self, authorization_id, alias_id):
"""Adds an ``Id`` to an ``Authorization`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Authorization`` is determined by the
provider. The new ``Id`` performs as an alias to the primary
``Id``. If the al... | def function[alias_authorization, parameter[self, authorization_id, alias_id]]:
constant[Adds an ``Id`` to an ``Authorization`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Authorization`` is determined by the
provider. The new ``Id`` performs as an alias to the primar... | keyword[def] identifier[alias_authorization] ( identifier[self] , identifier[authorization_id] , identifier[alias_id] ):
literal[string]
identifier[self] . identifier[_alias_id] ( identifier[primary_id] = identifier[authorization_id] , identifier[equivalent_id] = identifier[alias_... | def alias_authorization(self, authorization_id, alias_id):
"""Adds an ``Id`` to an ``Authorization`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Authorization`` is determined by the
provider. The new ``Id`` performs as an alias to the primary
``Id``. If the alias ... |
def update_internal_networks(self, network_uri_list, force=False, timeout=-1):
"""
Updates internal networks on the logical interconnect.
Args:
network_uri_list: List of Ethernet network uris.
force: If set to true, the operation completes despite any problems with netwo... | def function[update_internal_networks, parameter[self, network_uri_list, force, timeout]]:
constant[
Updates internal networks on the logical interconnect.
Args:
network_uri_list: List of Ethernet network uris.
force: If set to true, the operation completes despite any p... | keyword[def] identifier[update_internal_networks] ( identifier[self] , identifier[network_uri_list] , identifier[force] = keyword[False] , identifier[timeout] =- literal[int] ):
literal[string]
identifier[uri] = literal[string] . identifier[format] ( identifier[self] . identifier[data] [ literal[st... | def update_internal_networks(self, network_uri_list, force=False, timeout=-1):
"""
Updates internal networks on the logical interconnect.
Args:
network_uri_list: List of Ethernet network uris.
force: If set to true, the operation completes despite any problems with network c... |
def MultiOpenOrdered(self, urns, **kwargs):
"""Opens many URNs and returns handles in the same order.
`MultiOpen` can return file handles in arbitrary order. This makes it more
efficient and in most cases the order does not matter. However, there are
cases where order is important and this function sho... | def function[MultiOpenOrdered, parameter[self, urns]]:
constant[Opens many URNs and returns handles in the same order.
`MultiOpen` can return file handles in arbitrary order. This makes it more
efficient and in most cases the order does not matter. However, there are
cases where order is important ... | keyword[def] identifier[MultiOpenOrdered] ( identifier[self] , identifier[urns] ,** identifier[kwargs] ):
literal[string]
identifier[precondition] . identifier[AssertIterableType] ( identifier[urns] , identifier[rdfvalue] . identifier[RDFURN] )
identifier[urn_filedescs] ={}
keyword[for] identif... | def MultiOpenOrdered(self, urns, **kwargs):
"""Opens many URNs and returns handles in the same order.
`MultiOpen` can return file handles in arbitrary order. This makes it more
efficient and in most cases the order does not matter. However, there are
cases where order is important and this function sho... |
def schedule_snapshot(self, format):
"""
Tell the canvas to perform a snapshot when it's finished rendering
:param format:
:return:
"""
bot = self.bot
canvas = self.bot.canvas
script = bot._namespace['__file__']
if script:
filename = os... | def function[schedule_snapshot, parameter[self, format]]:
constant[
Tell the canvas to perform a snapshot when it's finished rendering
:param format:
:return:
]
variable[bot] assign[=] name[self].bot
variable[canvas] assign[=] name[self].bot.canvas
variabl... | keyword[def] identifier[schedule_snapshot] ( identifier[self] , identifier[format] ):
literal[string]
identifier[bot] = identifier[self] . identifier[bot]
identifier[canvas] = identifier[self] . identifier[bot] . identifier[canvas]
identifier[script] = identifier[bot] . identifi... | def schedule_snapshot(self, format):
"""
Tell the canvas to perform a snapshot when it's finished rendering
:param format:
:return:
"""
bot = self.bot
canvas = self.bot.canvas
script = bot._namespace['__file__']
if script:
filename = os.path.splitext(script)[0... |
def mouseMoveEvent(self, event):
""" Handle the mouse move event for a drag operation.
"""
#if event.buttons() & Qt.LeftButton and self._drag_origin is not None:
#dist = (event.pos() - self._drag_origin).manhattanLength()
#if dist >= QApplication.startDragDistance():
... | def function[mouseMoveEvent, parameter[self, event]]:
constant[ Handle the mouse move event for a drag operation.
]
variable[widget] assign[=] name[self].widget
call[call[name[type], parameter[name[widget]]].mouseMoveEvent, parameter[name[widget], name[event]]] | keyword[def] identifier[mouseMoveEvent] ( identifier[self] , identifier[event] ):
literal[string]
identifier[widget] = identifier[self] . identifier[widget]
identifier[type] ( identifier[widget] ). identifier[mouseMoveEvent] ( identifi... | def mouseMoveEvent(self, event):
""" Handle the mouse move event for a drag operation.
"""
#if event.buttons() & Qt.LeftButton and self._drag_origin is not None:
#dist = (event.pos() - self._drag_origin).manhattanLength()
#if dist >= QApplication.startDragDistance():
#self.do_drag(event.wid... |
def partition_zero(max_range, max_sum, out = None, n_part = None):
'''
Function that can be helpful for obtaining the state space of a discrete Markov chain or Markov decision processes.
Returns a 2d-array with on the rows all possible partitions of the ranges `0,...,max_range[j]` that add up to at most `m... | def function[partition_zero, parameter[max_range, max_sum, out, n_part]]:
constant[
Function that can be helpful for obtaining the state space of a discrete Markov chain or Markov decision processes.
Returns a 2d-array with on the rows all possible partitions of the ranges `0,...,max_range[j]` that add... | keyword[def] identifier[partition_zero] ( identifier[max_range] , identifier[max_sum] , identifier[out] = keyword[None] , identifier[n_part] = keyword[None] ):
literal[string]
keyword[if] identifier[out] keyword[is] keyword[None] :
identifier[max_range] = identifier[np] . identifier[asarray] ( ... | def partition_zero(max_range, max_sum, out=None, n_part=None):
"""
Function that can be helpful for obtaining the state space of a discrete Markov chain or Markov decision processes.
Returns a 2d-array with on the rows all possible partitions of the ranges `0,...,max_range[j]` that add up to at most `max_s... |
def download(date_array, tag, sat_id, data_path, user=None, password=None):
"""
Download SuperDARN data from Virginia Tech organized for loading by pysat.
"""
import sys
import os
import pysftp
import davitpy
if user is None:
user = os.environ['DBREADUSER']
if password... | def function[download, parameter[date_array, tag, sat_id, data_path, user, password]]:
constant[
Download SuperDARN data from Virginia Tech organized for loading by pysat.
]
import module[sys]
import module[os]
import module[pysftp]
import module[davitpy]
if compare[name[user] i... | keyword[def] identifier[download] ( identifier[date_array] , identifier[tag] , identifier[sat_id] , identifier[data_path] , identifier[user] = keyword[None] , identifier[password] = keyword[None] ):
literal[string]
keyword[import] identifier[sys]
keyword[import] identifier[os]
keyword[import... | def download(date_array, tag, sat_id, data_path, user=None, password=None):
"""
Download SuperDARN data from Virginia Tech organized for loading by pysat.
"""
import sys
import os
import pysftp
import davitpy
if user is None:
user = os.environ['DBREADUSER'] # depends on [contro... |
def vxi_command_query(library, session, mode, command):
"""Sends the device a miscellaneous command or query and/or retrieves the response to a previous query.
Corresponds to viVxiCommandQuery function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logi... | def function[vxi_command_query, parameter[library, session, mode, command]]:
constant[Sends the device a miscellaneous command or query and/or retrieves the response to a previous query.
Corresponds to viVxiCommandQuery function of the VISA library.
:param library: the visa library wrapped by ctypes.
... | keyword[def] identifier[vxi_command_query] ( identifier[library] , identifier[session] , identifier[mode] , identifier[command] ):
literal[string]
identifier[response] = identifier[ViUInt32] ()
identifier[ret] = identifier[library] . identifier[viVxiCommandQuery] ( identifier[session] , identifier[mod... | def vxi_command_query(library, session, mode, command):
"""Sends the device a miscellaneous command or query and/or retrieves the response to a previous query.
Corresponds to viVxiCommandQuery function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logi... |
def createReport(tm, options, sequenceString, numSegments, numSynapses):
"""
Create CSV file with detailed trace of predictions, missed predictions,
accuracy, segment/synapse growth, etc.
"""
pac = tm.mmGetTracePredictedActiveColumns()
pic = tm.mmGetTracePredictedInactiveColumns()
upac = tm.mmGetTraceUnpr... | def function[createReport, parameter[tm, options, sequenceString, numSegments, numSynapses]]:
constant[
Create CSV file with detailed trace of predictions, missed predictions,
accuracy, segment/synapse growth, etc.
]
variable[pac] assign[=] call[name[tm].mmGetTracePredictedActiveColumns, parameter... | keyword[def] identifier[createReport] ( identifier[tm] , identifier[options] , identifier[sequenceString] , identifier[numSegments] , identifier[numSynapses] ):
literal[string]
identifier[pac] = identifier[tm] . identifier[mmGetTracePredictedActiveColumns] ()
identifier[pic] = identifier[tm] . identifier[mm... | def createReport(tm, options, sequenceString, numSegments, numSynapses):
"""
Create CSV file with detailed trace of predictions, missed predictions,
accuracy, segment/synapse growth, etc.
"""
pac = tm.mmGetTracePredictedActiveColumns()
pic = tm.mmGetTracePredictedInactiveColumns()
upac = tm.mmGetT... |
def select_where(self, where_col_list, where_value_list, col_name=''):
"""
selects rows from the array where col_list == val_list
"""
res = [] # list of rows to be returned
col_ids = [] # ids of the columns to check
#print('select_where : arr = ', len(self.ar... | def function[select_where, parameter[self, where_col_list, where_value_list, col_name]]:
constant[
selects rows from the array where col_list == val_list
]
variable[res] assign[=] list[[]]
variable[col_ids] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da20e... | keyword[def] identifier[select_where] ( identifier[self] , identifier[where_col_list] , identifier[where_value_list] , identifier[col_name] = literal[string] ):
literal[string]
identifier[res] =[]
identifier[col_ids] =[]
keyword[for] identifier[col_id] , identifier[col] ... | def select_where(self, where_col_list, where_value_list, col_name=''):
"""
selects rows from the array where col_list == val_list
"""
res = [] # list of rows to be returned
col_ids = [] # ids of the columns to check
#print('select_where : arr = ', len(self.arr), 'where_value_list = ... |
def rhyming_part(phones):
"""Get the "rhyming part" of a string with CMUdict phones.
"Rhyming part" here means everything from the vowel in the stressed
syllable nearest the end of the word up to the end of the word.
.. doctest::
>>> import pronouncing
>>> phones = pronouncing.phones_... | def function[rhyming_part, parameter[phones]]:
constant[Get the "rhyming part" of a string with CMUdict phones.
"Rhyming part" here means everything from the vowel in the stressed
syllable nearest the end of the word up to the end of the word.
.. doctest::
>>> import pronouncing
>... | keyword[def] identifier[rhyming_part] ( identifier[phones] ):
literal[string]
identifier[phones_list] = identifier[phones] . identifier[split] ()
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[len] ( identifier[phones_list] )- literal[int] , literal[int] ,- literal[int] ):
... | def rhyming_part(phones):
"""Get the "rhyming part" of a string with CMUdict phones.
"Rhyming part" here means everything from the vowel in the stressed
syllable nearest the end of the word up to the end of the word.
.. doctest::
>>> import pronouncing
>>> phones = pronouncing.phones_... |
def index(self, value: Any) -> int:
"""
Returns the index in the handlers list
that matches the given value.
If no condition matches, ValueError is raised.
"""
for i, cond in ((j[0], j[1][0]) for j in enumerate(self.handlers)):
try:
match = co... | def function[index, parameter[self, value]]:
constant[
Returns the index in the handlers list
that matches the given value.
If no condition matches, ValueError is raised.
]
for taget[tuple[[<ast.Name object at 0x7da2041d8520>, <ast.Name object at 0x7da20c993c70>]]] in st... | keyword[def] identifier[index] ( identifier[self] , identifier[value] : identifier[Any] )-> identifier[int] :
literal[string]
keyword[for] identifier[i] , identifier[cond] keyword[in] (( identifier[j] [ literal[int] ], identifier[j] [ literal[int] ][ literal[int] ]) keyword[for] identifier[j] k... | def index(self, value: Any) -> int:
"""
Returns the index in the handlers list
that matches the given value.
If no condition matches, ValueError is raised.
"""
for (i, cond) in ((j[0], j[1][0]) for j in enumerate(self.handlers)):
try:
match = cond(value) # d... |
def record(self, ch_node):
'''
Incremental changes
'''
rec = self.serialize_node(ch_node)
self.history.append(rec) | def function[record, parameter[self, ch_node]]:
constant[
Incremental changes
]
variable[rec] assign[=] call[name[self].serialize_node, parameter[name[ch_node]]]
call[name[self].history.append, parameter[name[rec]]] | keyword[def] identifier[record] ( identifier[self] , identifier[ch_node] ):
literal[string]
identifier[rec] = identifier[self] . identifier[serialize_node] ( identifier[ch_node] )
identifier[self] . identifier[history] . identifier[append] ( identifier[rec] ) | def record(self, ch_node):
"""
Incremental changes
"""
rec = self.serialize_node(ch_node)
self.history.append(rec) |
def content_type(self):
"""
Returns the content type of the request in all cases where it is
different than a submitted form - application/x-www-form-urlencoded
"""
type_formencoded = "application/x-www-form-urlencoded"
ctype = self.request.META.get('CONTENT_TYPE', type_... | def function[content_type, parameter[self]]:
constant[
Returns the content type of the request in all cases where it is
different than a submitted form - application/x-www-form-urlencoded
]
variable[type_formencoded] assign[=] constant[application/x-www-form-urlencoded]
v... | keyword[def] identifier[content_type] ( identifier[self] ):
literal[string]
identifier[type_formencoded] = literal[string]
identifier[ctype] = identifier[self] . identifier[request] . identifier[META] . identifier[get] ( literal[string] , identifier[type_formencoded] )
keyword[... | def content_type(self):
"""
Returns the content type of the request in all cases where it is
different than a submitted form - application/x-www-form-urlencoded
"""
type_formencoded = 'application/x-www-form-urlencoded'
ctype = self.request.META.get('CONTENT_TYPE', type_formencoded)
... |
def construct_pdb_to_rosetta_residue_map(self, rosetta_scripts_path, rosetta_database_path = None, extra_command_flags = None, cache_dir = None):
''' Uses the features database to create a mapping from Rosetta-numbered residues to PDB ATOM residues.
Next, the object's rosetta_sequences (a dict of Se... | def function[construct_pdb_to_rosetta_residue_map, parameter[self, rosetta_scripts_path, rosetta_database_path, extra_command_flags, cache_dir]]:
constant[ Uses the features database to create a mapping from Rosetta-numbered residues to PDB ATOM residues.
Next, the object's rosetta_sequences (a dict... | keyword[def] identifier[construct_pdb_to_rosetta_residue_map] ( identifier[self] , identifier[rosetta_scripts_path] , identifier[rosetta_database_path] = keyword[None] , identifier[extra_command_flags] = keyword[None] , identifier[cache_dir] = keyword[None] ):
literal[string]
keyword[imp... | def construct_pdb_to_rosetta_residue_map(self, rosetta_scripts_path, rosetta_database_path=None, extra_command_flags=None, cache_dir=None):
""" Uses the features database to create a mapping from Rosetta-numbered residues to PDB ATOM residues.
Next, the object's rosetta_sequences (a dict of Sequences) e... |
def find(self, selector: str = "*", *, containing: _Containing = None, clean: bool = False, first: bool = False, _encoding: str = None) -> _Find:
"""Given a CSS Selector, returns a list of
:class:`Element <Element>` objects or a single one.
:param selector: CSS Selector to use.
:param c... | def function[find, parameter[self, selector]]:
constant[Given a CSS Selector, returns a list of
:class:`Element <Element>` objects or a single one.
:param selector: CSS Selector to use.
:param clean: Whether or not to sanitize the found HTML of ``<script>`` and ``<style>`` tags.
... | keyword[def] identifier[find] ( identifier[self] , identifier[selector] : identifier[str] = literal[string] ,*, identifier[containing] : identifier[_Containing] = keyword[None] , identifier[clean] : identifier[bool] = keyword[False] , identifier[first] : identifier[bool] = keyword[False] , identifier[_encoding] : ide... | def find(self, selector: str='*', *, containing: _Containing=None, clean: bool=False, first: bool=False, _encoding: str=None) -> _Find:
"""Given a CSS Selector, returns a list of
:class:`Element <Element>` objects or a single one.
:param selector: CSS Selector to use.
:param clean: Whether ... |
def copyData(self, source):
"""
Subclasses may override this method.
If so, they should call the super.
"""
for attr in self.copyAttributes:
selfValue = getattr(self, attr)
sourceValue = getattr(source, attr)
if isinstance(selfValue, BaseObject... | def function[copyData, parameter[self, source]]:
constant[
Subclasses may override this method.
If so, they should call the super.
]
for taget[name[attr]] in starred[name[self].copyAttributes] begin[:]
variable[selfValue] assign[=] call[name[getattr], parameter[na... | keyword[def] identifier[copyData] ( identifier[self] , identifier[source] ):
literal[string]
keyword[for] identifier[attr] keyword[in] identifier[self] . identifier[copyAttributes] :
identifier[selfValue] = identifier[getattr] ( identifier[self] , identifier[attr] )
ide... | def copyData(self, source):
"""
Subclasses may override this method.
If so, they should call the super.
"""
for attr in self.copyAttributes:
selfValue = getattr(self, attr)
sourceValue = getattr(source, attr)
if isinstance(selfValue, BaseObject):
selfV... |
def error(msg: str, resource: Optional['Resource'] = None, stream_id: Optional[int] = None):
"""
Logs a message to the Pulumi CLI's error channel, associating it with a resource
and stream_id if provided.
:param str msg: The message to send to the Pulumi CLI.
:param Optional[Resource] resource: If ... | def function[error, parameter[msg, resource, stream_id]]:
constant[
Logs a message to the Pulumi CLI's error channel, associating it with a resource
and stream_id if provided.
:param str msg: The message to send to the Pulumi CLI.
:param Optional[Resource] resource: If provided, associate this ... | keyword[def] identifier[error] ( identifier[msg] : identifier[str] , identifier[resource] : identifier[Optional] [ literal[string] ]= keyword[None] , identifier[stream_id] : identifier[Optional] [ identifier[int] ]= keyword[None] ):
literal[string]
identifier[engine] = identifier[get_engine] ()
keywor... | def error(msg: str, resource: Optional['Resource']=None, stream_id: Optional[int]=None):
"""
Logs a message to the Pulumi CLI's error channel, associating it with a resource
and stream_id if provided.
:param str msg: The message to send to the Pulumi CLI.
:param Optional[Resource] resource: If prov... |
def is_netcdf(url):
'''
Returns True if the URL points to a valid local netCDF file
:param str url: Location of file on the file system
'''
# Try an obvious exclusion of remote resources
if url.startswith('http'):
return False
# If it's a known extension, give it a shot
if url.... | def function[is_netcdf, parameter[url]]:
constant[
Returns True if the URL points to a valid local netCDF file
:param str url: Location of file on the file system
]
if call[name[url].startswith, parameter[constant[http]]] begin[:]
return[constant[False]]
if call[name[url].en... | keyword[def] identifier[is_netcdf] ( identifier[url] ):
literal[string]
keyword[if] identifier[url] . identifier[startswith] ( literal[string] ):
keyword[return] keyword[False]
keyword[if] identifier[url] . identifier[endswith] ( literal[string] ):
keyword[return] ... | def is_netcdf(url):
"""
Returns True if the URL points to a valid local netCDF file
:param str url: Location of file on the file system
"""
# Try an obvious exclusion of remote resources
if url.startswith('http'):
return False # depends on [control=['if'], data=[]]
# If it's a know... |
def directory_generator(dirname, trim=0):
"""
yields a tuple of (relative filename, chunking function). The
chunking function can be called to open and iterate over the
contents of the filename.
"""
def gather(collect, dirname, fnames):
for fname in fnames:
df = join(dirname... | def function[directory_generator, parameter[dirname, trim]]:
constant[
yields a tuple of (relative filename, chunking function). The
chunking function can be called to open and iterate over the
contents of the filename.
]
def function[gather, parameter[collect, dirname, fnames]]:
... | keyword[def] identifier[directory_generator] ( identifier[dirname] , identifier[trim] = literal[int] ):
literal[string]
keyword[def] identifier[gather] ( identifier[collect] , identifier[dirname] , identifier[fnames] ):
keyword[for] identifier[fname] keyword[in] identifier[fnames] :
... | def directory_generator(dirname, trim=0):
"""
yields a tuple of (relative filename, chunking function). The
chunking function can be called to open and iterate over the
contents of the filename.
"""
def gather(collect, dirname, fnames):
for fname in fnames:
df = join(dirname... |
def tocimxml(self, ignore_path=False):
"""
Return the CIM-XML representation of this CIM instance,
as an object of an appropriate subclass of :term:`Element`.
If the instance has no instance path specified or if `ignore_path` is
`True`, the returned CIM-XML representation is an ... | def function[tocimxml, parameter[self, ignore_path]]:
constant[
Return the CIM-XML representation of this CIM instance,
as an object of an appropriate subclass of :term:`Element`.
If the instance has no instance path specified or if `ignore_path` is
`True`, the returned CIM-XML ... | keyword[def] identifier[tocimxml] ( identifier[self] , identifier[ignore_path] = keyword[False] ):
literal[string]
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[... | def tocimxml(self, ignore_path=False):
"""
Return the CIM-XML representation of this CIM instance,
as an object of an appropriate subclass of :term:`Element`.
If the instance has no instance path specified or if `ignore_path` is
`True`, the returned CIM-XML representation is an `INS... |
def increment(self, amount=1, output=True):
"""Increment progress by a given amount (defaults to 1) and (optionally) output the progress
status.
"""
self._current += amount
if output:
# NOTE: This algorithm averages out the time it has taken to get to the current / total to
# deter... | def function[increment, parameter[self, amount, output]]:
constant[Increment progress by a given amount (defaults to 1) and (optionally) output the progress
status.
]
<ast.AugAssign object at 0x7da1b13650f0>
if name[output] begin[:]
variable[now] assign[=] call[name[datetime]... | keyword[def] identifier[increment] ( identifier[self] , identifier[amount] = literal[int] , identifier[output] = keyword[True] ):
literal[string]
identifier[self] . identifier[_current] += identifier[amount]
keyword[if] identifier[output] :
identifier[now] = identifier[datetim... | def increment(self, amount=1, output=True):
"""Increment progress by a given amount (defaults to 1) and (optionally) output the progress
status.
"""
self._current += amount
if output:
# NOTE: This algorithm averages out the time it has taken to get to the current / total to
# d... |
def _fill_role_cache_batch(self, principals, overwrite=False):
"""Fill role cache for `principals` (Users and/or Groups), in order to
avoid too many queries when checking role access with 'has_role'."""
if not self.app_state.use_cache:
return
query = db.session.query(RoleAss... | def function[_fill_role_cache_batch, parameter[self, principals, overwrite]]:
constant[Fill role cache for `principals` (Users and/or Groups), in order to
avoid too many queries when checking role access with 'has_role'.]
if <ast.UnaryOp object at 0x7da1b196f610> begin[:]
return[None]
... | keyword[def] identifier[_fill_role_cache_batch] ( identifier[self] , identifier[principals] , identifier[overwrite] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[app_state] . identifier[use_cache] :
keyword[return]
identifier[qu... | def _fill_role_cache_batch(self, principals, overwrite=False):
"""Fill role cache for `principals` (Users and/or Groups), in order to
avoid too many queries when checking role access with 'has_role'."""
if not self.app_state.use_cache:
return # depends on [control=['if'], data=[]]
query = d... |
def handle_common_arguments(parsed_args):
"""
Handles the arguments defined by :meth:`~make_common_parser`
:param parsed_args: Argument parsed with ``argparse`` (``Namespace``)
:return: An :class:`~InitFileHandler` object
:raise IOError: Initial or run script not found
"""
# Setup the logge... | def function[handle_common_arguments, parameter[parsed_args]]:
constant[
Handles the arguments defined by :meth:`~make_common_parser`
:param parsed_args: Argument parsed with ``argparse`` (``Namespace``)
:return: An :class:`~InitFileHandler` object
:raise IOError: Initial or run script not foun... | keyword[def] identifier[handle_common_arguments] ( identifier[parsed_args] ):
literal[string]
identifier[logging] . identifier[basicConfig] (
identifier[level] = identifier[logging] . identifier[DEBUG] keyword[if] identifier[parsed_args] . identifier[verbose] keyword[else] identifier[logging]... | def handle_common_arguments(parsed_args):
"""
Handles the arguments defined by :meth:`~make_common_parser`
:param parsed_args: Argument parsed with ``argparse`` (``Namespace``)
:return: An :class:`~InitFileHandler` object
:raise IOError: Initial or run script not found
"""
# Setup the logge... |
def load(self, optional_cfg_files=None):
""" Actually load the configuation from either the default location or the given directory.
"""
optional_cfg_files = optional_cfg_files or []
# Guard against coding errors
if self._loaded:
raise RuntimeError("INTERNAL ERROR: A... | def function[load, parameter[self, optional_cfg_files]]:
constant[ Actually load the configuation from either the default location or the given directory.
]
variable[optional_cfg_files] assign[=] <ast.BoolOp object at 0x7da1b135bf70>
if name[self]._loaded begin[:]
<ast.Raise obje... | keyword[def] identifier[load] ( identifier[self] , identifier[optional_cfg_files] = keyword[None] ):
literal[string]
identifier[optional_cfg_files] = identifier[optional_cfg_files] keyword[or] []
keyword[if] identifier[self] . identifier[_loaded] :
keyword[raise] ... | def load(self, optional_cfg_files=None):
""" Actually load the configuation from either the default location or the given directory.
"""
optional_cfg_files = optional_cfg_files or []
# Guard against coding errors
if self._loaded:
raise RuntimeError('INTERNAL ERROR: Attempt to load config... |
def remove_event_subscriber(self, name, ws):
"""
Remove a websocket subscriber from an event.
name -- name of the event
ws -- the websocket
"""
if name in self.available_events and \
ws in self.available_events[name]['subscribers']:
self.avail... | def function[remove_event_subscriber, parameter[self, name, ws]]:
constant[
Remove a websocket subscriber from an event.
name -- name of the event
ws -- the websocket
]
if <ast.BoolOp object at 0x7da1b0338d30> begin[:]
call[call[call[name[self].available_... | keyword[def] identifier[remove_event_subscriber] ( identifier[self] , identifier[name] , identifier[ws] ):
literal[string]
keyword[if] identifier[name] keyword[in] identifier[self] . identifier[available_events] keyword[and] identifier[ws] keyword[in] identifier[self] . identifier[available_... | def remove_event_subscriber(self, name, ws):
"""
Remove a websocket subscriber from an event.
name -- name of the event
ws -- the websocket
"""
if name in self.available_events and ws in self.available_events[name]['subscribers']:
self.available_events[name]['subscribers... |
def __extract_modules(self, loader, name, is_pkg):
""" if module found load module and save all attributes in the module found """
mod = loader.find_module(name).load_module(name)
""" find the attribute method on each module """
if hasattr(mod, '__method__'):
""" register ... | def function[__extract_modules, parameter[self, loader, name, is_pkg]]:
constant[ if module found load module and save all attributes in the module found ]
variable[mod] assign[=] call[call[name[loader].find_module, parameter[name[name]]].load_module, parameter[name[name]]]
constant[ find the at... | keyword[def] identifier[__extract_modules] ( identifier[self] , identifier[loader] , identifier[name] , identifier[is_pkg] ):
literal[string]
identifier[mod] = identifier[loader] . identifier[find_module] ( identifier[name] ). identifier[load_module] ( identifier[name] )
literal[string] ... | def __extract_modules(self, loader, name, is_pkg):
""" if module found load module and save all attributes in the module found """
mod = loader.find_module(name).load_module(name)
' find the attribute method on each module '
if hasattr(mod, '__method__'):
' register to the blueprint if method at... |
def _interp(self):
"""Interpolate the cartesian coordinates.
"""
if np.all(self.hrow_indices == self.row_indices):
return self._interp1d()
xpoints, ypoints = np.meshgrid(self.hrow_indices,
self.hcol_indices)
for num, data in en... | def function[_interp, parameter[self]]:
constant[Interpolate the cartesian coordinates.
]
if call[name[np].all, parameter[compare[name[self].hrow_indices equal[==] name[self].row_indices]]] begin[:]
return[call[name[self]._interp1d, parameter[]]]
<ast.Tuple object at 0x7da1b1c7d7... | keyword[def] identifier[_interp] ( identifier[self] ):
literal[string]
keyword[if] identifier[np] . identifier[all] ( identifier[self] . identifier[hrow_indices] == identifier[self] . identifier[row_indices] ):
keyword[return] identifier[self] . identifier[_interp1d] ()
ide... | def _interp(self):
"""Interpolate the cartesian coordinates.
"""
if np.all(self.hrow_indices == self.row_indices):
return self._interp1d() # depends on [control=['if'], data=[]]
(xpoints, ypoints) = np.meshgrid(self.hrow_indices, self.hcol_indices)
for (num, data) in enumerate(self.tie_... |
def enter(self, screen_id, y, x, default_action, allowed_actions, formats):
"""Informs the target about a drag and drop enter event.
in screen_id of type int
The screen ID where the drag and drop event occurred.
in y of type int
Y-position of the event.
in x of... | def function[enter, parameter[self, screen_id, y, x, default_action, allowed_actions, formats]]:
constant[Informs the target about a drag and drop enter event.
in screen_id of type int
The screen ID where the drag and drop event occurred.
in y of type int
Y-position of ... | keyword[def] identifier[enter] ( identifier[self] , identifier[screen_id] , identifier[y] , identifier[x] , identifier[default_action] , identifier[allowed_actions] , identifier[formats] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[screen_id] , identifier[basein... | def enter(self, screen_id, y, x, default_action, allowed_actions, formats):
"""Informs the target about a drag and drop enter event.
in screen_id of type int
The screen ID where the drag and drop event occurred.
in y of type int
Y-position of the event.
in x of typ... |
def dump_rexobj_results(rexobj, options=None):
'''
print all the results.
'''
print("-" * 60)
print("Match count: ", rexobj.res_count)
matches = rexobj.matches
for match in matches:
print("Loc:", match.loc, ":: ")
for key in match.named_groups.keys():
print("%s: %... | def function[dump_rexobj_results, parameter[rexobj, options]]:
constant[
print all the results.
]
call[name[print], parameter[binary_operation[constant[-] * constant[60]]]]
call[name[print], parameter[constant[Match count: ], name[rexobj].res_count]]
variable[matches] assign[=] n... | keyword[def] identifier[dump_rexobj_results] ( identifier[rexobj] , identifier[options] = keyword[None] ):
literal[string]
identifier[print] ( literal[string] * literal[int] )
identifier[print] ( literal[string] , identifier[rexobj] . identifier[res_count] )
identifier[matches] = identifier[rexob... | def dump_rexobj_results(rexobj, options=None):
"""
print all the results.
"""
print('-' * 60)
print('Match count: ', rexobj.res_count)
matches = rexobj.matches
for match in matches:
print('Loc:', match.loc, ':: ')
for key in match.named_groups.keys():
print('%s: %... |
def get_samples(in_file):
"""Retrieve samples present in a VCF file
"""
with utils.open_gzipsafe(in_file) as in_handle:
for line in in_handle:
if line.startswith("#CHROM"):
parts = line.strip().split("\t")
return parts[9:]
raise ValueError("Did not fin... | def function[get_samples, parameter[in_file]]:
constant[Retrieve samples present in a VCF file
]
with call[name[utils].open_gzipsafe, parameter[name[in_file]]] begin[:]
for taget[name[line]] in starred[name[in_handle]] begin[:]
if call[name[line].startswith, p... | keyword[def] identifier[get_samples] ( identifier[in_file] ):
literal[string]
keyword[with] identifier[utils] . identifier[open_gzipsafe] ( identifier[in_file] ) keyword[as] identifier[in_handle] :
keyword[for] identifier[line] keyword[in] identifier[in_handle] :
keyword[if] ide... | def get_samples(in_file):
"""Retrieve samples present in a VCF file
"""
with utils.open_gzipsafe(in_file) as in_handle:
for line in in_handle:
if line.startswith('#CHROM'):
parts = line.strip().split('\t')
return parts[9:] # depends on [control=['if'], da... |
def _update_function_transition_graph(self, src_node_key, dst_node_key, jumpkind='Ijk_Boring', ins_addr=None,
stmt_idx=None, confirmed=None):
"""
Update transition graphs of functions in function manager based on information passed in.
:param str jumpki... | def function[_update_function_transition_graph, parameter[self, src_node_key, dst_node_key, jumpkind, ins_addr, stmt_idx, confirmed]]:
constant[
Update transition graphs of functions in function manager based on information passed in.
:param str jumpkind: Jumpkind.
:param CFGNode src_no... | keyword[def] identifier[_update_function_transition_graph] ( identifier[self] , identifier[src_node_key] , identifier[dst_node_key] , identifier[jumpkind] = literal[string] , identifier[ins_addr] = keyword[None] ,
identifier[stmt_idx] = keyword[None] , identifier[confirmed] = keyword[None] ):
literal[string... | def _update_function_transition_graph(self, src_node_key, dst_node_key, jumpkind='Ijk_Boring', ins_addr=None, stmt_idx=None, confirmed=None):
"""
Update transition graphs of functions in function manager based on information passed in.
:param str jumpkind: Jumpkind.
:param CFGNode src_node:... |
def console_output(self, instance=None):
"""Yields the output and metadata from all jobs in the pipeline
Args:
instance: The result of a :meth:`instance` call, if not supplied
the latest of the pipeline will be used.
Yields:
tuple: (metadata (dict), output (str)... | def function[console_output, parameter[self, instance]]:
constant[Yields the output and metadata from all jobs in the pipeline
Args:
instance: The result of a :meth:`instance` call, if not supplied
the latest of the pipeline will be used.
Yields:
tuple: (metadat... | keyword[def] identifier[console_output] ( identifier[self] , identifier[instance] = keyword[None] ):
literal[string]
keyword[if] identifier[instance] keyword[is] keyword[None] :
identifier[instance] = identifier[self] . identifier[instance] ()
keyword[for] identifier[stag... | def console_output(self, instance=None):
"""Yields the output and metadata from all jobs in the pipeline
Args:
instance: The result of a :meth:`instance` call, if not supplied
the latest of the pipeline will be used.
Yields:
tuple: (metadata (dict), output (str)).
... |
def _scaleSinglePoint(point, scale=1, convertToInteger=True):
"""
Scale a single point
"""
x, y = point
if convertToInteger:
return int(round(x * scale)), int(round(y * scale))
else:
return (x * scale, y * scale) | def function[_scaleSinglePoint, parameter[point, scale, convertToInteger]]:
constant[
Scale a single point
]
<ast.Tuple object at 0x7da1b0f3a200> assign[=] name[point]
if name[convertToInteger] begin[:]
return[tuple[[<ast.Call object at 0x7da1b0f3ad10>, <ast.Call object at 0x7da1... | keyword[def] identifier[_scaleSinglePoint] ( identifier[point] , identifier[scale] = literal[int] , identifier[convertToInteger] = keyword[True] ):
literal[string]
identifier[x] , identifier[y] = identifier[point]
keyword[if] identifier[convertToInteger] :
keyword[return] identifier[int] (... | def _scaleSinglePoint(point, scale=1, convertToInteger=True):
"""
Scale a single point
"""
(x, y) = point
if convertToInteger:
return (int(round(x * scale)), int(round(y * scale))) # depends on [control=['if'], data=[]]
else:
return (x * scale, y * scale) |
def query(self, coords, mode='random_sample'):
"""
Returns A0 at the given coordinates. There are several different query
modes, which handle the probabilistic nature of the map differently.
Args:
coords (:obj:`astropy.coordinates.SkyCoord`): The coordinates to query.
... | def function[query, parameter[self, coords, mode]]:
constant[
Returns A0 at the given coordinates. There are several different query
modes, which handle the probabilistic nature of the map differently.
Args:
coords (:obj:`astropy.coordinates.SkyCoord`): The coordinates to qu... | keyword[def] identifier[query] ( identifier[self] , identifier[coords] , identifier[mode] = literal[string] ):
literal[string]
identifier[valid_modes] =[
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ]
... | def query(self, coords, mode='random_sample'):
"""
Returns A0 at the given coordinates. There are several different query
modes, which handle the probabilistic nature of the map differently.
Args:
coords (:obj:`astropy.coordinates.SkyCoord`): The coordinates to query.
... |
def group_nodes_by_annotation(graph: BELGraph, annotation: str = 'Subgraph') -> Mapping[str, Set[BaseEntity]]:
"""Group the nodes occurring in edges by the given annotation."""
result = defaultdict(set)
for u, v, d in graph.edges(data=True):
if not edge_has_annotation(d, annotation):
co... | def function[group_nodes_by_annotation, parameter[graph, annotation]]:
constant[Group the nodes occurring in edges by the given annotation.]
variable[result] assign[=] call[name[defaultdict], parameter[name[set]]]
for taget[tuple[[<ast.Name object at 0x7da18f810880>, <ast.Name object at 0x7da18f... | keyword[def] identifier[group_nodes_by_annotation] ( identifier[graph] : identifier[BELGraph] , identifier[annotation] : identifier[str] = literal[string] )-> identifier[Mapping] [ identifier[str] , identifier[Set] [ identifier[BaseEntity] ]]:
literal[string]
identifier[result] = identifier[defaultdict] ( ... | def group_nodes_by_annotation(graph: BELGraph, annotation: str='Subgraph') -> Mapping[str, Set[BaseEntity]]:
"""Group the nodes occurring in edges by the given annotation."""
result = defaultdict(set)
for (u, v, d) in graph.edges(data=True):
if not edge_has_annotation(d, annotation):
con... |
def filter(self, table, domains, filter_string):
"""Naive case-insensitive search."""
q = filter_string.lower()
def comp(domain):
if q in domain.name.lower():
return True
return False
return filter(comp, domains) | def function[filter, parameter[self, table, domains, filter_string]]:
constant[Naive case-insensitive search.]
variable[q] assign[=] call[name[filter_string].lower, parameter[]]
def function[comp, parameter[domain]]:
if compare[name[q] in call[name[domain].name.lower, parameter[]... | keyword[def] identifier[filter] ( identifier[self] , identifier[table] , identifier[domains] , identifier[filter_string] ):
literal[string]
identifier[q] = identifier[filter_string] . identifier[lower] ()
keyword[def] identifier[comp] ( identifier[domain] ):
keyword[if] ide... | def filter(self, table, domains, filter_string):
"""Naive case-insensitive search."""
q = filter_string.lower()
def comp(domain):
if q in domain.name.lower():
return True # depends on [control=['if'], data=[]]
return False
return filter(comp, domains) |
def _check_enclosing_characters(string, opener, closer):
"""
Makes sure that the enclosing characters for a definition set make sense
1) There is only one set
2) They are in the right order (opening, then closing)
"""
opener_count = string.count(opener)
closer_count = string.count(closer)
... | def function[_check_enclosing_characters, parameter[string, opener, closer]]:
constant[
Makes sure that the enclosing characters for a definition set make sense
1) There is only one set
2) They are in the right order (opening, then closing)
]
variable[opener_count] assign[=] call[name[st... | keyword[def] identifier[_check_enclosing_characters] ( identifier[string] , identifier[opener] , identifier[closer] ):
literal[string]
identifier[opener_count] = identifier[string] . identifier[count] ( identifier[opener] )
identifier[closer_count] = identifier[string] . identifier[count] ( identifier... | def _check_enclosing_characters(string, opener, closer):
"""
Makes sure that the enclosing characters for a definition set make sense
1) There is only one set
2) They are in the right order (opening, then closing)
"""
opener_count = string.count(opener)
closer_count = string.count(closer)
... |
def sscan(self, key, cursor=0, pattern=None, count=None):
"""The :meth:`~tredis.RedisClient.sscan` command and the closely
related commands :meth:`~tredis.RedisClient.scan`,
:meth:`~tredis.RedisClient.hscan` and :meth:`~tredis.RedisClient.zscan`
are used in order to incrementally iterate... | def function[sscan, parameter[self, key, cursor, pattern, count]]:
constant[The :meth:`~tredis.RedisClient.sscan` command and the closely
related commands :meth:`~tredis.RedisClient.scan`,
:meth:`~tredis.RedisClient.hscan` and :meth:`~tredis.RedisClient.zscan`
are used in order to increm... | keyword[def] identifier[sscan] ( identifier[self] , identifier[key] , identifier[cursor] = literal[int] , identifier[pattern] = keyword[None] , identifier[count] = keyword[None] ):
literal[string]
keyword[def] identifier[format_response] ( identifier[value] ):
literal[string]
... | def sscan(self, key, cursor=0, pattern=None, count=None):
"""The :meth:`~tredis.RedisClient.sscan` command and the closely
related commands :meth:`~tredis.RedisClient.scan`,
:meth:`~tredis.RedisClient.hscan` and :meth:`~tredis.RedisClient.zscan`
are used in order to incrementally iterate ove... |
def _check_valid_version():
'''
Check the version of Bower to ensure this module will work. Currently
bower must be at least version 1.3.
'''
# pylint: disable=no-member
bower_version = _LooseVersion(
__salt__['cmd.run']('bower --version'))
valid_version = _LooseVersion('1.3')
# ... | def function[_check_valid_version, parameter[]]:
constant[
Check the version of Bower to ensure this module will work. Currently
bower must be at least version 1.3.
]
variable[bower_version] assign[=] call[name[_LooseVersion], parameter[call[call[name[__salt__]][constant[cmd.run]], parameter... | keyword[def] identifier[_check_valid_version] ():
literal[string]
identifier[bower_version] = identifier[_LooseVersion] (
identifier[__salt__] [ literal[string] ]( literal[string] ))
identifier[valid_version] = identifier[_LooseVersion] ( literal[string] )
keyword[if] identifier[b... | def _check_valid_version():
"""
Check the version of Bower to ensure this module will work. Currently
bower must be at least version 1.3.
"""
# pylint: disable=no-member
bower_version = _LooseVersion(__salt__['cmd.run']('bower --version'))
valid_version = _LooseVersion('1.3')
# pylint: e... |
def get_lines(data_nts, prtfmt=None, nt_fields=None, **kws):
"""Print list of namedtuples into a table using prtfmt."""
lines = []
# optional keyword args: prt_if sort_by
if prtfmt is None:
prtfmt = mk_fmtfld(data_nts[0], kws.get('joinchr', ' '), kws.get('eol', '\n'))
# if nt_fields arg is N... | def function[get_lines, parameter[data_nts, prtfmt, nt_fields]]:
constant[Print list of namedtuples into a table using prtfmt.]
variable[lines] assign[=] list[[]]
if compare[name[prtfmt] is constant[None]] begin[:]
variable[prtfmt] assign[=] call[name[mk_fmtfld], parameter[call[n... | keyword[def] identifier[get_lines] ( identifier[data_nts] , identifier[prtfmt] = keyword[None] , identifier[nt_fields] = keyword[None] ,** identifier[kws] ):
literal[string]
identifier[lines] =[]
keyword[if] identifier[prtfmt] keyword[is] keyword[None] :
identifier[prtfmt] = identifie... | def get_lines(data_nts, prtfmt=None, nt_fields=None, **kws):
"""Print list of namedtuples into a table using prtfmt."""
lines = []
# optional keyword args: prt_if sort_by
if prtfmt is None:
prtfmt = mk_fmtfld(data_nts[0], kws.get('joinchr', ' '), kws.get('eol', '\n')) # depends on [control=['if... |
def _parse_vagrant_sandbox_status(self, vagrant_output):
'''
Returns the status of the sandbox mode given output from
'vagrant sandbox status'.
'''
# typical output
# [default] - snapshot mode is off
# or
# [default] - machine not created
# if the ... | def function[_parse_vagrant_sandbox_status, parameter[self, vagrant_output]]:
constant[
Returns the status of the sandbox mode given output from
'vagrant sandbox status'.
]
variable[tokens] assign[=] <ast.ListComp object at 0x7da1b1a7df90>
if compare[call[name[tokens]][co... | keyword[def] identifier[_parse_vagrant_sandbox_status] ( identifier[self] , identifier[vagrant_output] ):
literal[string]
identifier[tokens] =[ identifier[token] . identifier[strip] () keyword[for] identifier[token] keyword[in] identifier[vagrant_outp... | def _parse_vagrant_sandbox_status(self, vagrant_output):
"""
Returns the status of the sandbox mode given output from
'vagrant sandbox status'.
"""
# typical output
# [default] - snapshot mode is off
# or
# [default] - machine not created
# if the box VM is down
token... |
def _parse_deaths(self, rows):
"""
Parses the character's recent deaths
Parameters
----------
rows: :class:`list` of :class:`bs4.Tag`
A list of all rows contained in the table.
"""
for row in rows:
cols = row.find_all('td')
dea... | def function[_parse_deaths, parameter[self, rows]]:
constant[
Parses the character's recent deaths
Parameters
----------
rows: :class:`list` of :class:`bs4.Tag`
A list of all rows contained in the table.
]
for taget[name[row]] in starred[name[rows]] b... | keyword[def] identifier[_parse_deaths] ( identifier[self] , identifier[rows] ):
literal[string]
keyword[for] identifier[row] keyword[in] identifier[rows] :
identifier[cols] = identifier[row] . identifier[find_all] ( literal[string] )
identifier[death_time_str] = identif... | def _parse_deaths(self, rows):
"""
Parses the character's recent deaths
Parameters
----------
rows: :class:`list` of :class:`bs4.Tag`
A list of all rows contained in the table.
"""
for row in rows:
cols = row.find_all('td')
death_time_str = co... |
def create(self, body=values.unset, priority=values.unset, ttl=values.unset,
title=values.unset, sound=values.unset, action=values.unset,
data=values.unset, apn=values.unset, gcm=values.unset,
sms=values.unset, facebook_messenger=values.unset, fcm=values.unset,
... | def function[create, parameter[self, body, priority, ttl, title, sound, action, data, apn, gcm, sms, facebook_messenger, fcm, segment, alexa, to_binding, identity, tag]]:
constant[
Create a new NotificationInstance
:param unicode body: The notification body text
:param NotificationInsta... | keyword[def] identifier[create] ( identifier[self] , identifier[body] = identifier[values] . identifier[unset] , identifier[priority] = identifier[values] . identifier[unset] , identifier[ttl] = identifier[values] . identifier[unset] ,
identifier[title] = identifier[values] . identifier[unset] , identifier[sound] = ... | def create(self, body=values.unset, priority=values.unset, ttl=values.unset, title=values.unset, sound=values.unset, action=values.unset, data=values.unset, apn=values.unset, gcm=values.unset, sms=values.unset, facebook_messenger=values.unset, fcm=values.unset, segment=values.unset, alexa=values.unset, to_binding=value... |
def add_process(self, command=None, vsplit=False, start_directory=None):
"""
Add a new process to the current window. (vsplit/hsplit).
"""
assert command is None or isinstance(command, six.text_type)
assert start_directory is None or isinstance(start_directory, six.text_type)
... | def function[add_process, parameter[self, command, vsplit, start_directory]]:
constant[
Add a new process to the current window. (vsplit/hsplit).
]
assert[<ast.BoolOp object at 0x7da20e9603a0>]
assert[<ast.BoolOp object at 0x7da20c76d5a0>]
variable[window] assign[=] call[name[sel... | keyword[def] identifier[add_process] ( identifier[self] , identifier[command] = keyword[None] , identifier[vsplit] = keyword[False] , identifier[start_directory] = keyword[None] ):
literal[string]
keyword[assert] identifier[command] keyword[is] keyword[None] keyword[or] identifier[isinstance] ... | def add_process(self, command=None, vsplit=False, start_directory=None):
"""
Add a new process to the current window. (vsplit/hsplit).
"""
assert command is None or isinstance(command, six.text_type)
assert start_directory is None or isinstance(start_directory, six.text_type)
window = se... |
def lnprior(x):
"""Return the log prior given parameter vector `x`."""
per, t0, b = x
if b < -1 or b > 1:
return -np.inf
elif per < 7 or per > 10:
return -np.inf
elif t0 < 1978 or t0 > 1979:
return -np.inf
else:
return 0. | def function[lnprior, parameter[x]]:
constant[Return the log prior given parameter vector `x`.]
<ast.Tuple object at 0x7da1b0e0d3f0> assign[=] name[x]
if <ast.BoolOp object at 0x7da1b0e0ec20> begin[:]
return[<ast.UnaryOp object at 0x7da1b0e0dc60>] | keyword[def] identifier[lnprior] ( identifier[x] ):
literal[string]
identifier[per] , identifier[t0] , identifier[b] = identifier[x]
keyword[if] identifier[b] <- literal[int] keyword[or] identifier[b] > literal[int] :
keyword[return] - identifier[np] . identifier[inf]
keyword[elif] ... | def lnprior(x):
"""Return the log prior given parameter vector `x`."""
(per, t0, b) = x
if b < -1 or b > 1:
return -np.inf # depends on [control=['if'], data=[]]
elif per < 7 or per > 10:
return -np.inf # depends on [control=['if'], data=[]]
elif t0 < 1978 or t0 > 1979:
ret... |
def methods(*meth):
"""
To explicitely set the methods to use without using @route
This can only be applied of methods. Not class.
:param meth: tuple of available method
:return:
"""
def decorator(f):
if not hasattr(f, '_methods_cache'):
f._methods_cache = [m.upper() for... | def function[methods, parameter[]]:
constant[
To explicitely set the methods to use without using @route
This can only be applied of methods. Not class.
:param meth: tuple of available method
:return:
]
def function[decorator, parameter[f]]:
if <ast.UnaryOp object at... | keyword[def] identifier[methods] (* identifier[meth] ):
literal[string]
keyword[def] identifier[decorator] ( identifier[f] ):
keyword[if] keyword[not] identifier[hasattr] ( identifier[f] , literal[string] ):
identifier[f] . identifier[_methods_cache] =[ identifier[m] . identifier[u... | def methods(*meth):
"""
To explicitely set the methods to use without using @route
This can only be applied of methods. Not class.
:param meth: tuple of available method
:return:
"""
def decorator(f):
if not hasattr(f, '_methods_cache'):
f._methods_cache = [m.upper() fo... |
def load_config_module():
"""
If the config.py file exists, import it as a module. If it does not exist,
call sys.exit() with a request to run oaepub configure.
"""
import imp
config_path = config_location()
try:
config = imp.load_source('config', config_path)
except IOError:
... | def function[load_config_module, parameter[]]:
constant[
If the config.py file exists, import it as a module. If it does not exist,
call sys.exit() with a request to run oaepub configure.
]
import module[imp]
variable[config_path] assign[=] call[name[config_location], parameter[]]
<a... | keyword[def] identifier[load_config_module] ():
literal[string]
keyword[import] identifier[imp]
identifier[config_path] = identifier[config_location] ()
keyword[try] :
identifier[config] = identifier[imp] . identifier[load_source] ( literal[string] , identifier[config_path] )
keyw... | def load_config_module():
"""
If the config.py file exists, import it as a module. If it does not exist,
call sys.exit() with a request to run oaepub configure.
"""
import imp
config_path = config_location()
try:
config = imp.load_source('config', config_path) # depends on [control=... |
def get_seqstr(config, metadata):
"""
Extract and reformat imaging sequence(s) and variant(s) into pretty
strings.
Parameters
----------
config : :obj:`dict`
A dictionary with relevant information regarding sequences, sequence
variants, phase encoding directions, and task names.... | def function[get_seqstr, parameter[config, metadata]]:
constant[
Extract and reformat imaging sequence(s) and variant(s) into pretty
strings.
Parameters
----------
config : :obj:`dict`
A dictionary with relevant information regarding sequences, sequence
variants, phase encod... | keyword[def] identifier[get_seqstr] ( identifier[config] , identifier[metadata] ):
literal[string]
identifier[seq_abbrs] = identifier[metadata] . identifier[get] ( literal[string] , literal[string] ). identifier[split] ( literal[string] )
identifier[seqs] =[ identifier[config] [ literal[string] ]. ide... | def get_seqstr(config, metadata):
"""
Extract and reformat imaging sequence(s) and variant(s) into pretty
strings.
Parameters
----------
config : :obj:`dict`
A dictionary with relevant information regarding sequences, sequence
variants, phase encoding directions, and task names.... |
def new_socket():
"""
Create a new socket with OS-specific parameters
Try to set SO_REUSEPORT for BSD-flavored systems if it's an option.
Catches errors if not.
"""
new_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
new_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
... | def function[new_socket, parameter[]]:
constant[
Create a new socket with OS-specific parameters
Try to set SO_REUSEPORT for BSD-flavored systems if it's an option.
Catches errors if not.
]
variable[new_sock] assign[=] call[name[socket].socket, parameter[name[socket].AF_INET, name[socke... | keyword[def] identifier[new_socket] ():
literal[string]
identifier[new_sock] = identifier[socket] . identifier[socket] ( identifier[socket] . identifier[AF_INET] , identifier[socket] . identifier[SOCK_STREAM] )
identifier[new_sock] . identifier[setsockopt] ( identifier[socket] . identifier[SOL_SOCKET]... | def new_socket():
"""
Create a new socket with OS-specific parameters
Try to set SO_REUSEPORT for BSD-flavored systems if it's an option.
Catches errors if not.
"""
new_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
new_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
... |
def show_configure(self):
"""
Show the configuration window, or deiconify (un-minimise) it if it's already open.
"""
logging.info("Displaying configuration window")
if self.configWindow is None:
self.configWindow = ConfigWindow(self)
self.configWindow.show... | def function[show_configure, parameter[self]]:
constant[
Show the configuration window, or deiconify (un-minimise) it if it's already open.
]
call[name[logging].info, parameter[constant[Displaying configuration window]]]
if compare[name[self].configWindow is constant[None]] begin... | keyword[def] identifier[show_configure] ( identifier[self] ):
literal[string]
identifier[logging] . identifier[info] ( literal[string] )
keyword[if] identifier[self] . identifier[configWindow] keyword[is] keyword[None] :
identifier[self] . identifier[configWindow] = identif... | def show_configure(self):
"""
Show the configuration window, or deiconify (un-minimise) it if it's already open.
"""
logging.info('Displaying configuration window')
if self.configWindow is None:
self.configWindow = ConfigWindow(self)
self.configWindow.show() # depends on [co... |
def circle_plot(netIn, ax, nodelabels=None, linestyle='k-', nodesize=1000, cmap='Set2'):
r'''
Function draws "circle plot" and exports axis handles
Parameters
-------------
netIn : temporal network input (graphlet or contact)
ax : matplotlib ax handles.
nodelabels : list
nodes labe... | def function[circle_plot, parameter[netIn, ax, nodelabels, linestyle, nodesize, cmap]]:
constant[
Function draws "circle plot" and exports axis handles
Parameters
-------------
netIn : temporal network input (graphlet or contact)
ax : matplotlib ax handles.
nodelabels : list
no... | keyword[def] identifier[circle_plot] ( identifier[netIn] , identifier[ax] , identifier[nodelabels] = keyword[None] , identifier[linestyle] = literal[string] , identifier[nodesize] = literal[int] , identifier[cmap] = literal[string] ):
literal[string]
identifier[inputType] = identifier[checkInput] ( id... | def circle_plot(netIn, ax, nodelabels=None, linestyle='k-', nodesize=1000, cmap='Set2'):
"""
Function draws "circle plot" and exports axis handles
Parameters
-------------
netIn : temporal network input (graphlet or contact)
ax : matplotlib ax handles.
nodelabels : list
nodes label... |
def _zmaxFindStart(z,Ez,pot):
"""
NAME:
_zmaxFindStart
PURPOSE:
Find adequate end point to solve for zmax
INPUT:
z - height
Ez - vertical energy
pot - potential
OUTPUT:
zend
HISTORY:
2012-06-01 - Written - Bovy (IAS)
"""
if z == 0.: ztry= ... | def function[_zmaxFindStart, parameter[z, Ez, pot]]:
constant[
NAME:
_zmaxFindStart
PURPOSE:
Find adequate end point to solve for zmax
INPUT:
z - height
Ez - vertical energy
pot - potential
OUTPUT:
zend
HISTORY:
2012-06-01 - Written - Bovy (IA... | keyword[def] identifier[_zmaxFindStart] ( identifier[z] , identifier[Ez] , identifier[pot] ):
literal[string]
keyword[if] identifier[z] == literal[int] : identifier[ztry] = literal[int]
keyword[else] : identifier[ztry] = literal[int] * identifier[nu] . identifier[fabs] ( identifier[z] )
keyword... | def _zmaxFindStart(z, Ez, pot):
"""
NAME:
_zmaxFindStart
PURPOSE:
Find adequate end point to solve for zmax
INPUT:
z - height
Ez - vertical energy
pot - potential
OUTPUT:
zend
HISTORY:
2012-06-01 - Written - Bovy (IAS)
"""
if z == 0.0:
... |
def head(source, count: int = 5):
"""
Displays a specified number of elements in a source object of many
different possible types.
:param source:
DataFrames will show *count* rows of that DataFrame. A list, tuple or
other iterable, will show the first *count* rows. Dictionaries will
... | def function[head, parameter[source, count]]:
constant[
Displays a specified number of elements in a source object of many
different possible types.
:param source:
DataFrames will show *count* rows of that DataFrame. A list, tuple or
other iterable, will show the first *count* rows.... | keyword[def] identifier[head] ( identifier[source] , identifier[count] : identifier[int] = literal[int] ):
literal[string]
identifier[r] = identifier[_get_report] ()
identifier[r] . identifier[append_body] ( identifier[render_texts] . identifier[head] ( identifier[source] , identifier[count] = identif... | def head(source, count: int=5):
"""
Displays a specified number of elements in a source object of many
different possible types.
:param source:
DataFrames will show *count* rows of that DataFrame. A list, tuple or
other iterable, will show the first *count* rows. Dictionaries will
... |
def eval_str(s: str, ctx: compiler.CompilerContext, module: types.ModuleType, eof: Any):
"""Evaluate the forms in a string into a Python module AST node."""
last = eof
for form in reader.read_str(s, resolver=runtime.resolve_alias, eof=eof):
last = compiler.compile_and_exec_form(form, ctx, module)
... | def function[eval_str, parameter[s, ctx, module, eof]]:
constant[Evaluate the forms in a string into a Python module AST node.]
variable[last] assign[=] name[eof]
for taget[name[form]] in starred[call[name[reader].read_str, parameter[name[s]]]] begin[:]
variable[last] assign[=] c... | keyword[def] identifier[eval_str] ( identifier[s] : identifier[str] , identifier[ctx] : identifier[compiler] . identifier[CompilerContext] , identifier[module] : identifier[types] . identifier[ModuleType] , identifier[eof] : identifier[Any] ):
literal[string]
identifier[last] = identifier[eof]
keywor... | def eval_str(s: str, ctx: compiler.CompilerContext, module: types.ModuleType, eof: Any):
"""Evaluate the forms in a string into a Python module AST node."""
last = eof
for form in reader.read_str(s, resolver=runtime.resolve_alias, eof=eof):
last = compiler.compile_and_exec_form(form, ctx, module) #... |
def _find_terminator(self, iterator):
"""The terminator might have some additional newlines before it.
There is at least one application that sends additional newlines
before headers (the python setuptools package).
"""
for line in iterator:
if not line:
... | def function[_find_terminator, parameter[self, iterator]]:
constant[The terminator might have some additional newlines before it.
There is at least one application that sends additional newlines
before headers (the python setuptools package).
]
for taget[name[line]] in starred[na... | keyword[def] identifier[_find_terminator] ( identifier[self] , identifier[iterator] ):
literal[string]
keyword[for] identifier[line] keyword[in] identifier[iterator] :
keyword[if] keyword[not] identifier[line] :
keyword[break]
identifier[line] = iden... | def _find_terminator(self, iterator):
"""The terminator might have some additional newlines before it.
There is at least one application that sends additional newlines
before headers (the python setuptools package).
"""
for line in iterator:
if not line:
break # depe... |
def create_body_index(xml_string):
""" Extract a name to index dictionary from 6dof settings xml """
xml = ET.fromstring(xml_string)
body_to_index = {}
for index, body in enumerate(xml.findall("*/Body/Name")):
body_to_index[body.text.strip()] = index
return body_to_index | def function[create_body_index, parameter[xml_string]]:
constant[ Extract a name to index dictionary from 6dof settings xml ]
variable[xml] assign[=] call[name[ET].fromstring, parameter[name[xml_string]]]
variable[body_to_index] assign[=] dictionary[[], []]
for taget[tuple[[<ast.Name obj... | keyword[def] identifier[create_body_index] ( identifier[xml_string] ):
literal[string]
identifier[xml] = identifier[ET] . identifier[fromstring] ( identifier[xml_string] )
identifier[body_to_index] ={}
keyword[for] identifier[index] , identifier[body] keyword[in] identifier[enumerate] ( ident... | def create_body_index(xml_string):
""" Extract a name to index dictionary from 6dof settings xml """
xml = ET.fromstring(xml_string)
body_to_index = {}
for (index, body) in enumerate(xml.findall('*/Body/Name')):
body_to_index[body.text.strip()] = index # depends on [control=['for'], data=[]]
... |
def runTask(self, task, timeout=None):
"""Run a child task to completion. Returns the result of
the child task.
"""
# Initialize the task.
task.initialize(self)
# Start the task.
task.start()
# Lets other threads run
time.sleep(0)
# Wai... | def function[runTask, parameter[self, task, timeout]]:
constant[Run a child task to completion. Returns the result of
the child task.
]
call[name[task].initialize, parameter[name[self]]]
call[name[task].start, parameter[]]
call[name[time].sleep, parameter[constant[0]]]
... | keyword[def] identifier[runTask] ( identifier[self] , identifier[task] , identifier[timeout] = keyword[None] ):
literal[string]
identifier[task] . identifier[initialize] ( identifier[self] )
identifier[task] . identifier[start] ()
identifier[time] . id... | def runTask(self, task, timeout=None):
"""Run a child task to completion. Returns the result of
the child task.
"""
# Initialize the task.
task.initialize(self)
# Start the task.
task.start()
# Lets other threads run
time.sleep(0)
# Wait for it to finish.
res = task.... |
def trace(fun, *a, **k):
""" define a tracer for a rule function
for log and statistic purposes """
@wraps(fun)
def tracer(*a, **k):
ret = fun(*a, **k)
print('trace:fun: %s\n ret=%s\n a=%s\nk%s\n' %
(str(fun), str(ret), str(a), str(k)))
return ret
return tracer | def function[trace, parameter[fun]]:
constant[ define a tracer for a rule function
for log and statistic purposes ]
def function[tracer, parameter[]]:
variable[ret] assign[=] call[name[fun], parameter[<ast.Starred object at 0x7da1b28d81f0>]]
call[name[print], paramete... | keyword[def] identifier[trace] ( identifier[fun] ,* identifier[a] ,** identifier[k] ):
literal[string]
@ identifier[wraps] ( identifier[fun] )
keyword[def] identifier[tracer] (* identifier[a] ,** identifier[k] ):
identifier[ret] = identifier[fun] (* identifier[a] ,** identifier[k] )
... | def trace(fun, *a, **k):
""" define a tracer for a rule function
for log and statistic purposes """
@wraps(fun)
def tracer(*a, **k):
ret = fun(*a, **k)
print('trace:fun: %s\n ret=%s\n a=%s\nk%s\n' % (str(fun), str(ret), str(a), str(k)))
return ret
return tracer |
def ignore(self, matcher):
'''
Unblock and ignore the matched events, if any.
'''
events = self.eventtree.findAndRemove(matcher)
for e in events:
self.queue.unblock(e)
e.canignore = True | def function[ignore, parameter[self, matcher]]:
constant[
Unblock and ignore the matched events, if any.
]
variable[events] assign[=] call[name[self].eventtree.findAndRemove, parameter[name[matcher]]]
for taget[name[e]] in starred[name[events]] begin[:]
call[name... | keyword[def] identifier[ignore] ( identifier[self] , identifier[matcher] ):
literal[string]
identifier[events] = identifier[self] . identifier[eventtree] . identifier[findAndRemove] ( identifier[matcher] )
keyword[for] identifier[e] keyword[in] identifier[events] :
identifi... | def ignore(self, matcher):
"""
Unblock and ignore the matched events, if any.
"""
events = self.eventtree.findAndRemove(matcher)
for e in events:
self.queue.unblock(e)
e.canignore = True # depends on [control=['for'], data=['e']] |
def process_event(event):
"""Pretty prints events.
Prints all events that occur with two spaces between each new
conversation and a single space between turns of a conversation.
Args:
event(event.Event): The current event to process.
"""
if event.type == EventType.ON_CONVERSATION_TURN_... | def function[process_event, parameter[event]]:
constant[Pretty prints events.
Prints all events that occur with two spaces between each new
conversation and a single space between turns of a conversation.
Args:
event(event.Event): The current event to process.
]
if compare[name... | keyword[def] identifier[process_event] ( identifier[event] ):
literal[string]
keyword[if] identifier[event] . identifier[type] == identifier[EventType] . identifier[ON_CONVERSATION_TURN_STARTED] :
identifier[print] ()
identifier[print] ( identifier[event] )
keyword[if] ( identifier[ev... | def process_event(event):
"""Pretty prints events.
Prints all events that occur with two spaces between each new
conversation and a single space between turns of a conversation.
Args:
event(event.Event): The current event to process.
"""
if event.type == EventType.ON_CONVERSATION_TURN_... |
def send(self, msg):
'''Send the message. If message is an iterable, then send
all the messages.'''
app = self.app or current_app
mailer = app.extensions['marrowmailer']
mailer.start()
if not hasattr(msg, '__iter__'):
result = mailer.send(msg)
else:
... | def function[send, parameter[self, msg]]:
constant[Send the message. If message is an iterable, then send
all the messages.]
variable[app] assign[=] <ast.BoolOp object at 0x7da1b2350940>
variable[mailer] assign[=] call[name[app].extensions][constant[marrowmailer]]
call[name[mail... | keyword[def] identifier[send] ( identifier[self] , identifier[msg] ):
literal[string]
identifier[app] = identifier[self] . identifier[app] keyword[or] identifier[current_app]
identifier[mailer] = identifier[app] . identifier[extensions] [ literal[string] ]
identifier[mailer] . ... | def send(self, msg):
"""Send the message. If message is an iterable, then send
all the messages."""
app = self.app or current_app
mailer = app.extensions['marrowmailer']
mailer.start()
if not hasattr(msg, '__iter__'):
result = mailer.send(msg) # depends on [control=['if'], data=[]]... |
def add_boolean(self, b):
"""
Add a boolean value to the stream.
:param bool b: boolean value to add
"""
if b:
self.packet.write(one_byte)
else:
self.packet.write(zero_byte)
return self | def function[add_boolean, parameter[self, b]]:
constant[
Add a boolean value to the stream.
:param bool b: boolean value to add
]
if name[b] begin[:]
call[name[self].packet.write, parameter[name[one_byte]]]
return[name[self]] | keyword[def] identifier[add_boolean] ( identifier[self] , identifier[b] ):
literal[string]
keyword[if] identifier[b] :
identifier[self] . identifier[packet] . identifier[write] ( identifier[one_byte] )
keyword[else] :
identifier[self] . identifier[packet] . ident... | def add_boolean(self, b):
"""
Add a boolean value to the stream.
:param bool b: boolean value to add
"""
if b:
self.packet.write(one_byte) # depends on [control=['if'], data=[]]
else:
self.packet.write(zero_byte)
return self |
def GET_blockchain_num_subdomains( self, path_info, blockchain_name ):
"""
Handle GET /blockchains/:blockchainID/subdomains_count
Takes `all=true` to include expired names
Reply with the number of names on this blockchain
"""
if blockchain_name != 'bitcoin':
#... | def function[GET_blockchain_num_subdomains, parameter[self, path_info, blockchain_name]]:
constant[
Handle GET /blockchains/:blockchainID/subdomains_count
Takes `all=true` to include expired names
Reply with the number of names on this blockchain
]
if compare[name[blockch... | keyword[def] identifier[GET_blockchain_num_subdomains] ( identifier[self] , identifier[path_info] , identifier[blockchain_name] ):
literal[string]
keyword[if] identifier[blockchain_name] != literal[string] :
identifier[self] . identifier[_reply_json] ({ literal[string] : lite... | def GET_blockchain_num_subdomains(self, path_info, blockchain_name):
"""
Handle GET /blockchains/:blockchainID/subdomains_count
Takes `all=true` to include expired names
Reply with the number of names on this blockchain
"""
if blockchain_name != 'bitcoin':
# not supported... |
def kcover(I,J,c,k):
"""kcover -- minimize the number of uncovered customers from k facilities.
Parameters:
- I: set of customers
- J: set of potential facilities
- c[i,j]: cost of servicing customer i from facility j
- k: number of facilities to be used
Returns a model, read... | def function[kcover, parameter[I, J, c, k]]:
constant[kcover -- minimize the number of uncovered customers from k facilities.
Parameters:
- I: set of customers
- J: set of potential facilities
- c[i,j]: cost of servicing customer i from facility j
- k: number of facilities to... | keyword[def] identifier[kcover] ( identifier[I] , identifier[J] , identifier[c] , identifier[k] ):
literal[string]
identifier[model] = identifier[Model] ( literal[string] )
identifier[z] , identifier[y] , identifier[x] ={},{},{}
keyword[for] identifier[i] keyword[in] identifier[I] :
... | def kcover(I, J, c, k):
"""kcover -- minimize the number of uncovered customers from k facilities.
Parameters:
- I: set of customers
- J: set of potential facilities
- c[i,j]: cost of servicing customer i from facility j
- k: number of facilities to be used
Returns a model, r... |
def hide_routemap_holder_route_map_content_match_extcommunity_extcommunity_num(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
route_map ... | def function[hide_routemap_holder_route_map_content_match_extcommunity_extcommunity_num, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[hide_routemap_holder] assign[=] call[name[ET].SubElement, para... | keyword[def] identifier[hide_routemap_holder_route_map_content_match_extcommunity_extcommunity_num] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[hide_routemap_holder] = identifier[ET] .... | def hide_routemap_holder_route_map_content_match_extcommunity_extcommunity_num(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
hide_routemap_holder = ET.SubElement(config, 'hide-routemap-holder', xmlns='urn:brocade.com:mgmt:brocade-ip-policy')
route_map = ET.SubElement(... |
def cotangent(x, null=(-np.inf, np.inf), rtol=default_rtol, atol=default_atol):
'''
cotangent(x) is equivalent to cot(x) except that it also works on sparse arrays.
The optional argument null (default, (-numpy.inf, numpy.inf)) may be specified to indicate what
value(s) should be assigned when x == 0 or... | def function[cotangent, parameter[x, null, rtol, atol]]:
constant[
cotangent(x) is equivalent to cot(x) except that it also works on sparse arrays.
The optional argument null (default, (-numpy.inf, numpy.inf)) may be specified to indicate what
value(s) should be assigned when x == 0 or pi. If only ... | keyword[def] identifier[cotangent] ( identifier[x] , identifier[null] =(- identifier[np] . identifier[inf] , identifier[np] . identifier[inf] ), identifier[rtol] = identifier[default_rtol] , identifier[atol] = identifier[default_atol] ):
literal[string]
keyword[if] identifier[sps] . identifier[issparse] (... | def cotangent(x, null=(-np.inf, np.inf), rtol=default_rtol, atol=default_atol):
"""
cotangent(x) is equivalent to cot(x) except that it also works on sparse arrays.
The optional argument null (default, (-numpy.inf, numpy.inf)) may be specified to indicate what
value(s) should be assigned when x == 0 or... |
def create_or_login(resp):
"""This is called when login with OpenID succeeded and it's not
necessary to figure out if this is the users's first login or not.
This function has to redirect otherwise the user will be presented
with a terrible URL which we certainly don't want.
"""
session['openid'... | def function[create_or_login, parameter[resp]]:
constant[This is called when login with OpenID succeeded and it's not
necessary to figure out if this is the users's first login or not.
This function has to redirect otherwise the user will be presented
with a terrible URL which we certainly don't wan... | keyword[def] identifier[create_or_login] ( identifier[resp] ):
literal[string]
identifier[session] [ literal[string] ]= identifier[resp] . identifier[identity_url]
identifier[user] = identifier[User] . identifier[get_collection] (). identifier[find_one] ({ literal[string] : identifier[resp] . identif... | def create_or_login(resp):
"""This is called when login with OpenID succeeded and it's not
necessary to figure out if this is the users's first login or not.
This function has to redirect otherwise the user will be presented
with a terrible URL which we certainly don't want.
"""
session['openid'... |
def get_instance_id():
"""Gets the instance ID of this EC2 instance
:return: String instance ID or None
"""
log = logging.getLogger(mod_logger + '.get_instance_id')
# Exit if not running on AWS
if not is_aws():
log.info('This machine is not running in AWS, exiting...')
return
... | def function[get_instance_id, parameter[]]:
constant[Gets the instance ID of this EC2 instance
:return: String instance ID or None
]
variable[log] assign[=] call[name[logging].getLogger, parameter[binary_operation[name[mod_logger] + constant[.get_instance_id]]]]
if <ast.UnaryOp object a... | keyword[def] identifier[get_instance_id] ():
literal[string]
identifier[log] = identifier[logging] . identifier[getLogger] ( identifier[mod_logger] + literal[string] )
keyword[if] keyword[not] identifier[is_aws] ():
identifier[log] . identifier[info] ( literal[string] )
keywo... | def get_instance_id():
"""Gets the instance ID of this EC2 instance
:return: String instance ID or None
"""
log = logging.getLogger(mod_logger + '.get_instance_id')
# Exit if not running on AWS
if not is_aws():
log.info('This machine is not running in AWS, exiting...')
return #... |
def upload(target):
# type: (str) -> None
""" Upload the release to a pypi server.
TODO: Make sure the git directory is clean before allowing a release.
Args:
target (str):
pypi target as defined in ~/.pypirc
"""
log.info("Uploading to pypi server <33>{}".format(target))
... | def function[upload, parameter[target]]:
constant[ Upload the release to a pypi server.
TODO: Make sure the git directory is clean before allowing a release.
Args:
target (str):
pypi target as defined in ~/.pypirc
]
call[name[log].info, parameter[call[constant[Uploading... | keyword[def] identifier[upload] ( identifier[target] ):
literal[string]
identifier[log] . identifier[info] ( literal[string] . identifier[format] ( identifier[target] ))
keyword[with] identifier[conf] . identifier[within_proj_dir] ():
identifier[shell] . identifier[run] ( literal[string] . ... | def upload(target):
# type: (str) -> None
' Upload the release to a pypi server.\n\n TODO: Make sure the git directory is clean before allowing a release.\n\n Args:\n target (str):\n pypi target as defined in ~/.pypirc\n '
log.info('Uploading to pypi server <33>{}'.format(target))... |
def xd(self):
"""get xarray dataset file handle to LSM files"""
if self._xd is None:
# download files if the user requests
if None not in (self.download_start_datetime, self.download_end_datetime):
self._download()
self._xd = super(ERAtoGSSHA, self).x... | def function[xd, parameter[self]]:
constant[get xarray dataset file handle to LSM files]
if compare[name[self]._xd is constant[None]] begin[:]
if compare[constant[None] <ast.NotIn object at 0x7da2590d7190> tuple[[<ast.Attribute object at 0x7da20c6a9f90>, <ast.Attribute object at 0x7da20c... | keyword[def] identifier[xd] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_xd] keyword[is] keyword[None] :
keyword[if] keyword[None] keyword[not] keyword[in] ( identifier[self] . identifier[download_start_datetime] , identifier[self] . i... | def xd(self):
"""get xarray dataset file handle to LSM files"""
if self._xd is None:
# download files if the user requests
if None not in (self.download_start_datetime, self.download_end_datetime):
self._download() # depends on [control=['if'], data=[]]
self._xd = super(ERAt... |
def fraction_correct_fuzzy_linear_create_vector(z, z_cutoff, z_fuzzy_range):
'''A helper function for fraction_correct_fuzzy_linear.'''
assert(z_fuzzy_range * 2 < z_cutoff)
if (z == None or numpy.isnan(z)): # todo: and ignore_null_values: # If we are missing values then we either discount the case or consi... | def function[fraction_correct_fuzzy_linear_create_vector, parameter[z, z_cutoff, z_fuzzy_range]]:
constant[A helper function for fraction_correct_fuzzy_linear.]
assert[compare[binary_operation[name[z_fuzzy_range] * constant[2]] less[<] name[z_cutoff]]]
if <ast.BoolOp object at 0x7da1b23d5540> begin[... | keyword[def] identifier[fraction_correct_fuzzy_linear_create_vector] ( identifier[z] , identifier[z_cutoff] , identifier[z_fuzzy_range] ):
literal[string]
keyword[assert] ( identifier[z_fuzzy_range] * literal[int] < identifier[z_cutoff] )
keyword[if] ( identifier[z] == keyword[None] keyword[or] ide... | def fraction_correct_fuzzy_linear_create_vector(z, z_cutoff, z_fuzzy_range):
"""A helper function for fraction_correct_fuzzy_linear."""
assert z_fuzzy_range * 2 < z_cutoff
if z == None or numpy.isnan(z): # todo: and ignore_null_values: # If we are missing values then we either discount the case or consider... |
def provider_id_slot(self, other):
"""
Args:
other (ConfigProvider): Provider to examine
Returns:
(int | None): Index of existing provider with same id, if any
"""
if other:
pid = other.provider_id()
for i, provider in enumerate(se... | def function[provider_id_slot, parameter[self, other]]:
constant[
Args:
other (ConfigProvider): Provider to examine
Returns:
(int | None): Index of existing provider with same id, if any
]
if name[other] begin[:]
variable[pid] assign[=] ca... | keyword[def] identifier[provider_id_slot] ( identifier[self] , identifier[other] ):
literal[string]
keyword[if] identifier[other] :
identifier[pid] = identifier[other] . identifier[provider_id] ()
keyword[for] identifier[i] , identifier[provider] keyword[in] identifier... | def provider_id_slot(self, other):
"""
Args:
other (ConfigProvider): Provider to examine
Returns:
(int | None): Index of existing provider with same id, if any
"""
if other:
pid = other.provider_id()
for (i, provider) in enumerate(self.providers):... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.