code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _absf(ins):
''' Absolute value of top of the stack (48 bits)
'''
output = _float_oper(ins.quad[2])
output.append('res 7, e') # Just resets the sign bit!
output.extend(_fpush())
return output | def function[_absf, parameter[ins]]:
constant[ Absolute value of top of the stack (48 bits)
]
variable[output] assign[=] call[name[_float_oper], parameter[call[name[ins].quad][constant[2]]]]
call[name[output].append, parameter[constant[res 7, e]]]
call[name[output].extend, parameter[... | keyword[def] identifier[_absf] ( identifier[ins] ):
literal[string]
identifier[output] = identifier[_float_oper] ( identifier[ins] . identifier[quad] [ literal[int] ])
identifier[output] . identifier[append] ( literal[string] )
identifier[output] . identifier[extend] ( identifier[_fpush] ())
... | def _absf(ins):
""" Absolute value of top of the stack (48 bits)
"""
output = _float_oper(ins.quad[2])
output.append('res 7, e') # Just resets the sign bit!
output.extend(_fpush())
return output |
def _do_lumping(self):
"""Do the MVCA lumping.
"""
model = LandmarkAgglomerative(linkage='ward',
n_clusters=self.n_macrostates,
metric=self.metric,
n_landmarks=self.n_landmarks,
... | def function[_do_lumping, parameter[self]]:
constant[Do the MVCA lumping.
]
variable[model] assign[=] call[name[LandmarkAgglomerative], parameter[]]
call[name[model].fit, parameter[list[[<ast.Attribute object at 0x7da1b0785d50>]]]]
if name[self].fit_only begin[:]
... | keyword[def] identifier[_do_lumping] ( identifier[self] ):
literal[string]
identifier[model] = identifier[LandmarkAgglomerative] ( identifier[linkage] = literal[string] ,
identifier[n_clusters] = identifier[self] . identifier[n_macrostates] ,
identifier[metric] = identifier[self] ... | def _do_lumping(self):
"""Do the MVCA lumping.
"""
model = LandmarkAgglomerative(linkage='ward', n_clusters=self.n_macrostates, metric=self.metric, n_landmarks=self.n_landmarks, landmark_strategy=self.landmark_strategy, random_state=self.random_state)
model.fit([self.transmat_])
if self.fit_only... |
def exit(self, status=0, message=None):
""" Handle general message exits (e.g. version).
"""
if message:
raise HelpBanner(message.strip(), code=status) | def function[exit, parameter[self, status, message]]:
constant[ Handle general message exits (e.g. version).
]
if name[message] begin[:]
<ast.Raise object at 0x7da204564c70> | keyword[def] identifier[exit] ( identifier[self] , identifier[status] = literal[int] , identifier[message] = keyword[None] ):
literal[string]
keyword[if] identifier[message] :
keyword[raise] identifier[HelpBanner] ( identifier[message] . identifier[strip] (), identifier[code] = ident... | def exit(self, status=0, message=None):
""" Handle general message exits (e.g. version).
"""
if message:
raise HelpBanner(message.strip(), code=status) # depends on [control=['if'], data=[]] |
def keyPressEvent(self, event):
"""Reimplement Qt method"""
if event == QKeySequence.Copy:
self.copy()
else:
QTableView.keyPressEvent(self, event) | def function[keyPressEvent, parameter[self, event]]:
constant[Reimplement Qt method]
if compare[name[event] equal[==] name[QKeySequence].Copy] begin[:]
call[name[self].copy, parameter[]] | keyword[def] identifier[keyPressEvent] ( identifier[self] , identifier[event] ):
literal[string]
keyword[if] identifier[event] == identifier[QKeySequence] . identifier[Copy] :
identifier[self] . identifier[copy] ()
keyword[else] :
identifier[QTableView] . id... | def keyPressEvent(self, event):
"""Reimplement Qt method"""
if event == QKeySequence.Copy:
self.copy() # depends on [control=['if'], data=[]]
else:
QTableView.keyPressEvent(self, event) |
def open_multi(cls, sock, chunk_types, isattys, chunk_eof_type=None, buf_size=None,
select_timeout=None):
"""Yields the write sides of pipes that will copy appropriately chunked values to the socket."""
cls._assert_aligned(chunk_types, isattys)
# N.B. This is purely to permit safe handling... | def function[open_multi, parameter[cls, sock, chunk_types, isattys, chunk_eof_type, buf_size, select_timeout]]:
constant[Yields the write sides of pipes that will copy appropriately chunked values to the socket.]
call[name[cls]._assert_aligned, parameter[name[chunk_types], name[isattys]]]
with c... | keyword[def] identifier[open_multi] ( identifier[cls] , identifier[sock] , identifier[chunk_types] , identifier[isattys] , identifier[chunk_eof_type] = keyword[None] , identifier[buf_size] = keyword[None] ,
identifier[select_timeout] = keyword[None] ):
literal[string]
identifier[cls] . identifier[_assert_... | def open_multi(cls, sock, chunk_types, isattys, chunk_eof_type=None, buf_size=None, select_timeout=None):
"""Yields the write sides of pipes that will copy appropriately chunked values to the socket."""
cls._assert_aligned(chunk_types, isattys)
# N.B. This is purely to permit safe handling of a dynamic numb... |
def MA_serial(self,days,rev=0):
""" see make_serial()
收盤價移動平均 list 化,資料格式請見 def make_serial()
"""
return self.make_serial(self.raw_data,days,rev) | def function[MA_serial, parameter[self, days, rev]]:
constant[ see make_serial()
收盤價移動平均 list 化,資料格式請見 def make_serial()
]
return[call[name[self].make_serial, parameter[name[self].raw_data, name[days], name[rev]]]] | keyword[def] identifier[MA_serial] ( identifier[self] , identifier[days] , identifier[rev] = literal[int] ):
literal[string]
keyword[return] identifier[self] . identifier[make_serial] ( identifier[self] . identifier[raw_data] , identifier[days] , identifier[rev] ) | def MA_serial(self, days, rev=0):
""" see make_serial()
收盤價移動平均 list 化,資料格式請見 def make_serial()
"""
return self.make_serial(self.raw_data, days, rev) |
def processResponse(self, arg, replytype, **kw):
"""
Parameters:
arg -- deferred
replytype -- typecode
"""
if self.debug:
log.msg('--->PROCESS REQUEST\n%s' %arg, debug=1)
for h in self.handlers:
arg.addCallback(h.processResponse, ... | def function[processResponse, parameter[self, arg, replytype]]:
constant[
Parameters:
arg -- deferred
replytype -- typecode
]
if name[self].debug begin[:]
call[name[log].msg, parameter[binary_operation[constant[--->PROCESS REQUEST
%s] <ast.Mod obj... | keyword[def] identifier[processResponse] ( identifier[self] , identifier[arg] , identifier[replytype] ,** identifier[kw] ):
literal[string]
keyword[if] identifier[self] . identifier[debug] :
identifier[log] . identifier[msg] ( literal[string] % identifier[arg] , identifier[debug] = li... | def processResponse(self, arg, replytype, **kw):
"""
Parameters:
arg -- deferred
replytype -- typecode
"""
if self.debug:
log.msg('--->PROCESS REQUEST\n%s' % arg, debug=1) # depends on [control=['if'], data=[]]
for h in self.handlers:
arg.addCallback... |
async def wait(self):
"""Wait until the connection with the server ends.
Client applications can use this function to block the main thread
during the life of the connection.
Note: this method is a coroutine.
"""
while True:
await self.eio.wait()
... | <ast.AsyncFunctionDef object at 0x7da18ede7760> | keyword[async] keyword[def] identifier[wait] ( identifier[self] ):
literal[string]
keyword[while] keyword[True] :
keyword[await] identifier[self] . identifier[eio] . identifier[wait] ()
keyword[await] identifier[self] . identifier[sleep] ( literal[int] )
k... | async def wait(self):
"""Wait until the connection with the server ends.
Client applications can use this function to block the main thread
during the life of the connection.
Note: this method is a coroutine.
"""
while True:
await self.eio.wait()
await self.slee... |
def _IsText(self, bytes_in, encoding=None):
"""Examine the bytes in and determine if they are indicative of text.
Parsers need quick and at least semi reliable method of discovering whether
or not a particular byte stream is text or resembles text or not. This can
be used in text parsers to determine i... | def function[_IsText, parameter[self, bytes_in, encoding]]:
constant[Examine the bytes in and determine if they are indicative of text.
Parsers need quick and at least semi reliable method of discovering whether
or not a particular byte stream is text or resembles text or not. This can
be used in t... | keyword[def] identifier[_IsText] ( identifier[self] , identifier[bytes_in] , identifier[encoding] = keyword[None] ):
literal[string]
identifier[is_text] = keyword[True]
keyword[if] identifier[isinstance] ( identifier[bytes_in] , identifier[py2to3] . identifier[UNICODE_TYPE] ):
keyw... | def _IsText(self, bytes_in, encoding=None):
"""Examine the bytes in and determine if they are indicative of text.
Parsers need quick and at least semi reliable method of discovering whether
or not a particular byte stream is text or resembles text or not. This can
be used in text parsers to determine i... |
def filter_by_widget(self, widget_type):
"""
Returns a LayoutSlice pointing to fields with widgets of `widget_type`
"""
self._check_layout_and_form()
layout_field_names = self.layout.get_field_names()
# Let's filter all fields with widgets like widget_type
filter... | def function[filter_by_widget, parameter[self, widget_type]]:
constant[
Returns a LayoutSlice pointing to fields with widgets of `widget_type`
]
call[name[self]._check_layout_and_form, parameter[]]
variable[layout_field_names] assign[=] call[name[self].layout.get_field_names, par... | keyword[def] identifier[filter_by_widget] ( identifier[self] , identifier[widget_type] ):
literal[string]
identifier[self] . identifier[_check_layout_and_form] ()
identifier[layout_field_names] = identifier[self] . identifier[layout] . identifier[get_field_names] ()
iden... | def filter_by_widget(self, widget_type):
"""
Returns a LayoutSlice pointing to fields with widgets of `widget_type`
"""
self._check_layout_and_form()
layout_field_names = self.layout.get_field_names()
# Let's filter all fields with widgets like widget_type
filtered_fields = []
fo... |
def wheel():
'''
Return all inline documentation for wheel modules
CLI Example:
.. code-block:: bash
salt-run doc.wheel
'''
client = salt.wheel.Wheel(__opts__)
ret = client.get_docs()
return ret | def function[wheel, parameter[]]:
constant[
Return all inline documentation for wheel modules
CLI Example:
.. code-block:: bash
salt-run doc.wheel
]
variable[client] assign[=] call[name[salt].wheel.Wheel, parameter[name[__opts__]]]
variable[ret] assign[=] call[name[cli... | keyword[def] identifier[wheel] ():
literal[string]
identifier[client] = identifier[salt] . identifier[wheel] . identifier[Wheel] ( identifier[__opts__] )
identifier[ret] = identifier[client] . identifier[get_docs] ()
keyword[return] identifier[ret] | def wheel():
"""
Return all inline documentation for wheel modules
CLI Example:
.. code-block:: bash
salt-run doc.wheel
"""
client = salt.wheel.Wheel(__opts__)
ret = client.get_docs()
return ret |
def L(s, o, N=5):
"""
Likelihood
input:
s: simulated
o: observed
output:
L: likelihood
"""
# s,o = filter_nan(s,o)
return np.exp(-N*np.sum((s-o)**2)/np.sum((o-np.mean(o))**2)) | def function[L, parameter[s, o, N]]:
constant[
Likelihood
input:
s: simulated
o: observed
output:
L: likelihood
]
return[call[name[np].exp, parameter[binary_operation[binary_operation[<ast.UnaryOp object at 0x7da204564550> * call[name[np].sum, paramete... | keyword[def] identifier[L] ( identifier[s] , identifier[o] , identifier[N] = literal[int] ):
literal[string]
keyword[return] identifier[np] . identifier[exp] (- identifier[N] * identifier[np] . identifier[sum] (( identifier[s] - identifier[o] )** literal[int] )/ identifier[np] . identifier[sum] (( id... | def L(s, o, N=5):
"""
Likelihood
input:
s: simulated
o: observed
output:
L: likelihood
"""
# s,o = filter_nan(s,o)
return np.exp(-N * np.sum((s - o) ** 2) / np.sum((o - np.mean(o)) ** 2)) |
def _create_filter_by(self):
"""Transform the json-server filter arguments to model-resource ones."""
filter_by = []
for name, values in request.args.copy().lists(): # copy.lists works in py2 and py3
if name not in _SKIPPED_ARGUMENTS:
column = _re_column_name.search... | def function[_create_filter_by, parameter[self]]:
constant[Transform the json-server filter arguments to model-resource ones.]
variable[filter_by] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da1b196e5c0>, <ast.Name object at 0x7da1b196e3b0>]]] in starred[call[call[name[request].ar... | keyword[def] identifier[_create_filter_by] ( identifier[self] ):
literal[string]
identifier[filter_by] =[]
keyword[for] identifier[name] , identifier[values] keyword[in] identifier[request] . identifier[args] . identifier[copy] (). identifier[lists] ():
keyword[if] identi... | def _create_filter_by(self):
"""Transform the json-server filter arguments to model-resource ones."""
filter_by = []
for (name, values) in request.args.copy().lists(): # copy.lists works in py2 and py3
if name not in _SKIPPED_ARGUMENTS:
column = _re_column_name.search(name).group(1)
... |
def _transfer_result(fut1, fut2):
"""Helper to transfer result or errors from one Future to another."""
exc = fut1.get_exception()
if exc is not None:
tb = fut1.get_traceback()
fut2.set_exception(exc, tb)
else:
val = fut1.get_result()
fut2.set_result(val) | def function[_transfer_result, parameter[fut1, fut2]]:
constant[Helper to transfer result or errors from one Future to another.]
variable[exc] assign[=] call[name[fut1].get_exception, parameter[]]
if compare[name[exc] is_not constant[None]] begin[:]
variable[tb] assign[=] call[na... | keyword[def] identifier[_transfer_result] ( identifier[fut1] , identifier[fut2] ):
literal[string]
identifier[exc] = identifier[fut1] . identifier[get_exception] ()
keyword[if] identifier[exc] keyword[is] keyword[not] keyword[None] :
identifier[tb] = identifier[fut1] . identifier[get_traceback] ()
... | def _transfer_result(fut1, fut2):
"""Helper to transfer result or errors from one Future to another."""
exc = fut1.get_exception()
if exc is not None:
tb = fut1.get_traceback()
fut2.set_exception(exc, tb) # depends on [control=['if'], data=['exc']]
else:
val = fut1.get_result()
... |
def render_trace(
self, trace_list=None, file=sys.stdout, render_cls=default_renderer(),
symbol_len=5, segment_size=5, segment_delim=' ', extra_line=True):
""" Render the trace to a file using unicode and ASCII escape sequences.
:param trace_list: A list of signals to be output... | def function[render_trace, parameter[self, trace_list, file, render_cls, symbol_len, segment_size, segment_delim, extra_line]]:
constant[ Render the trace to a file using unicode and ASCII escape sequences.
:param trace_list: A list of signals to be output in the specified order.
:param file: T... | keyword[def] identifier[render_trace] (
identifier[self] , identifier[trace_list] = keyword[None] , identifier[file] = identifier[sys] . identifier[stdout] , identifier[render_cls] = identifier[default_renderer] (),
identifier[symbol_len] = literal[int] , identifier[segment_size] = literal[int] , identifier[segment... | def render_trace(self, trace_list=None, file=sys.stdout, render_cls=default_renderer(), symbol_len=5, segment_size=5, segment_delim=' ', extra_line=True):
""" Render the trace to a file using unicode and ASCII escape sequences.
:param trace_list: A list of signals to be output in the specified order.
... |
def _parse(data: str) -> list:
"""
Parses the given data string and returns
a list of rule objects.
"""
if isinstance(data, bytes):
data = data.decode('utf-8')
lines = (
item for item in
(item.strip() for item in data.split('\n'))
... | def function[_parse, parameter[data]]:
constant[
Parses the given data string and returns
a list of rule objects.
]
if call[name[isinstance], parameter[name[data], name[bytes]]] begin[:]
variable[data] assign[=] call[name[data].decode, parameter[constant[utf-8]]]
... | keyword[def] identifier[_parse] ( identifier[data] : identifier[str] )-> identifier[list] :
literal[string]
keyword[if] identifier[isinstance] ( identifier[data] , identifier[bytes] ):
identifier[data] = identifier[data] . identifier[decode] ( literal[string] )
identifier[lin... | def _parse(data: str) -> list:
"""
Parses the given data string and returns
a list of rule objects.
"""
if isinstance(data, bytes):
data = data.decode('utf-8') # depends on [control=['if'], data=[]]
lines = (item for item in (item.strip() for item in data.split('\n')) if len... |
def batch_normalize_with_arguments(x, arguments):
"""Applies batch normalization to x as specified in arguments.
Args:
x: A Pretty Tensor.
arguments: Either a boolean to batch_normalize or a
BatchNormalizationArguments
Returns:
x with batch normalization applied.
"""
x = prettytensor.wrap(... | def function[batch_normalize_with_arguments, parameter[x, arguments]]:
constant[Applies batch normalization to x as specified in arguments.
Args:
x: A Pretty Tensor.
arguments: Either a boolean to batch_normalize or a
BatchNormalizationArguments
Returns:
x with batch normalization applie... | keyword[def] identifier[batch_normalize_with_arguments] ( identifier[x] , identifier[arguments] ):
literal[string]
identifier[x] = identifier[prettytensor] . identifier[wrap] ( identifier[x] )
keyword[if] identifier[isinstance] ( identifier[arguments] , identifier[bool] ):
keyword[if] identifier[a... | def batch_normalize_with_arguments(x, arguments):
"""Applies batch normalization to x as specified in arguments.
Args:
x: A Pretty Tensor.
arguments: Either a boolean to batch_normalize or a
BatchNormalizationArguments
Returns:
x with batch normalization applied.
"""
x = prettytensor.w... |
def _get_data_files(self):
"""
Override of build_py.get_data_files that includes out of tree configs.
These are currently hardcoded to include everything in
../shared-data/robot-data, which will move to
opentrons/config/shared-data
"""
files = super()._get_data_f... | def function[_get_data_files, parameter[self]]:
constant[
Override of build_py.get_data_files that includes out of tree configs.
These are currently hardcoded to include everything in
../shared-data/robot-data, which will move to
opentrons/config/shared-data
]
va... | keyword[def] identifier[_get_data_files] ( identifier[self] ):
literal[string]
identifier[files] = identifier[super] (). identifier[_get_data_files] ()
identifier[build_base] = identifier[os] . identifier[path] . identifier[commonpath] ([ identifier[f] [ literal[... | def _get_data_files(self):
"""
Override of build_py.get_data_files that includes out of tree configs.
These are currently hardcoded to include everything in
../shared-data/robot-data, which will move to
opentrons/config/shared-data
"""
files = super()._get_data_files()
... |
def get_tile_id(self):
"""Creates ESA tile ID
:return: ESA tile ID
:rtype: str
"""
tree = get_xml(self.get_url(AwsConstants.METADATA))
tile_id_tag = 'TILE_ID_2A' if self.data_source is DataSource.SENTINEL2_L2A and self.baseline <= '02.06' else\
'TILE_ID'
... | def function[get_tile_id, parameter[self]]:
constant[Creates ESA tile ID
:return: ESA tile ID
:rtype: str
]
variable[tree] assign[=] call[name[get_xml], parameter[call[name[self].get_url, parameter[name[AwsConstants].METADATA]]]]
variable[tile_id_tag] assign[=] <ast.IfEx... | keyword[def] identifier[get_tile_id] ( identifier[self] ):
literal[string]
identifier[tree] = identifier[get_xml] ( identifier[self] . identifier[get_url] ( identifier[AwsConstants] . identifier[METADATA] ))
identifier[tile_id_tag] = literal[string] keyword[if] identifier[self] . identi... | def get_tile_id(self):
"""Creates ESA tile ID
:return: ESA tile ID
:rtype: str
"""
tree = get_xml(self.get_url(AwsConstants.METADATA))
tile_id_tag = 'TILE_ID_2A' if self.data_source is DataSource.SENTINEL2_L2A and self.baseline <= '02.06' else 'TILE_ID'
tile_id = tree[0].find(ti... |
def dedents(self, s, stacklevel=3):
"""
Dedent a string and substitute with the :attr:`params` attribute
Parameters
----------
s: str
string to dedent and insert the sections of the :attr:`params`
attribute
stacklevel: int
The stacklev... | def function[dedents, parameter[self, s, stacklevel]]:
constant[
Dedent a string and substitute with the :attr:`params` attribute
Parameters
----------
s: str
string to dedent and insert the sections of the :attr:`params`
attribute
stacklevel: int... | keyword[def] identifier[dedents] ( identifier[self] , identifier[s] , identifier[stacklevel] = literal[int] ):
literal[string]
identifier[s] = identifier[dedents] ( identifier[s] )
keyword[return] identifier[safe_modulo] ( identifier[s] , identifier[self] . identifier[params] , identifier... | def dedents(self, s, stacklevel=3):
"""
Dedent a string and substitute with the :attr:`params` attribute
Parameters
----------
s: str
string to dedent and insert the sections of the :attr:`params`
attribute
stacklevel: int
The stacklevel f... |
def parse_address(self, address, line_number=-1):
"""
Return an Address object from the given address. Passes itself to the Address constructor to use all the custom
loaded suffixes, cities, etc.
"""
return Address(address, self, line_number, self.logger) | def function[parse_address, parameter[self, address, line_number]]:
constant[
Return an Address object from the given address. Passes itself to the Address constructor to use all the custom
loaded suffixes, cities, etc.
]
return[call[name[Address], parameter[name[address], name[self]... | keyword[def] identifier[parse_address] ( identifier[self] , identifier[address] , identifier[line_number] =- literal[int] ):
literal[string]
keyword[return] identifier[Address] ( identifier[address] , identifier[self] , identifier[line_number] , identifier[self] . identifier[logger] ) | def parse_address(self, address, line_number=-1):
"""
Return an Address object from the given address. Passes itself to the Address constructor to use all the custom
loaded suffixes, cities, etc.
"""
return Address(address, self, line_number, self.logger) |
def from_private_key(path: str) -> SigningKeyType:
"""
Read authentication file
Add public key attribute
:param path: Authentication file path
"""
key = load_key(path)
key.pubkey = Base58Encoder.encode(key.vk)
return key | def function[from_private_key, parameter[path]]:
constant[
Read authentication file
Add public key attribute
:param path: Authentication file path
]
variable[key] assign[=] call[name[load_key], parameter[name[path]]]
name[key].pubkey assign[=] call[name[Base58Enc... | keyword[def] identifier[from_private_key] ( identifier[path] : identifier[str] )-> identifier[SigningKeyType] :
literal[string]
identifier[key] = identifier[load_key] ( identifier[path] )
identifier[key] . identifier[pubkey] = identifier[Base58Encoder] . identifier[encode] ( identifier[key... | def from_private_key(path: str) -> SigningKeyType:
"""
Read authentication file
Add public key attribute
:param path: Authentication file path
"""
key = load_key(path)
key.pubkey = Base58Encoder.encode(key.vk)
return key |
def ensembl_to_kegg(organism,kegg_db):
"""
Looks up KEGG mappings of KEGG ids to ensembl ids
:param organism: an organisms as listed in organismsKEGG()
:param kegg_db: a matching KEGG db as reported in databasesKEGG
:returns: a Pandas dataframe of with 'KEGGid' and 'ENSid'.
"""
print("KEG... | def function[ensembl_to_kegg, parameter[organism, kegg_db]]:
constant[
Looks up KEGG mappings of KEGG ids to ensembl ids
:param organism: an organisms as listed in organismsKEGG()
:param kegg_db: a matching KEGG db as reported in databasesKEGG
:returns: a Pandas dataframe of with 'KEGGid' and ... | keyword[def] identifier[ensembl_to_kegg] ( identifier[organism] , identifier[kegg_db] ):
literal[string]
identifier[print] ( literal[string] + identifier[kegg_db] + literal[string] + identifier[organism] )
identifier[sys] . identifier[stdout] . identifier[flush] ()
identifier[kegg_ens] = identifi... | def ensembl_to_kegg(organism, kegg_db):
"""
Looks up KEGG mappings of KEGG ids to ensembl ids
:param organism: an organisms as listed in organismsKEGG()
:param kegg_db: a matching KEGG db as reported in databasesKEGG
:returns: a Pandas dataframe of with 'KEGGid' and 'ENSid'.
"""
print('KE... |
def add_missing(self, aesthetics):
"""
Add missing but required scales.
Parameters
----------
aesthetics : list | tuple
Aesthetic names. Typically, ('x', 'y').
"""
# Keep only aesthetics that don't have scales
aesthetics = set(aesthetics) - se... | def function[add_missing, parameter[self, aesthetics]]:
constant[
Add missing but required scales.
Parameters
----------
aesthetics : list | tuple
Aesthetic names. Typically, ('x', 'y').
]
variable[aesthetics] assign[=] binary_operation[call[name[set]... | keyword[def] identifier[add_missing] ( identifier[self] , identifier[aesthetics] ):
literal[string]
identifier[aesthetics] = identifier[set] ( identifier[aesthetics] )- identifier[set] ( identifier[self] . identifier[input] ())
keyword[for] identifier[ae] keyword[in] identifie... | def add_missing(self, aesthetics):
"""
Add missing but required scales.
Parameters
----------
aesthetics : list | tuple
Aesthetic names. Typically, ('x', 'y').
"""
# Keep only aesthetics that don't have scales
aesthetics = set(aesthetics) - set(self.input... |
def ensure_permissions(path, user, group, permissions, maxdepth=-1):
"""Ensure permissions for path.
If path is a file, apply to file and return. If path is a directory,
apply recursively (if required) to directory contents and return.
:param user: user name
:param group: group name
:param per... | def function[ensure_permissions, parameter[path, user, group, permissions, maxdepth]]:
constant[Ensure permissions for path.
If path is a file, apply to file and return. If path is a directory,
apply recursively (if required) to directory contents and return.
:param user: user name
:param grou... | keyword[def] identifier[ensure_permissions] ( identifier[path] , identifier[user] , identifier[group] , identifier[permissions] , identifier[maxdepth] =- literal[int] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[path] ):
identifi... | def ensure_permissions(path, user, group, permissions, maxdepth=-1):
"""Ensure permissions for path.
If path is a file, apply to file and return. If path is a directory,
apply recursively (if required) to directory contents and return.
:param user: user name
:param group: group name
:param per... |
def reset(self):
"""
Process everything all over again.
"""
self.indexCount = 0
indexDir = self.store.newDirectory(self.indexDirectory)
if indexDir.exists():
indexDir.remove()
for src in self.getSources():
src.removeReliableListener(self)
... | def function[reset, parameter[self]]:
constant[
Process everything all over again.
]
name[self].indexCount assign[=] constant[0]
variable[indexDir] assign[=] call[name[self].store.newDirectory, parameter[name[self].indexDirectory]]
if call[name[indexDir].exists, parameter... | keyword[def] identifier[reset] ( identifier[self] ):
literal[string]
identifier[self] . identifier[indexCount] = literal[int]
identifier[indexDir] = identifier[self] . identifier[store] . identifier[newDirectory] ( identifier[self] . identifier[indexDirectory] )
keyword[if] iden... | def reset(self):
"""
Process everything all over again.
"""
self.indexCount = 0
indexDir = self.store.newDirectory(self.indexDirectory)
if indexDir.exists():
indexDir.remove() # depends on [control=['if'], data=[]]
for src in self.getSources():
src.removeReliableList... |
def SegmentProd(a, ids):
"""
Segmented prod op.
"""
func = lambda idxs: reduce(np.multiply, a[idxs])
return seg_map(func, a, ids), | def function[SegmentProd, parameter[a, ids]]:
constant[
Segmented prod op.
]
variable[func] assign[=] <ast.Lambda object at 0x7da1b0650d00>
return[tuple[[<ast.Call object at 0x7da1b0652380>]]] | keyword[def] identifier[SegmentProd] ( identifier[a] , identifier[ids] ):
literal[string]
identifier[func] = keyword[lambda] identifier[idxs] : identifier[reduce] ( identifier[np] . identifier[multiply] , identifier[a] [ identifier[idxs] ])
keyword[return] identifier[seg_map] ( identifier[func] , id... | def SegmentProd(a, ids):
"""
Segmented prod op.
"""
func = lambda idxs: reduce(np.multiply, a[idxs])
return (seg_map(func, a, ids),) |
def alter(self, function):
"""
Alters the currently stored value by applying a function on it.
:param function: (Function), A stateful serializable object which represents the Function defined on
server side.
This object must have a serializable Function counter part reg... | def function[alter, parameter[self, function]]:
constant[
Alters the currently stored value by applying a function on it.
:param function: (Function), A stateful serializable object which represents the Function defined on
server side.
This object must have a serializabl... | keyword[def] identifier[alter] ( identifier[self] , identifier[function] ):
literal[string]
identifier[check_not_none] ( identifier[function] , literal[string] )
keyword[return] identifier[self] . identifier[_encode_invoke] ( identifier[atomic_long_alter_codec] , identifier[function] = id... | def alter(self, function):
"""
Alters the currently stored value by applying a function on it.
:param function: (Function), A stateful serializable object which represents the Function defined on
server side.
This object must have a serializable Function counter part registe... |
def pack(self, value=None):
"""Pack the value as a binary representation.
:attr:`data` is packed before the calling :meth:`.GenericMessage.pack`.
After that, :attr:`data`'s value is restored.
Returns:
bytes: The binary representation.
Raises:
:exc:`~.ex... | def function[pack, parameter[self, value]]:
constant[Pack the value as a binary representation.
:attr:`data` is packed before the calling :meth:`.GenericMessage.pack`.
After that, :attr:`data`'s value is restored.
Returns:
bytes: The binary representation.
Raises:
... | keyword[def] identifier[pack] ( identifier[self] , identifier[value] = keyword[None] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[None] :
identifier[data_backup] = keyword[None]
keyword[if] identifier[self] . identifier[data] keyword[is] keyw... | def pack(self, value=None):
"""Pack the value as a binary representation.
:attr:`data` is packed before the calling :meth:`.GenericMessage.pack`.
After that, :attr:`data`'s value is restored.
Returns:
bytes: The binary representation.
Raises:
:exc:`~.except... |
def resnet_imagenet_34_td_weight_05_05():
"""Set of hyperparameters."""
hp = resnet_imagenet_34()
hp.use_td = "weight"
hp.targeting_rate = 0.5
hp.keep_prob = 0.5
return hp | def function[resnet_imagenet_34_td_weight_05_05, parameter[]]:
constant[Set of hyperparameters.]
variable[hp] assign[=] call[name[resnet_imagenet_34], parameter[]]
name[hp].use_td assign[=] constant[weight]
name[hp].targeting_rate assign[=] constant[0.5]
name[hp].keep_prob assign... | keyword[def] identifier[resnet_imagenet_34_td_weight_05_05] ():
literal[string]
identifier[hp] = identifier[resnet_imagenet_34] ()
identifier[hp] . identifier[use_td] = literal[string]
identifier[hp] . identifier[targeting_rate] = literal[int]
identifier[hp] . identifier[keep_prob] = literal[int]
... | def resnet_imagenet_34_td_weight_05_05():
"""Set of hyperparameters."""
hp = resnet_imagenet_34()
hp.use_td = 'weight'
hp.targeting_rate = 0.5
hp.keep_prob = 0.5
return hp |
def display_information_message_bar(
title=None,
message=None,
more_details=None,
button_text=tr('Show details ...'),
duration=8,
iface_object=iface):
"""
Display an information message bar.
:param iface_object: The QGIS IFace instance. Note that we cannot
... | def function[display_information_message_bar, parameter[title, message, more_details, button_text, duration, iface_object]]:
constant[
Display an information message bar.
:param iface_object: The QGIS IFace instance. Note that we cannot
use qgis.utils.iface since it is not available in our
... | keyword[def] identifier[display_information_message_bar] (
identifier[title] = keyword[None] ,
identifier[message] = keyword[None] ,
identifier[more_details] = keyword[None] ,
identifier[button_text] = identifier[tr] ( literal[string] ),
identifier[duration] = literal[int] ,
identifier[iface_object] = identifie... | def display_information_message_bar(title=None, message=None, more_details=None, button_text=tr('Show details ...'), duration=8, iface_object=iface):
"""
Display an information message bar.
:param iface_object: The QGIS IFace instance. Note that we cannot
use qgis.utils.iface since it is not availa... |
def _get_cache_dir(candidate):
"""Get the current cache directory."""
if candidate:
return candidate
import distutils.dist # suppress(import-error)
import distutils.command.build # suppress(import-error)
build_cmd = distutils.command.build.build(distutils.dist.Distribution())
build_cm... | def function[_get_cache_dir, parameter[candidate]]:
constant[Get the current cache directory.]
if name[candidate] begin[:]
return[name[candidate]]
import module[distutils.dist]
import module[distutils.command.build]
variable[build_cmd] assign[=] call[name[distutils].command.build... | keyword[def] identifier[_get_cache_dir] ( identifier[candidate] ):
literal[string]
keyword[if] identifier[candidate] :
keyword[return] identifier[candidate]
keyword[import] identifier[distutils] . identifier[dist]
keyword[import] identifier[distutils] . identifier[command] . ident... | def _get_cache_dir(candidate):
"""Get the current cache directory."""
if candidate:
return candidate # depends on [control=['if'], data=[]]
import distutils.dist # suppress(import-error)
import distutils.command.build # suppress(import-error)
build_cmd = distutils.command.build.build(dist... |
def has_pfn(self, url, site=None):
""" Wrapper of the pegasus hasPFN function, that allows it to be called
outside of specific pegasus functions.
"""
curr_pfn = dax.PFN(url, site)
return self.hasPFN(curr_pfn) | def function[has_pfn, parameter[self, url, site]]:
constant[ Wrapper of the pegasus hasPFN function, that allows it to be called
outside of specific pegasus functions.
]
variable[curr_pfn] assign[=] call[name[dax].PFN, parameter[name[url], name[site]]]
return[call[name[self].hasPFN, ... | keyword[def] identifier[has_pfn] ( identifier[self] , identifier[url] , identifier[site] = keyword[None] ):
literal[string]
identifier[curr_pfn] = identifier[dax] . identifier[PFN] ( identifier[url] , identifier[site] )
keyword[return] identifier[self] . identifier[hasPFN] ( identifier[cu... | def has_pfn(self, url, site=None):
""" Wrapper of the pegasus hasPFN function, that allows it to be called
outside of specific pegasus functions.
"""
curr_pfn = dax.PFN(url, site)
return self.hasPFN(curr_pfn) |
def wait_for_fun(fun, timeout=900, **kwargs):
'''
Wait until a function finishes, or times out
'''
start = time.time()
log.debug('Attempting function %s', fun)
trycount = 0
while True:
trycount += 1
try:
response = fun(**kwargs)
if not isinstance(respo... | def function[wait_for_fun, parameter[fun, timeout]]:
constant[
Wait until a function finishes, or times out
]
variable[start] assign[=] call[name[time].time, parameter[]]
call[name[log].debug, parameter[constant[Attempting function %s], name[fun]]]
variable[trycount] assign[=] co... | keyword[def] identifier[wait_for_fun] ( identifier[fun] , identifier[timeout] = literal[int] ,** identifier[kwargs] ):
literal[string]
identifier[start] = identifier[time] . identifier[time] ()
identifier[log] . identifier[debug] ( literal[string] , identifier[fun] )
identifier[trycount] = litera... | def wait_for_fun(fun, timeout=900, **kwargs):
"""
Wait until a function finishes, or times out
"""
start = time.time()
log.debug('Attempting function %s', fun)
trycount = 0
while True:
trycount += 1
try:
response = fun(**kwargs)
if not isinstance(respo... |
def reverseGeocode(self, location):
"""
The reverseGeocode operation determines the address at a particular
x/y location. You pass the coordinates of a point location to the
geocoding service, and the service returns the address that is
closest to the location.
Input:
... | def function[reverseGeocode, parameter[self, location]]:
constant[
The reverseGeocode operation determines the address at a particular
x/y location. You pass the coordinates of a point location to the
geocoding service, and the service returns the address that is
closest to the l... | keyword[def] identifier[reverseGeocode] ( identifier[self] , identifier[location] ):
literal[string]
identifier[params] ={
literal[string] : literal[string]
}
identifier[url] = identifier[self] . identifier[_url] + literal[string]
keyword[if] identifier[isinsta... | def reverseGeocode(self, location):
"""
The reverseGeocode operation determines the address at a particular
x/y location. You pass the coordinates of a point location to the
geocoding service, and the service returns the address that is
closest to the location.
Input:
... |
def validate_config(cls, service_config, target):
""" Validate generic options for a particular target """
if service_config.has_option(target, 'only_if_assigned'):
die("[%s] has an 'only_if_assigned' option. Should be "
"'%s.only_if_assigned'." % (target, cls.CONFIG_PREFIX)... | def function[validate_config, parameter[cls, service_config, target]]:
constant[ Validate generic options for a particular target ]
if call[name[service_config].has_option, parameter[name[target], constant[only_if_assigned]]] begin[:]
call[name[die], parameter[binary_operation[constant[[... | keyword[def] identifier[validate_config] ( identifier[cls] , identifier[service_config] , identifier[target] ):
literal[string]
keyword[if] identifier[service_config] . identifier[has_option] ( identifier[target] , literal[string] ):
identifier[die] ( literal[string]
lit... | def validate_config(cls, service_config, target):
""" Validate generic options for a particular target """
if service_config.has_option(target, 'only_if_assigned'):
die("[%s] has an 'only_if_assigned' option. Should be '%s.only_if_assigned'." % (target, cls.CONFIG_PREFIX)) # depends on [control=['if']... |
def template_overlaps(bank_filters, template, psd, low_frequency_cutoff):
""" This functions calculates the overlaps between the template and the
bank veto templates.
Parameters
----------
bank_filters: List of FrequencySeries
template: FrequencySeries
psd: FrequencySeries
low_frequency... | def function[template_overlaps, parameter[bank_filters, template, psd, low_frequency_cutoff]]:
constant[ This functions calculates the overlaps between the template and the
bank veto templates.
Parameters
----------
bank_filters: List of FrequencySeries
template: FrequencySeries
psd: Fr... | keyword[def] identifier[template_overlaps] ( identifier[bank_filters] , identifier[template] , identifier[psd] , identifier[low_frequency_cutoff] ):
literal[string]
identifier[overlaps] =[]
identifier[template_ow] = identifier[template] / identifier[psd]
keyword[for] identifier[bank_template] ... | def template_overlaps(bank_filters, template, psd, low_frequency_cutoff):
""" This functions calculates the overlaps between the template and the
bank veto templates.
Parameters
----------
bank_filters: List of FrequencySeries
template: FrequencySeries
psd: FrequencySeries
low_frequency... |
def arcs_missing(self):
"""Returns a sorted list of the arcs in the code not executed."""
possible = self.arc_possibilities()
executed = self.arcs_executed()
missing = [
p for p in possible
if p not in executed
and p[0] not in self.no_branc... | def function[arcs_missing, parameter[self]]:
constant[Returns a sorted list of the arcs in the code not executed.]
variable[possible] assign[=] call[name[self].arc_possibilities, parameter[]]
variable[executed] assign[=] call[name[self].arcs_executed, parameter[]]
variable[missing] assig... | keyword[def] identifier[arcs_missing] ( identifier[self] ):
literal[string]
identifier[possible] = identifier[self] . identifier[arc_possibilities] ()
identifier[executed] = identifier[self] . identifier[arcs_executed] ()
identifier[missing] =[
identifier[p] keyword[for]... | def arcs_missing(self):
"""Returns a sorted list of the arcs in the code not executed."""
possible = self.arc_possibilities()
executed = self.arcs_executed()
missing = [p for p in possible if p not in executed and p[0] not in self.no_branch]
return sorted(missing) |
def put_file(self, file, object_type, object_id, width, height, mimetype,
reproducible):
"""Puts the ``file`` of the image.
:param file: the image file to put
:type file: file-like object, :class:`file`
:param object_type: the object type of the image to put
... | def function[put_file, parameter[self, file, object_type, object_id, width, height, mimetype, reproducible]]:
constant[Puts the ``file`` of the image.
:param file: the image file to put
:type file: file-like object, :class:`file`
:param object_type: the object type of the image to put
... | keyword[def] identifier[put_file] ( identifier[self] , identifier[file] , identifier[object_type] , identifier[object_id] , identifier[width] , identifier[height] , identifier[mimetype] ,
identifier[reproducible] ):
literal[string]
keyword[raise] identifier[NotImplementedError] ( literal[string] ... | def put_file(self, file, object_type, object_id, width, height, mimetype, reproducible):
"""Puts the ``file`` of the image.
:param file: the image file to put
:type file: file-like object, :class:`file`
:param object_type: the object type of the image to put
e.g.... |
def _check_all_metadata_found(metadata, items):
"""Print warning if samples in CSV file are missing in folder"""
for name in metadata:
seen = False
for sample in items:
check_file = sample["files"][0] if sample.get("files") else sample["vrn_file"]
if isinstance(name, (tup... | def function[_check_all_metadata_found, parameter[metadata, items]]:
constant[Print warning if samples in CSV file are missing in folder]
for taget[name[name]] in starred[name[metadata]] begin[:]
variable[seen] assign[=] constant[False]
for taget[name[sample]] in starred[... | keyword[def] identifier[_check_all_metadata_found] ( identifier[metadata] , identifier[items] ):
literal[string]
keyword[for] identifier[name] keyword[in] identifier[metadata] :
identifier[seen] = keyword[False]
keyword[for] identifier[sample] keyword[in] identifier[items] :
... | def _check_all_metadata_found(metadata, items):
"""Print warning if samples in CSV file are missing in folder"""
for name in metadata:
seen = False
for sample in items:
check_file = sample['files'][0] if sample.get('files') else sample['vrn_file']
if isinstance(name, (tup... |
def create_layout(lexer=None,
reserve_space_for_menu=8,
get_prompt_tokens=None,
get_bottom_toolbar_tokens=None,
extra_input_processors=None, multiline=False,
wrap_lines=True):
"""
Creates a custom `Layout` for the Crash in... | def function[create_layout, parameter[lexer, reserve_space_for_menu, get_prompt_tokens, get_bottom_toolbar_tokens, extra_input_processors, multiline, wrap_lines]]:
constant[
Creates a custom `Layout` for the Crash input REPL
This layout includes:
* a bottom left-aligned session toolbar containe... | keyword[def] identifier[create_layout] ( identifier[lexer] = keyword[None] ,
identifier[reserve_space_for_menu] = literal[int] ,
identifier[get_prompt_tokens] = keyword[None] ,
identifier[get_bottom_toolbar_tokens] = keyword[None] ,
identifier[extra_input_processors] = keyword[None] , identifier[multiline] = keyw... | def create_layout(lexer=None, reserve_space_for_menu=8, get_prompt_tokens=None, get_bottom_toolbar_tokens=None, extra_input_processors=None, multiline=False, wrap_lines=True):
"""
Creates a custom `Layout` for the Crash input REPL
This layout includes:
* a bottom left-aligned session toolbar contai... |
async def timeout(source, timeout):
"""Raise a time-out if an element of the asynchronous sequence
takes too long to arrive.
Note: the timeout is not global but specific to each step of
the iteration.
"""
async with streamcontext(source) as streamer:
while True:
try:
... | <ast.AsyncFunctionDef object at 0x7da1b1b7d1b0> | keyword[async] keyword[def] identifier[timeout] ( identifier[source] , identifier[timeout] ):
literal[string]
keyword[async] keyword[with] identifier[streamcontext] ( identifier[source] ) keyword[as] identifier[streamer] :
keyword[while] keyword[True] :
keyword[try] :
... | async def timeout(source, timeout):
"""Raise a time-out if an element of the asynchronous sequence
takes too long to arrive.
Note: the timeout is not global but specific to each step of
the iteration.
"""
async with streamcontext(source) as streamer:
while True:
try:
... |
def ptmsiReallocationCommand(PTmsiSignature_presence=0):
"""P-TMSI REALLOCATION COMMAND Section 9.4.7"""
a = TpPd(pd=0x3)
b = MessageType(mesType=0x10) # 00010000
c = MobileId()
d = RoutingAreaIdentification()
e = ForceToStandbyAndSpareHalfOctets()
packet = a / b / c / d / e
if PTmsiSig... | def function[ptmsiReallocationCommand, parameter[PTmsiSignature_presence]]:
constant[P-TMSI REALLOCATION COMMAND Section 9.4.7]
variable[a] assign[=] call[name[TpPd], parameter[]]
variable[b] assign[=] call[name[MessageType], parameter[]]
variable[c] assign[=] call[name[MobileId], parame... | keyword[def] identifier[ptmsiReallocationCommand] ( identifier[PTmsiSignature_presence] = literal[int] ):
literal[string]
identifier[a] = identifier[TpPd] ( identifier[pd] = literal[int] )
identifier[b] = identifier[MessageType] ( identifier[mesType] = literal[int] )
identifier[c] = identifier[Mo... | def ptmsiReallocationCommand(PTmsiSignature_presence=0):
"""P-TMSI REALLOCATION COMMAND Section 9.4.7"""
a = TpPd(pd=3)
b = MessageType(mesType=16) # 00010000
c = MobileId()
d = RoutingAreaIdentification()
e = ForceToStandbyAndSpareHalfOctets()
packet = a / b / c / d / e
if PTmsiSignatu... |
def buffer_list(self):
"""
The buffer list this instance operates on.
Only available in mode != AIOBLOCK_MODE_POLL.
Changes on a submitted transfer are not fully applied until its
next submission: kernel will still be using original buffer list.
"""
if self._ioc... | def function[buffer_list, parameter[self]]:
constant[
The buffer list this instance operates on.
Only available in mode != AIOBLOCK_MODE_POLL.
Changes on a submitted transfer are not fully applied until its
next submission: kernel will still be using original buffer list.
... | keyword[def] identifier[buffer_list] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_iocb] . identifier[aio_lio_opcode] == identifier[libaio] . identifier[IO_CMD_POLL] :
keyword[raise] identifier[AttributeError]
keyword[return] identifier[s... | def buffer_list(self):
"""
The buffer list this instance operates on.
Only available in mode != AIOBLOCK_MODE_POLL.
Changes on a submitted transfer are not fully applied until its
next submission: kernel will still be using original buffer list.
"""
if self._iocb.aio_li... |
def levenshtein(str1, s2):
'''
Distance between two strings
'''
N1 = len(str1)
N2 = len(s2)
stringRange = [range(N1 + 1)] * (N2 + 1)
for i in range(N2 + 1):
stringRange[i] = range(i,i + N1 + 1)
for i in range(0,N2):
for j in range(0,N1):
if str1[j] == s2[i]:
... | def function[levenshtein, parameter[str1, s2]]:
constant[
Distance between two strings
]
variable[N1] assign[=] call[name[len], parameter[name[str1]]]
variable[N2] assign[=] call[name[len], parameter[name[s2]]]
variable[stringRange] assign[=] binary_operation[list[[<ast.Call obje... | keyword[def] identifier[levenshtein] ( identifier[str1] , identifier[s2] ):
literal[string]
identifier[N1] = identifier[len] ( identifier[str1] )
identifier[N2] = identifier[len] ( identifier[s2] )
identifier[stringRange] =[ identifier[range] ( identifier[N1] + literal[int] )]*( identifier[N2] +... | def levenshtein(str1, s2):
"""
Distance between two strings
"""
N1 = len(str1)
N2 = len(s2)
stringRange = [range(N1 + 1)] * (N2 + 1)
for i in range(N2 + 1):
stringRange[i] = range(i, i + N1 + 1) # depends on [control=['for'], data=['i']]
for i in range(0, N2):
for j in r... |
def check_requirements(self, reqs):
# type: (Iterable[str]) -> Tuple[Set[Tuple[str, str]], Set[str]]
"""Return 2 sets:
- conflicting requirements: set of (installed, wanted) reqs tuples
- missing requirements: set of reqs
"""
missing = set()
conflicting = ... | def function[check_requirements, parameter[self, reqs]]:
constant[Return 2 sets:
- conflicting requirements: set of (installed, wanted) reqs tuples
- missing requirements: set of reqs
]
variable[missing] assign[=] call[name[set], parameter[]]
variable[conflicting]... | keyword[def] identifier[check_requirements] ( identifier[self] , identifier[reqs] ):
literal[string]
identifier[missing] = identifier[set] ()
identifier[conflicting] = identifier[set] ()
keyword[if] identifier[reqs] :
identifier[ws] = identifier[WorkingSet] ( identi... | def check_requirements(self, reqs):
# type: (Iterable[str]) -> Tuple[Set[Tuple[str, str]], Set[str]]
'Return 2 sets:\n - conflicting requirements: set of (installed, wanted) reqs tuples\n - missing requirements: set of reqs\n '
missing = set()
conflicting = set()
if reqs... |
def compare_ecp_pots(potential1, potential2, compare_meta=False, rel_tol=0.0):
'''
Compare two ecp potentials for approximate equality
(exponents/coefficients are within a tolerance)
If compare_meta is True, the metadata is also compared for exact equality.
'''
if potential1['angular_momentum... | def function[compare_ecp_pots, parameter[potential1, potential2, compare_meta, rel_tol]]:
constant[
Compare two ecp potentials for approximate equality
(exponents/coefficients are within a tolerance)
If compare_meta is True, the metadata is also compared for exact equality.
]
if compar... | keyword[def] identifier[compare_ecp_pots] ( identifier[potential1] , identifier[potential2] , identifier[compare_meta] = keyword[False] , identifier[rel_tol] = literal[int] ):
literal[string]
keyword[if] identifier[potential1] [ literal[string] ]!= identifier[potential2] [ literal[string] ]:
key... | def compare_ecp_pots(potential1, potential2, compare_meta=False, rel_tol=0.0):
"""
Compare two ecp potentials for approximate equality
(exponents/coefficients are within a tolerance)
If compare_meta is True, the metadata is also compared for exact equality.
"""
if potential1['angular_momentum'... |
def generate_about_table(extra_info={}):
"""
Make a table with information about FlowCal and the current analysis.
Parameters
----------
extra_info : dict, optional
Additional keyword:value pairs to include in the table.
Returns
-------
about_table : DataFrame
Table wit... | def function[generate_about_table, parameter[extra_info]]:
constant[
Make a table with information about FlowCal and the current analysis.
Parameters
----------
extra_info : dict, optional
Additional keyword:value pairs to include in the table.
Returns
-------
about_table :... | keyword[def] identifier[generate_about_table] ( identifier[extra_info] ={}):
literal[string]
identifier[keywords] =[]
identifier[values] =[]
identifier[keywords] . identifier[append] ( literal[string] )
identifier[values] . identifier[append] ( identifier[FlowCal] . identifier[__ve... | def generate_about_table(extra_info={}):
"""
Make a table with information about FlowCal and the current analysis.
Parameters
----------
extra_info : dict, optional
Additional keyword:value pairs to include in the table.
Returns
-------
about_table : DataFrame
Table wit... |
def set_armed_state(self, state):
"""Set the armed state, also update local state."""
self.set_service_value(
self.security_sensor_service,
'Armed',
'newArmedValue',
state)
self.set_cache_value('Armed', state) | def function[set_armed_state, parameter[self, state]]:
constant[Set the armed state, also update local state.]
call[name[self].set_service_value, parameter[name[self].security_sensor_service, constant[Armed], constant[newArmedValue], name[state]]]
call[name[self].set_cache_value, parameter[const... | keyword[def] identifier[set_armed_state] ( identifier[self] , identifier[state] ):
literal[string]
identifier[self] . identifier[set_service_value] (
identifier[self] . identifier[security_sensor_service] ,
literal[string] ,
literal[string] ,
identifier[state] )
... | def set_armed_state(self, state):
"""Set the armed state, also update local state."""
self.set_service_value(self.security_sensor_service, 'Armed', 'newArmedValue', state)
self.set_cache_value('Armed', state) |
def AddBlock(self, block):
"""
Add the given block to the model and also its input/output variables
"""
if isinstance(block, Block):
self.blocks.append(block)
self.max_order = max(self.max_order, block.max_input_order-1)
self.max_order = max(self.max_o... | def function[AddBlock, parameter[self, block]]:
constant[
Add the given block to the model and also its input/output variables
]
if call[name[isinstance], parameter[name[block], name[Block]]] begin[:]
call[name[self].blocks.append, parameter[name[block]]]
... | keyword[def] identifier[AddBlock] ( identifier[self] , identifier[block] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[block] , identifier[Block] ):
identifier[self] . identifier[blocks] . identifier[append] ( identifier[block] )
identifier[self] . id... | def AddBlock(self, block):
"""
Add the given block to the model and also its input/output variables
"""
if isinstance(block, Block):
self.blocks.append(block)
self.max_order = max(self.max_order, block.max_input_order - 1)
self.max_order = max(self.max_order, block.max_ou... |
def update_track(session, track_id, latitude, longitude, stop_tracking=False):
"""
Updates the current location by creating a new track point and appending
it to the given track
"""
tracking_data = {
'track_point': {
'latitude': latitude,
'longitude': longitude,
... | def function[update_track, parameter[session, track_id, latitude, longitude, stop_tracking]]:
constant[
Updates the current location by creating a new track point and appending
it to the given track
]
variable[tracking_data] assign[=] dictionary[[<ast.Constant object at 0x7da18f00c460>, <ast... | keyword[def] identifier[update_track] ( identifier[session] , identifier[track_id] , identifier[latitude] , identifier[longitude] , identifier[stop_tracking] = keyword[False] ):
literal[string]
identifier[tracking_data] ={
literal[string] :{
literal[string] : identifier[latitude] ,
literal[... | def update_track(session, track_id, latitude, longitude, stop_tracking=False):
"""
Updates the current location by creating a new track point and appending
it to the given track
"""
tracking_data = {'track_point': {'latitude': latitude, 'longitude': longitude}, 'stop_tracking': stop_tracking}
# ... |
def resizeColumnsToContents(self):
"""Resize the columns to its contents."""
self._autosized_cols = set()
self._resizeColumnsToContents(self.table_level,
self.table_index, self._max_autosize_ms)
self._update_layout() | def function[resizeColumnsToContents, parameter[self]]:
constant[Resize the columns to its contents.]
name[self]._autosized_cols assign[=] call[name[set], parameter[]]
call[name[self]._resizeColumnsToContents, parameter[name[self].table_level, name[self].table_index, name[self]._max_autosize_ms]... | keyword[def] identifier[resizeColumnsToContents] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_autosized_cols] = identifier[set] ()
identifier[self] . identifier[_resizeColumnsToContents] ( identifier[self] . identifier[table_level] ,
identifier[self] . ... | def resizeColumnsToContents(self):
"""Resize the columns to its contents."""
self._autosized_cols = set()
self._resizeColumnsToContents(self.table_level, self.table_index, self._max_autosize_ms)
self._update_layout() |
def bat_to_sh(file_path):
"""Convert honeybee .bat file to .sh file.
WARNING: This is a very simple function and doesn't handle any edge cases.
"""
sh_file = file_path[:-4] + '.sh'
with open(file_path, 'rb') as inf, open(sh_file, 'wb') as outf:
outf.write('#!/usr/bin/env bash\n\n')
... | def function[bat_to_sh, parameter[file_path]]:
constant[Convert honeybee .bat file to .sh file.
WARNING: This is a very simple function and doesn't handle any edge cases.
]
variable[sh_file] assign[=] binary_operation[call[name[file_path]][<ast.Slice object at 0x7da1b1251750>] + constant[.sh]]
... | keyword[def] identifier[bat_to_sh] ( identifier[file_path] ):
literal[string]
identifier[sh_file] = identifier[file_path] [:- literal[int] ]+ literal[string]
keyword[with] identifier[open] ( identifier[file_path] , literal[string] ) keyword[as] identifier[inf] , identifier[open] ( identifier[sh_fil... | def bat_to_sh(file_path):
"""Convert honeybee .bat file to .sh file.
WARNING: This is a very simple function and doesn't handle any edge cases.
"""
sh_file = file_path[:-4] + '.sh'
with open(file_path, 'rb') as inf, open(sh_file, 'wb') as outf:
outf.write('#!/usr/bin/env bash\n\n')
... |
def add_options(self):
""" Add program options.
"""
super(ThemeSwitcher, self).add_options()
self.add_bool_option("-l", "--list",
help="list available themes")
self.add_bool_option("-c", "--current",
help="print path to currently selected theme")
... | def function[add_options, parameter[self]]:
constant[ Add program options.
]
call[call[name[super], parameter[name[ThemeSwitcher], name[self]]].add_options, parameter[]]
call[name[self].add_bool_option, parameter[constant[-l], constant[--list]]]
call[name[self].add_bool_option, p... | keyword[def] identifier[add_options] ( identifier[self] ):
literal[string]
identifier[super] ( identifier[ThemeSwitcher] , identifier[self] ). identifier[add_options] ()
identifier[self] . identifier[add_bool_option] ( literal[string] , literal[string] ,
identifier[help] = litera... | def add_options(self):
""" Add program options.
"""
super(ThemeSwitcher, self).add_options()
self.add_bool_option('-l', '--list', help='list available themes')
self.add_bool_option('-c', '--current', help='print path to currently selected theme')
self.add_bool_option('-n', '--next', help='ro... |
def stem(self, word):
"""
Stem a Romanian word and return the stemmed form.
:param word: The word that is stemmed.
:type word: str or unicode
:return: The stemmed form.
:rtype: unicode
"""
word = word.lower()
step1_success = False
step2_... | def function[stem, parameter[self, word]]:
constant[
Stem a Romanian word and return the stemmed form.
:param word: The word that is stemmed.
:type word: str or unicode
:return: The stemmed form.
:rtype: unicode
]
variable[word] assign[=] call[name[word]... | keyword[def] identifier[stem] ( identifier[self] , identifier[word] ):
literal[string]
identifier[word] = identifier[word] . identifier[lower] ()
identifier[step1_success] = keyword[False]
identifier[step2_success] = keyword[False]
keyword[for] identifier[i] keyword... | def stem(self, word):
"""
Stem a Romanian word and return the stemmed form.
:param word: The word that is stemmed.
:type word: str or unicode
:return: The stemmed form.
:rtype: unicode
"""
word = word.lower()
step1_success = False
step2_success = False
... |
def check_api_key(request, key, hproPk):
"""Check if an API key is valid"""
if settings.PIAPI_STANDALONE:
return True
(_, _, hproject) = getPlugItObject(hproPk)
if not hproject:
return False
if hproject.plugItApiKey is None or hproject.plugItApiKey == '':
return False
... | def function[check_api_key, parameter[request, key, hproPk]]:
constant[Check if an API key is valid]
if name[settings].PIAPI_STANDALONE begin[:]
return[constant[True]]
<ast.Tuple object at 0x7da18f723c40> assign[=] call[name[getPlugItObject], parameter[name[hproPk]]]
if <ast.Unar... | keyword[def] identifier[check_api_key] ( identifier[request] , identifier[key] , identifier[hproPk] ):
literal[string]
keyword[if] identifier[settings] . identifier[PIAPI_STANDALONE] :
keyword[return] keyword[True]
( identifier[_] , identifier[_] , identifier[hproject] )= identifier[getPl... | def check_api_key(request, key, hproPk):
"""Check if an API key is valid"""
if settings.PIAPI_STANDALONE:
return True # depends on [control=['if'], data=[]]
(_, _, hproject) = getPlugItObject(hproPk)
if not hproject:
return False # depends on [control=['if'], data=[]]
if hproject.p... |
def compute_retrospective_loss(self):
'''
Compute retrospective loss.
Returns:
The tuple data.
- `np.ndarray` of delta.
- `np.ndarray` of losses of each batch.
- float of loss of all batch.
'''
observed_arr, encoded_arr... | def function[compute_retrospective_loss, parameter[self]]:
constant[
Compute retrospective loss.
Returns:
The tuple data.
- `np.ndarray` of delta.
- `np.ndarray` of losses of each batch.
- float of loss of all batch.
]
<ast.Tuple ... | keyword[def] identifier[compute_retrospective_loss] ( identifier[self] ):
literal[string]
identifier[observed_arr] , identifier[encoded_arr] , identifier[decoded_arr] , identifier[re_encoded_arr] = identifier[self] . identifier[__inferenced_tuple]
identifier[batch_size] = identifier[ob... | def compute_retrospective_loss(self):
"""
Compute retrospective loss.
Returns:
The tuple data.
- `np.ndarray` of delta.
- `np.ndarray` of losses of each batch.
- float of loss of all batch.
"""
(observed_arr, encoded_arr, decoded_arr, re_... |
def _check_rotated_filename_candidates(self):
"""
Check for various rotated logfile filename patterns and return the first
match we find.
"""
# savelog(8)
candidate = "%s.0" % self.filename
if (exists(candidate) and exists("%s.1.gz" % self.filename) and
... | def function[_check_rotated_filename_candidates, parameter[self]]:
constant[
Check for various rotated logfile filename patterns and return the first
match we find.
]
variable[candidate] assign[=] binary_operation[constant[%s.0] <ast.Mod object at 0x7da2590d6920> name[self].filen... | keyword[def] identifier[_check_rotated_filename_candidates] ( identifier[self] ):
literal[string]
identifier[candidate] = literal[string] % identifier[self] . identifier[filename]
keyword[if] ( identifier[exists] ( identifier[candidate] ) keyword[and] identifier[exists] ( litera... | def _check_rotated_filename_candidates(self):
"""
Check for various rotated logfile filename patterns and return the first
match we find.
"""
# savelog(8)
candidate = '%s.0' % self.filename
if exists(candidate) and exists('%s.1.gz' % self.filename) and (stat(candidate).st_mtime >... |
def fill_triangular(x, upper=False, name=None):
r"""Creates a (batch of) triangular matrix from a vector of inputs.
Created matrix can be lower- or upper-triangular. (It is more efficient to
create the matrix as upper or lower, rather than transpose.)
Triangular matrix elements are filled in a clockwise spira... | def function[fill_triangular, parameter[x, upper, name]]:
constant[Creates a (batch of) triangular matrix from a vector of inputs.
Created matrix can be lower- or upper-triangular. (It is more efficient to
create the matrix as upper or lower, rather than transpose.)
Triangular matrix elements are filled... | keyword[def] identifier[fill_triangular] ( identifier[x] , identifier[upper] = keyword[False] , identifier[name] = keyword[None] ):
literal[string]
keyword[with] identifier[tf] . identifier[name_scope] ( identifier[name] keyword[or] literal[string] ):
identifier[x] = identifier[tf] . identifier[conver... | def fill_triangular(x, upper=False, name=None):
"""Creates a (batch of) triangular matrix from a vector of inputs.
Created matrix can be lower- or upper-triangular. (It is more efficient to
create the matrix as upper or lower, rather than transpose.)
Triangular matrix elements are filled in a clockwise spir... |
def tables(self):
"""
Returns a list of table names.
Example:
>>> db.tables
["bar", "foo"]
Returns:
list of str: One string for each table name.
"""
select = ("SELECT name FROM sqlite_master",)
query = self.execute(*select)
... | def function[tables, parameter[self]]:
constant[
Returns a list of table names.
Example:
>>> db.tables
["bar", "foo"]
Returns:
list of str: One string for each table name.
]
variable[select] assign[=] tuple[[<ast.Constant object at ... | keyword[def] identifier[tables] ( identifier[self] ):
literal[string]
identifier[select] =( literal[string] ,)
identifier[query] = identifier[self] . identifier[execute] (* identifier[select] )
identifier[result] = identifier[query] . identifier[fetchall] ()
key... | def tables(self):
"""
Returns a list of table names.
Example:
>>> db.tables
["bar", "foo"]
Returns:
list of str: One string for each table name.
"""
select = ('SELECT name FROM sqlite_master',)
query = self.execute(*select)
result =... |
def identity(requestContext, name, step=60):
"""
Identity function:
Returns datapoints where the value equals the timestamp of the datapoint.
Useful when you have another series where the value is a timestamp, and
you want to compare it to the time of the datapoint, to render an age
Example::
... | def function[identity, parameter[requestContext, name, step]]:
constant[
Identity function:
Returns datapoints where the value equals the timestamp of the datapoint.
Useful when you have another series where the value is a timestamp, and
you want to compare it to the time of the datapoint, to re... | keyword[def] identifier[identity] ( identifier[requestContext] , identifier[name] , identifier[step] = literal[int] ):
literal[string]
identifier[start] = identifier[int] ( identifier[epoch] ( identifier[requestContext] [ literal[string] ]))
identifier[end] = identifier[int] ( identifier[epoch] ( iden... | def identity(requestContext, name, step=60):
"""
Identity function:
Returns datapoints where the value equals the timestamp of the datapoint.
Useful when you have another series where the value is a timestamp, and
you want to compare it to the time of the datapoint, to render an age
Example::
... |
def get_time(self, **params):
"""https://developers.coinbase.com/api/v2#time"""
response = self._get('v2', 'time', params=params)
return self._make_api_object(response, APIObject) | def function[get_time, parameter[self]]:
constant[https://developers.coinbase.com/api/v2#time]
variable[response] assign[=] call[name[self]._get, parameter[constant[v2], constant[time]]]
return[call[name[self]._make_api_object, parameter[name[response], name[APIObject]]]] | keyword[def] identifier[get_time] ( identifier[self] ,** identifier[params] ):
literal[string]
identifier[response] = identifier[self] . identifier[_get] ( literal[string] , literal[string] , identifier[params] = identifier[params] )
keyword[return] identifier[self] . identifier[_make_api... | def get_time(self, **params):
"""https://developers.coinbase.com/api/v2#time"""
response = self._get('v2', 'time', params=params)
return self._make_api_object(response, APIObject) |
def add_annotation_comment(self, doc, comment):
"""Sets the annotation comment. Raises CardinalityError if
already set. OrderError if no annotator defined before.
Raises SPDXValueError if comment is not free form text.
"""
if len(doc.annotations) != 0:
if not self.ann... | def function[add_annotation_comment, parameter[self, doc, comment]]:
constant[Sets the annotation comment. Raises CardinalityError if
already set. OrderError if no annotator defined before.
Raises SPDXValueError if comment is not free form text.
]
if compare[call[name[len], param... | keyword[def] identifier[add_annotation_comment] ( identifier[self] , identifier[doc] , identifier[comment] ):
literal[string]
keyword[if] identifier[len] ( identifier[doc] . identifier[annotations] )!= literal[int] :
keyword[if] keyword[not] identifier[self] . identifier[annotation_... | def add_annotation_comment(self, doc, comment):
"""Sets the annotation comment. Raises CardinalityError if
already set. OrderError if no annotator defined before.
Raises SPDXValueError if comment is not free form text.
"""
if len(doc.annotations) != 0:
if not self.annotation_comm... |
def boolean(input):
"""Convert the given input to a boolean value.
Intelligently handles boolean and non-string values, returning
as-is and passing to the bool builtin respectively.
This process is case-insensitive.
Acceptable values:
True
* yes
* y
* ... | def function[boolean, parameter[input]]:
constant[Convert the given input to a boolean value.
Intelligently handles boolean and non-string values, returning
as-is and passing to the bool builtin respectively.
This process is case-insensitive.
Acceptable values:
True
... | keyword[def] identifier[boolean] ( identifier[input] ):
literal[string]
keyword[try] :
identifier[input] = identifier[input] . identifier[strip] (). identifier[lower] ()
keyword[except] identifier[AttributeError] :
keyword[return] identifier[bool] ( identifier[input] )
keywo... | def boolean(input):
"""Convert the given input to a boolean value.
Intelligently handles boolean and non-string values, returning
as-is and passing to the bool builtin respectively.
This process is case-insensitive.
Acceptable values:
True
* yes
* y
* ... |
def __get_average_intra_cluster_distance(self, entry):
"""!
@brief Calculates average intra cluster distance between current and specified clusters.
@param[in] entry (cfentry): Clustering feature to which distance should be obtained.
@return (double) Average intra... | def function[__get_average_intra_cluster_distance, parameter[self, entry]]:
constant[!
@brief Calculates average intra cluster distance between current and specified clusters.
@param[in] entry (cfentry): Clustering feature to which distance should be obtained.
@return (... | keyword[def] identifier[__get_average_intra_cluster_distance] ( identifier[self] , identifier[entry] ):
literal[string]
identifier[linear_part_first] = identifier[list_math_addition] ( identifier[self] . identifier[linear_sum] , identifier[entry] . identifier[linear_sum] );
identifier... | def __get_average_intra_cluster_distance(self, entry):
"""!
@brief Calculates average intra cluster distance between current and specified clusters.
@param[in] entry (cfentry): Clustering feature to which distance should be obtained.
@return (double) Average intra cluster d... |
def clean_name(self):
"Avoid name clashes between static and dynamic attributes."
name = self.cleaned_data['name']
reserved_names = self._meta.model._meta.get_all_field_names()
if name not in reserved_names:
return name
raise ValidationError(_('Attribute name must not... | def function[clean_name, parameter[self]]:
constant[Avoid name clashes between static and dynamic attributes.]
variable[name] assign[=] call[name[self].cleaned_data][constant[name]]
variable[reserved_names] assign[=] call[name[self]._meta.model._meta.get_all_field_names, parameter[]]
if ... | keyword[def] identifier[clean_name] ( identifier[self] ):
literal[string]
identifier[name] = identifier[self] . identifier[cleaned_data] [ literal[string] ]
identifier[reserved_names] = identifier[self] . identifier[_meta] . identifier[model] . identifier[_meta] . identifier[get_all_field_... | def clean_name(self):
"""Avoid name clashes between static and dynamic attributes."""
name = self.cleaned_data['name']
reserved_names = self._meta.model._meta.get_all_field_names()
if name not in reserved_names:
return name # depends on [control=['if'], data=['name']]
raise ValidationError(... |
def _collapse_cursor(self, parts):
""" Act on any CursorMoveUp commands by deleting preceding tokens """
final_parts = []
for part in parts:
# Throw out empty string tokens ("")
if not part:
continue
# Go back, deleting every token in the la... | def function[_collapse_cursor, parameter[self, parts]]:
constant[ Act on any CursorMoveUp commands by deleting preceding tokens ]
variable[final_parts] assign[=] list[[]]
for taget[name[part]] in starred[name[parts]] begin[:]
if <ast.UnaryOp object at 0x7da1b12920b0> begin[:]
... | keyword[def] identifier[_collapse_cursor] ( identifier[self] , identifier[parts] ):
literal[string]
identifier[final_parts] =[]
keyword[for] identifier[part] keyword[in] identifier[parts] :
keyword[if] keyword[not] identifier[part] :
keyword[co... | def _collapse_cursor(self, parts):
""" Act on any CursorMoveUp commands by deleting preceding tokens """
final_parts = []
for part in parts:
# Throw out empty string tokens ("")
if not part:
continue # depends on [control=['if'], data=[]]
# Go back, deleting every token ... |
def convert_batchnorm(net, node, module, builder):
"""Convert a batchnorm layer from mxnet to coreml.
Parameters
----------
network: net
A mxnet network object.
layer: node
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
A... | def function[convert_batchnorm, parameter[net, node, module, builder]]:
constant[Convert a batchnorm layer from mxnet to coreml.
Parameters
----------
network: net
A mxnet network object.
layer: node
Node to convert.
module: module
An module for MXNet
builder:... | keyword[def] identifier[convert_batchnorm] ( identifier[net] , identifier[node] , identifier[module] , identifier[builder] ):
literal[string]
identifier[input_name] , identifier[output_name] = identifier[_get_input_output_name] ( identifier[net] , identifier[node] )
identifier[name] = identifier[node]... | def convert_batchnorm(net, node, module, builder):
"""Convert a batchnorm layer from mxnet to coreml.
Parameters
----------
network: net
A mxnet network object.
layer: node
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
A... |
def _get_xml(xml_str):
'''
Intrepret the data coming from opennebula and raise if it's not XML.
'''
try:
xml_data = etree.XML(xml_str)
# XMLSyntaxError seems to be only available from lxml, but that is the xml
# library loaded by this module
except etree.XMLSyntaxError as err:
... | def function[_get_xml, parameter[xml_str]]:
constant[
Intrepret the data coming from opennebula and raise if it's not XML.
]
<ast.Try object at 0x7da18bc70550>
return[name[xml_data]] | keyword[def] identifier[_get_xml] ( identifier[xml_str] ):
literal[string]
keyword[try] :
identifier[xml_data] = identifier[etree] . identifier[XML] ( identifier[xml_str] )
keyword[except] identifier[etree] . identifier[XMLSyntaxError] keyword[as] identifier[err] :
... | def _get_xml(xml_str):
"""
Intrepret the data coming from opennebula and raise if it's not XML.
"""
try:
xml_data = etree.XML(xml_str) # depends on [control=['try'], data=[]]
# XMLSyntaxError seems to be only available from lxml, but that is the xml
# library loaded by this module
e... |
def print_tree(root, child_func, prune=0, showtags=0, margin=[0], visited=None):
"""
Print a tree of nodes. This is like render_tree, except it prints
lines directly instead of creating a string representation in memory,
so that huge trees can be printed.
:Parameters:
- `root` - the ... | def function[print_tree, parameter[root, child_func, prune, showtags, margin, visited]]:
constant[
Print a tree of nodes. This is like render_tree, except it prints
lines directly instead of creating a string representation in memory,
so that huge trees can be printed.
:Parameters:
- `... | keyword[def] identifier[print_tree] ( identifier[root] , identifier[child_func] , identifier[prune] = literal[int] , identifier[showtags] = literal[int] , identifier[margin] =[ literal[int] ], identifier[visited] = keyword[None] ):
literal[string]
identifier[rname] = identifier[str] ( identifier[root] )
... | def print_tree(root, child_func, prune=0, showtags=0, margin=[0], visited=None):
"""
Print a tree of nodes. This is like render_tree, except it prints
lines directly instead of creating a string representation in memory,
so that huge trees can be printed.
:Parameters:
- `root` - the ... |
def qteGetVariableDoc(self, varName: str, module=None):
"""
Retrieve documentation for ``varName`` defined in ``module``.
If ``module`` is **None** then ``qte_global`` will be used.
|Args|
* ``varName`` (**str**): variable name.
* ``module`` (**Python module**): the mo... | def function[qteGetVariableDoc, parameter[self, varName, module]]:
constant[
Retrieve documentation for ``varName`` defined in ``module``.
If ``module`` is **None** then ``qte_global`` will be used.
|Args|
* ``varName`` (**str**): variable name.
* ``module`` (**Python ... | keyword[def] identifier[qteGetVariableDoc] ( identifier[self] , identifier[varName] : identifier[str] , identifier[module] = keyword[None] ):
literal[string]
keyword[if] identifier[module] keyword[is] keyword[None] :
identifier[module] = identifier[qte_global]
... | def qteGetVariableDoc(self, varName: str, module=None):
"""
Retrieve documentation for ``varName`` defined in ``module``.
If ``module`` is **None** then ``qte_global`` will be used.
|Args|
* ``varName`` (**str**): variable name.
* ``module`` (**Python module**): the module... |
def setup_prjs_page(self, ):
"""Create and set the model on the projects page
:returns: None
:rtype: None
:raises: None
"""
self.prjs_tablev.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents)
log.debug("Loading projects for projects page.")
... | def function[setup_prjs_page, parameter[self]]:
constant[Create and set the model on the projects page
:returns: None
:rtype: None
:raises: None
]
call[call[name[self].prjs_tablev.horizontalHeader, parameter[]].setResizeMode, parameter[name[QtGui].QHeaderView.ResizeToCon... | keyword[def] identifier[setup_prjs_page] ( identifier[self] ,):
literal[string]
identifier[self] . identifier[prjs_tablev] . identifier[horizontalHeader] (). identifier[setResizeMode] ( identifier[QtGui] . identifier[QHeaderView] . identifier[ResizeToContents] )
identifier[log] . identifie... | def setup_prjs_page(self):
"""Create and set the model on the projects page
:returns: None
:rtype: None
:raises: None
"""
self.prjs_tablev.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents)
log.debug('Loading projects for projects page.')
rootdata = tre... |
def preprocess_ubuntu_corpus(df):
"""Split all strings in df.Context and df.Utterance on __eot__ (turn) markers """
statements = []
replies = []
for i, record in tqdm(df.iterrows()):
turns = list(split_turns(record.Context))
statement = turns[-1] if len(turns) else '\n' # <1>
st... | def function[preprocess_ubuntu_corpus, parameter[df]]:
constant[Split all strings in df.Context and df.Utterance on __eot__ (turn) markers ]
variable[statements] assign[=] list[[]]
variable[replies] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da18f8130d0>, <ast.Name object... | keyword[def] identifier[preprocess_ubuntu_corpus] ( identifier[df] ):
literal[string]
identifier[statements] =[]
identifier[replies] =[]
keyword[for] identifier[i] , identifier[record] keyword[in] identifier[tqdm] ( identifier[df] . identifier[iterrows] ()):
identifier[turns] = identi... | def preprocess_ubuntu_corpus(df):
"""Split all strings in df.Context and df.Utterance on __eot__ (turn) markers """
statements = []
replies = []
for (i, record) in tqdm(df.iterrows()):
turns = list(split_turns(record.Context))
statement = turns[-1] if len(turns) else '\n' # <1>
... |
def mount(self, app, script_path):
''' Mount a Bottle application to a specific URL prefix '''
if not isinstance(app, Bottle):
raise TypeError('Only Bottle instances are supported for now.')
script_path = '/'.join(filter(None, script_path.split('/')))
path_depth = script_path... | def function[mount, parameter[self, app, script_path]]:
constant[ Mount a Bottle application to a specific URL prefix ]
if <ast.UnaryOp object at 0x7da20c6e6980> begin[:]
<ast.Raise object at 0x7da20c6e5750>
variable[script_path] assign[=] call[constant[/].join, parameter[call[name[filte... | keyword[def] identifier[mount] ( identifier[self] , identifier[app] , identifier[script_path] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[app] , identifier[Bottle] ):
keyword[raise] identifier[TypeError] ( literal[string] )
identifier[scr... | def mount(self, app, script_path):
""" Mount a Bottle application to a specific URL prefix """
if not isinstance(app, Bottle):
raise TypeError('Only Bottle instances are supported for now.') # depends on [control=['if'], data=[]]
script_path = '/'.join(filter(None, script_path.split('/')))
path... |
def add_virtual_columns_equatorial_to_galactic_cartesian(self, alpha, delta, distance, xname, yname, zname, radians=True, alpha_gp=np.radians(192.85948), delta_gp=np.radians(27.12825), l_omega=np.radians(32.93192)):
"""From http://arxiv.org/pdf/1306.2945v2.pdf"""
if not radians:
alpha = "pi/180.*%s" % a... | def function[add_virtual_columns_equatorial_to_galactic_cartesian, parameter[self, alpha, delta, distance, xname, yname, zname, radians, alpha_gp, delta_gp, l_omega]]:
constant[From http://arxiv.org/pdf/1306.2945v2.pdf]
if <ast.UnaryOp object at 0x7da1b2345ab0> begin[:]
variable[alpha] a... | keyword[def] identifier[add_virtual_columns_equatorial_to_galactic_cartesian] ( identifier[self] , identifier[alpha] , identifier[delta] , identifier[distance] , identifier[xname] , identifier[yname] , identifier[zname] , identifier[radians] = keyword[True] , identifier[alpha_gp] = identifier[np] . identifier[radians... | def add_virtual_columns_equatorial_to_galactic_cartesian(self, alpha, delta, distance, xname, yname, zname, radians=True, alpha_gp=np.radians(192.85948), delta_gp=np.radians(27.12825), l_omega=np.radians(32.93192)):
"""From http://arxiv.org/pdf/1306.2945v2.pdf"""
if not radians:
alpha = 'pi/180.*%s' % a... |
def get_input_files(self):
"""
Return list of input files for this DAG node and its job.
"""
input_files = list(self.__input_files)
if isinstance(self.job(), CondorDAGJob):
input_files = input_files + self.job().get_input_files()
return input_files | def function[get_input_files, parameter[self]]:
constant[
Return list of input files for this DAG node and its job.
]
variable[input_files] assign[=] call[name[list], parameter[name[self].__input_files]]
if call[name[isinstance], parameter[call[name[self].job, parameter[]], name[CondorDA... | keyword[def] identifier[get_input_files] ( identifier[self] ):
literal[string]
identifier[input_files] = identifier[list] ( identifier[self] . identifier[__input_files] )
keyword[if] identifier[isinstance] ( identifier[self] . identifier[job] (), identifier[CondorDAGJob] ):
identifier[input_fi... | def get_input_files(self):
"""
Return list of input files for this DAG node and its job.
"""
input_files = list(self.__input_files)
if isinstance(self.job(), CondorDAGJob):
input_files = input_files + self.job().get_input_files() # depends on [control=['if'], data=[]]
return input_files |
def mdr_mutual_information(X, Y, labels, base=2):
"""Calculates the MDR mutual information, I(XY;labels), in the given base
MDR mutual information is calculated by combining variables X and Y into a single MDR model then calculating
the mutual information between the resulting model's predictions and the l... | def function[mdr_mutual_information, parameter[X, Y, labels, base]]:
constant[Calculates the MDR mutual information, I(XY;labels), in the given base
MDR mutual information is calculated by combining variables X and Y into a single MDR model then calculating
the mutual information between the resulting ... | keyword[def] identifier[mdr_mutual_information] ( identifier[X] , identifier[Y] , identifier[labels] , identifier[base] = literal[int] ):
literal[string]
keyword[return] identifier[mutual_information] ( identifier[_mdr_predict] ( identifier[X] , identifier[Y] , identifier[labels] ), identifier[labels] , i... | def mdr_mutual_information(X, Y, labels, base=2):
"""Calculates the MDR mutual information, I(XY;labels), in the given base
MDR mutual information is calculated by combining variables X and Y into a single MDR model then calculating
the mutual information between the resulting model's predictions and the l... |
def submit(self, executor, task, tag=None):
"""Submits a task to a provided executor
:type executor: s3transfer.futures.BoundedExecutor
:param executor: The executor to submit the callable to
:type task: s3transfer.tasks.Task
:param task: The task to submit to the executor
... | def function[submit, parameter[self, executor, task, tag]]:
constant[Submits a task to a provided executor
:type executor: s3transfer.futures.BoundedExecutor
:param executor: The executor to submit the callable to
:type task: s3transfer.tasks.Task
:param task: The task to submi... | keyword[def] identifier[submit] ( identifier[self] , identifier[executor] , identifier[task] , identifier[tag] = keyword[None] ):
literal[string]
identifier[logger] . identifier[debug] (
literal[string] %(
identifier[task] , identifier[executor] , identifier[self] . identifier[tra... | def submit(self, executor, task, tag=None):
"""Submits a task to a provided executor
:type executor: s3transfer.futures.BoundedExecutor
:param executor: The executor to submit the callable to
:type task: s3transfer.tasks.Task
:param task: The task to submit to the executor
... |
def register_actor(name, actor_handle):
"""Register a named actor under a string key.
Args:
name: The name of the named actor.
actor_handle: The actor object to be associated with this name
"""
if not isinstance(name, str):
raise TypeError("The name argument must be a string.")
... | def function[register_actor, parameter[name, actor_handle]]:
constant[Register a named actor under a string key.
Args:
name: The name of the named actor.
actor_handle: The actor object to be associated with this name
]
if <ast.UnaryOp object at 0x7da20e9b1c90> begin[:]
<ast.... | keyword[def] identifier[register_actor] ( identifier[name] , identifier[actor_handle] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[name] , identifier[str] ):
keyword[raise] identifier[TypeError] ( literal[string] )
keyword[if] keyword[not] identifier[is... | def register_actor(name, actor_handle):
"""Register a named actor under a string key.
Args:
name: The name of the named actor.
actor_handle: The actor object to be associated with this name
"""
if not isinstance(name, str):
raise TypeError('The name argument must be a string.') # d... |
def build_cpp(build_context, target, compiler_config, workspace_dir):
"""Compile and link a C++ binary for `target`."""
rmtree(workspace_dir)
binary = join(*split(target.name))
objects = link_cpp_artifacts(build_context, target, workspace_dir, True)
buildenv_workspace = build_context.conf.host_to_bu... | def function[build_cpp, parameter[build_context, target, compiler_config, workspace_dir]]:
constant[Compile and link a C++ binary for `target`.]
call[name[rmtree], parameter[name[workspace_dir]]]
variable[binary] assign[=] call[name[join], parameter[<ast.Starred object at 0x7da1b1b68460>]]
... | keyword[def] identifier[build_cpp] ( identifier[build_context] , identifier[target] , identifier[compiler_config] , identifier[workspace_dir] ):
literal[string]
identifier[rmtree] ( identifier[workspace_dir] )
identifier[binary] = identifier[join] (* identifier[split] ( identifier[target] . identifier... | def build_cpp(build_context, target, compiler_config, workspace_dir):
"""Compile and link a C++ binary for `target`."""
rmtree(workspace_dir)
binary = join(*split(target.name))
objects = link_cpp_artifacts(build_context, target, workspace_dir, True)
buildenv_workspace = build_context.conf.host_to_bu... |
def get_version(version=None):
"""Returns a PEP 386-compliant version number from VERSION.
:param version: A tuple that represent a version.
:type version: tuple
:returns: a PEP 386-compliant version number.
:rtype: str
"""
if version is None:
version_list = inasafe_version.split(... | def function[get_version, parameter[version]]:
constant[Returns a PEP 386-compliant version number from VERSION.
:param version: A tuple that represent a version.
:type version: tuple
:returns: a PEP 386-compliant version number.
:rtype: str
]
if compare[name[version] is constant[... | keyword[def] identifier[get_version] ( identifier[version] = keyword[None] ):
literal[string]
keyword[if] identifier[version] keyword[is] keyword[None] :
identifier[version_list] = identifier[inasafe_version] . identifier[split] ( literal[string] )
identifier[version] = identifier[tupl... | def get_version(version=None):
"""Returns a PEP 386-compliant version number from VERSION.
:param version: A tuple that represent a version.
:type version: tuple
:returns: a PEP 386-compliant version number.
:rtype: str
"""
if version is None:
version_list = inasafe_version.split(... |
def get_latex_expression(self, pos, strict_braces=None):
"""
Parses the latex content given to the constructor (and stored in `self.s`),
starting at position `pos`, to parse a single LaTeX expression.
Reads a latex expression, e.g. macro argument. This may be a single char, an escape
... | def function[get_latex_expression, parameter[self, pos, strict_braces]]:
constant[
Parses the latex content given to the constructor (and stored in `self.s`),
starting at position `pos`, to parse a single LaTeX expression.
Reads a latex expression, e.g. macro argument. This may be a sin... | keyword[def] identifier[get_latex_expression] ( identifier[self] , identifier[pos] , identifier[strict_braces] = keyword[None] ):
literal[string]
keyword[with] identifier[_PushPropOverride] ( identifier[self] , literal[string] , identifier[strict_braces] ):
identifier[tok] = identif... | def get_latex_expression(self, pos, strict_braces=None):
"""
Parses the latex content given to the constructor (and stored in `self.s`),
starting at position `pos`, to parse a single LaTeX expression.
Reads a latex expression, e.g. macro argument. This may be a single char, an escape
... |
def is_chief(task: backend.Task, run_name: str):
"""Returns True if task is chief task in the corresponding run"""
global run_task_dict
if run_name not in run_task_dict:
return True
task_list = run_task_dict[run_name]
assert task in task_list, f"Task {task.name} doesn't belong to run {run_name}"
return ... | def function[is_chief, parameter[task, run_name]]:
constant[Returns True if task is chief task in the corresponding run]
<ast.Global object at 0x7da2054a4d90>
if compare[name[run_name] <ast.NotIn object at 0x7da2590d7190> name[run_task_dict]] begin[:]
return[constant[True]]
variable[... | keyword[def] identifier[is_chief] ( identifier[task] : identifier[backend] . identifier[Task] , identifier[run_name] : identifier[str] ):
literal[string]
keyword[global] identifier[run_task_dict]
keyword[if] identifier[run_name] keyword[not] keyword[in] identifier[run_task_dict] :
keyword[return]... | def is_chief(task: backend.Task, run_name: str):
"""Returns True if task is chief task in the corresponding run"""
global run_task_dict
if run_name not in run_task_dict:
return True # depends on [control=['if'], data=[]]
task_list = run_task_dict[run_name]
assert task in task_list, f"Task {... |
def on_pytoml_dumps(self, pytoml, config, dictionary, **kwargs):
""" The `pytoml <https://pypi.org/project/pytoml/>`_ dumps method.
:param module pytoml: The ``pytoml`` module
:param class config: The instance's config class
:param dict dictionary: The dictionary to serialize
:r... | def function[on_pytoml_dumps, parameter[self, pytoml, config, dictionary]]:
constant[ The `pytoml <https://pypi.org/project/pytoml/>`_ dumps method.
:param module pytoml: The ``pytoml`` module
:param class config: The instance's config class
:param dict dictionary: The dictionary to ser... | keyword[def] identifier[on_pytoml_dumps] ( identifier[self] , identifier[pytoml] , identifier[config] , identifier[dictionary] ,** identifier[kwargs] ):
literal[string]
identifier[inline_tables] = identifier[set] ( identifier[kwargs] . identifier[get] ( literal[string] ,[]))
keyword[if] ... | def on_pytoml_dumps(self, pytoml, config, dictionary, **kwargs):
""" The `pytoml <https://pypi.org/project/pytoml/>`_ dumps method.
:param module pytoml: The ``pytoml`` module
:param class config: The instance's config class
:param dict dictionary: The dictionary to serialize
:retur... |
def compare_token(expected: Union[str, bytes],
actual: Union[str, bytes]) -> bool:
"""
Compares the given tokens.
:param expected: The expected token.
:type expected: Union[str, bytes]
:param actual: The actual token.
:type actual: Union[str, bytes]
:return: Do the tokens ... | def function[compare_token, parameter[expected, actual]]:
constant[
Compares the given tokens.
:param expected: The expected token.
:type expected: Union[str, bytes]
:param actual: The actual token.
:type actual: Union[str, bytes]
:return: Do the tokens match?
:rtype: bool
]
... | keyword[def] identifier[compare_token] ( identifier[expected] : identifier[Union] [ identifier[str] , identifier[bytes] ],
identifier[actual] : identifier[Union] [ identifier[str] , identifier[bytes] ])-> identifier[bool] :
literal[string]
identifier[expected] = identifier[util] . identifier[to_bytes] ( i... | def compare_token(expected: Union[str, bytes], actual: Union[str, bytes]) -> bool:
"""
Compares the given tokens.
:param expected: The expected token.
:type expected: Union[str, bytes]
:param actual: The actual token.
:type actual: Union[str, bytes]
:return: Do the tokens match?
:rtype:... |
def _recursive_import(package):
"""
Args:
package(py:term:`package`): Package to walk
Import all modules from a package recursively
"""
prefix = '%s.' % (package.__name__)
path = getattr(package, '__path__', None)
if path:
for submod in pkgutil.walk_packages(path, prefix=... | def function[_recursive_import, parameter[package]]:
constant[
Args:
package(py:term:`package`): Package to walk
Import all modules from a package recursively
]
variable[prefix] assign[=] binary_operation[constant[%s.] <ast.Mod object at 0x7da2590d6920> name[package].__name__]
... | keyword[def] identifier[_recursive_import] ( identifier[package] ):
literal[string]
identifier[prefix] = literal[string] %( identifier[package] . identifier[__name__] )
identifier[path] = identifier[getattr] ( identifier[package] , literal[string] , keyword[None] )
keyword[if] identifier[path... | def _recursive_import(package):
"""
Args:
package(py:term:`package`): Package to walk
Import all modules from a package recursively
"""
prefix = '%s.' % package.__name__
path = getattr(package, '__path__', None)
if path:
for submod in pkgutil.walk_packages(path, prefix=prefi... |
def get(self, id):
"""Retrieves the job with the selected ID.
:param str id: The ID of the job
:returns: The dictionary of the job if found, None otherwise
"""
self.cur.execute("SELECT * FROM jobs WHERE hash=?", (id,))
item = self.cur.fetchone()
if item:
... | def function[get, parameter[self, id]]:
constant[Retrieves the job with the selected ID.
:param str id: The ID of the job
:returns: The dictionary of the job if found, None otherwise
]
call[name[self].cur.execute, parameter[constant[SELECT * FROM jobs WHERE hash=?], tuple[[<ast.N... | keyword[def] identifier[get] ( identifier[self] , identifier[id] ):
literal[string]
identifier[self] . identifier[cur] . identifier[execute] ( literal[string] ,( identifier[id] ,))
identifier[item] = identifier[self] . identifier[cur] . identifier[fetchone] ()
keyword[if] identif... | def get(self, id):
"""Retrieves the job with the selected ID.
:param str id: The ID of the job
:returns: The dictionary of the job if found, None otherwise
"""
self.cur.execute('SELECT * FROM jobs WHERE hash=?', (id,))
item = self.cur.fetchone()
if item:
return dict(zip((... |
def __PrintMessageDocstringLines(self, message_type):
"""Print the docstring for this message."""
description = message_type.description or '%s message type.' % (
message_type.name)
short_description = (
_EmptyMessage(message_type) and
len(description) < (self... | def function[__PrintMessageDocstringLines, parameter[self, message_type]]:
constant[Print the docstring for this message.]
variable[description] assign[=] <ast.BoolOp object at 0x7da1b07f5630>
variable[short_description] assign[=] <ast.BoolOp object at 0x7da1b07f4e80>
with call[name[self... | keyword[def] identifier[__PrintMessageDocstringLines] ( identifier[self] , identifier[message_type] ):
literal[string]
identifier[description] = identifier[message_type] . identifier[description] keyword[or] literal[string] %(
identifier[message_type] . identifier[name] )
identi... | def __PrintMessageDocstringLines(self, message_type):
"""Print the docstring for this message."""
description = message_type.description or '%s message type.' % message_type.name
short_description = _EmptyMessage(message_type) and len(description) < self.__printer.CalculateWidth() - 6
with self.__printe... |
def flow_pipemajor(Diam, HeadLossFric, Length, Nu, PipeRough):
"""Return the flow rate with only major losses.
This function applies to both laminar and turbulent flows.
"""
#Inputs do not need to be checked here because they are checked by
#functions this function calls.
FlowHagen = flow_hagen... | def function[flow_pipemajor, parameter[Diam, HeadLossFric, Length, Nu, PipeRough]]:
constant[Return the flow rate with only major losses.
This function applies to both laminar and turbulent flows.
]
variable[FlowHagen] assign[=] call[name[flow_hagen], parameter[name[Diam], name[HeadLossFric], n... | keyword[def] identifier[flow_pipemajor] ( identifier[Diam] , identifier[HeadLossFric] , identifier[Length] , identifier[Nu] , identifier[PipeRough] ):
literal[string]
identifier[FlowHagen] = identifier[flow_hagen] ( identifier[Diam] , identifier[HeadLossFric] , identifier[Length] , identifier[Nu]... | def flow_pipemajor(Diam, HeadLossFric, Length, Nu, PipeRough):
"""Return the flow rate with only major losses.
This function applies to both laminar and turbulent flows.
"""
#Inputs do not need to be checked here because they are checked by
#functions this function calls.
FlowHagen = flow_hagen... |
def validate_boundary(reference_intervals, estimated_intervals, trim):
"""Checks that the input annotations to a segment boundary estimation
metric (i.e. one that only takes in segment intervals) look like valid
segment times, and throws helpful errors if not.
Parameters
----------
reference_in... | def function[validate_boundary, parameter[reference_intervals, estimated_intervals, trim]]:
constant[Checks that the input annotations to a segment boundary estimation
metric (i.e. one that only takes in segment intervals) look like valid
segment times, and throws helpful errors if not.
Parameters
... | keyword[def] identifier[validate_boundary] ( identifier[reference_intervals] , identifier[estimated_intervals] , identifier[trim] ):
literal[string]
keyword[if] identifier[trim] :
identifier[min_size] = literal[int]
keyword[else] :
identifier[min_size] = literal[int]
... | def validate_boundary(reference_intervals, estimated_intervals, trim):
"""Checks that the input annotations to a segment boundary estimation
metric (i.e. one that only takes in segment intervals) look like valid
segment times, and throws helpful errors if not.
Parameters
----------
reference_in... |
def to_seconds(value, strict=True, force_int=True):
"""
converts duration value to integer seconds
strict=True (by default) raises StrictnessError if either hours,
minutes or seconds in duration value exceed allowed values
"""
if isinstance(value, int):
return value # assuming it's sec... | def function[to_seconds, parameter[value, strict, force_int]]:
constant[
converts duration value to integer seconds
strict=True (by default) raises StrictnessError if either hours,
minutes or seconds in duration value exceed allowed values
]
if call[name[isinstance], parameter[name[valu... | keyword[def] identifier[to_seconds] ( identifier[value] , identifier[strict] = keyword[True] , identifier[force_int] = keyword[True] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[value] , identifier[int] ):
keyword[return] identifier[value]
keyword[elif] identifier[is... | def to_seconds(value, strict=True, force_int=True):
"""
converts duration value to integer seconds
strict=True (by default) raises StrictnessError if either hours,
minutes or seconds in duration value exceed allowed values
"""
if isinstance(value, int):
return value # assuming it's sec... |
def sample(self, image):
"""sample(image) -> bounding_box
Yields an iterator over all bounding boxes in different scales that are sampled for the given image.
**Parameters:**
``image`` : array_like(2D or 3D)
The image, for which the bounding boxes should be generated
**Yields:**
``bou... | def function[sample, parameter[self, image]]:
constant[sample(image) -> bounding_box
Yields an iterator over all bounding boxes in different scales that are sampled for the given image.
**Parameters:**
``image`` : array_like(2D or 3D)
The image, for which the bounding boxes should be genera... | keyword[def] identifier[sample] ( identifier[self] , identifier[image] ):
literal[string]
keyword[for] identifier[scale] , identifier[scaled_image_shape] keyword[in] identifier[self] . identifier[scales] ( identifier[image] ):
keyword[for] identifier[bb] keyword[in] identifier[self] . ide... | def sample(self, image):
"""sample(image) -> bounding_box
Yields an iterator over all bounding boxes in different scales that are sampled for the given image.
**Parameters:**
``image`` : array_like(2D or 3D)
The image, for which the bounding boxes should be generated
**Yields:**
``bou... |
def wait_until_invisibility_of(self, locator, timeout=None):
"""
Waits for an element to be invisible
@type locator: webdriverwrapper.support.locator.Locator
@param locator: the locator or css string to search for the element
@type timeout: int
@param timeout: the max... | def function[wait_until_invisibility_of, parameter[self, locator, timeout]]:
constant[
Waits for an element to be invisible
@type locator: webdriverwrapper.support.locator.Locator
@param locator: the locator or css string to search for the element
@type timeout: int
@p... | keyword[def] identifier[wait_until_invisibility_of] ( identifier[self] , identifier[locator] , identifier[timeout] = keyword[None] ):
literal[string]
identifier[timeout] = identifier[timeout] keyword[if] identifier[timeout] keyword[is] keyword[not] keyword[None] keyword[else] identifier[self... | def wait_until_invisibility_of(self, locator, timeout=None):
"""
Waits for an element to be invisible
@type locator: webdriverwrapper.support.locator.Locator
@param locator: the locator or css string to search for the element
@type timeout: int
@param timeout: the maximum... |
def default_mean_field_normal_fn(
is_singular=False,
loc_initializer=tf.compat.v1.initializers.random_normal(stddev=0.1),
untransformed_scale_initializer=tf.compat.v1.initializers.random_normal(
mean=-3., stddev=0.1),
loc_regularizer=None,
untransformed_scale_regularizer=None,
loc_constr... | def function[default_mean_field_normal_fn, parameter[is_singular, loc_initializer, untransformed_scale_initializer, loc_regularizer, untransformed_scale_regularizer, loc_constraint, untransformed_scale_constraint]]:
constant[Creates a function to build Normal distributions with trainable params.
This functio... | keyword[def] identifier[default_mean_field_normal_fn] (
identifier[is_singular] = keyword[False] ,
identifier[loc_initializer] = identifier[tf] . identifier[compat] . identifier[v1] . identifier[initializers] . identifier[random_normal] ( identifier[stddev] = literal[int] ),
identifier[untransformed_scale_initiali... | def default_mean_field_normal_fn(is_singular=False, loc_initializer=tf.compat.v1.initializers.random_normal(stddev=0.1), untransformed_scale_initializer=tf.compat.v1.initializers.random_normal(mean=-3.0, stddev=0.1), loc_regularizer=None, untransformed_scale_regularizer=None, loc_constraint=None, untransformed_scale_co... |
def device_is_attached_to_network(device, network_name):
"""
Checks if the device has a backing with of the right network name
:param <vim.vm.Device> device: instance of adapter
:param <str> network_name: network name
:return:
"""
try:
backing = device... | def function[device_is_attached_to_network, parameter[device, network_name]]:
constant[
Checks if the device has a backing with of the right network name
:param <vim.vm.Device> device: instance of adapter
:param <str> network_name: network name
:return:
]
<ast.Try obj... | keyword[def] identifier[device_is_attached_to_network] ( identifier[device] , identifier[network_name] ):
literal[string]
keyword[try] :
identifier[backing] = identifier[device] . identifier[backing]
keyword[except] :
keyword[return] keyword[False]
key... | def device_is_attached_to_network(device, network_name):
"""
Checks if the device has a backing with of the right network name
:param <vim.vm.Device> device: instance of adapter
:param <str> network_name: network name
:return:
"""
try:
backing = device.backing # ... |
def parse_options():
"""
Parses command-line options.
"""
try:
opts, args = getopt.getopt(sys.argv[1:], 'hms:v', ['help', 'model', 'solver=', 'verbose'])
except getopt.GetoptError as err:
sys.stderr.write(str(err).capitalize())
print_usage()
sys.exit(1)
solv... | def function[parse_options, parameter[]]:
constant[
Parses command-line options.
]
<ast.Try object at 0x7da1b119fe50>
variable[solver] assign[=] constant[g4]
variable[verbose] assign[=] constant[1]
variable[print_model] assign[=] constant[False]
for taget[tuple[[<... | keyword[def] identifier[parse_options] ():
literal[string]
keyword[try] :
identifier[opts] , identifier[args] = identifier[getopt] . identifier[getopt] ( identifier[sys] . identifier[argv] [ literal[int] :], literal[string] ,[ literal[string] , literal[string] , literal[string] , literal[string] ... | def parse_options():
"""
Parses command-line options.
"""
try:
(opts, args) = getopt.getopt(sys.argv[1:], 'hms:v', ['help', 'model', 'solver=', 'verbose']) # depends on [control=['try'], data=[]]
except getopt.GetoptError as err:
sys.stderr.write(str(err).capitalize())
p... |
def make_serviceitem_name(name, condition='is', negate=False, preserve_case=False):
"""
Create a node for ServiceItem/name
:return: A IndicatorItem represented as an Element node
"""
document = 'ServiceItem'
search = 'ServiceItem/name'
content_type = 'string'
content = name
ii_n... | def function[make_serviceitem_name, parameter[name, condition, negate, preserve_case]]:
constant[
Create a node for ServiceItem/name
:return: A IndicatorItem represented as an Element node
]
variable[document] assign[=] constant[ServiceItem]
variable[search] assign[=] constant[S... | keyword[def] identifier[make_serviceitem_name] ( identifier[name] , identifier[condition] = literal[string] , identifier[negate] = keyword[False] , identifier[preserve_case] = keyword[False] ):
literal[string]
identifier[document] = literal[string]
identifier[search] = literal[string]
identifie... | def make_serviceitem_name(name, condition='is', negate=False, preserve_case=False):
"""
Create a node for ServiceItem/name
:return: A IndicatorItem represented as an Element node
"""
document = 'ServiceItem'
search = 'ServiceItem/name'
content_type = 'string'
content = name
ii_n... |
def login():
"""
This route has two purposes. First, it is used by the user
to login. Second, it is used by the CAS to respond with the
`ticket` after the user logs in successfully.
When the user accesses this url, they are redirected to the CAS
to login. If the login was successful, the CAS wi... | def function[login, parameter[]]:
constant[
This route has two purposes. First, it is used by the user
to login. Second, it is used by the CAS to respond with the
`ticket` after the user logs in successfully.
When the user accesses this url, they are redirected to the CAS
to login. If the l... | keyword[def] identifier[login] ():
literal[string]
identifier[cas_token_session_key] = identifier[current_app] . identifier[config] [ literal[string] ]
identifier[redirect_url] = identifier[create_cas_login_url] (
identifier[current_app] . identifier[config] [ literal[string] ],
identifier... | def login():
"""
This route has two purposes. First, it is used by the user
to login. Second, it is used by the CAS to respond with the
`ticket` after the user logs in successfully.
When the user accesses this url, they are redirected to the CAS
to login. If the login was successful, the CAS wi... |
def stop_capture(self, port_number):
"""
Stops a packet capture.
:param port_number: port number
"""
if not self._ethernet_adapter.port_exists(port_number):
raise VPCSError("Port {port_number} doesn't exist in adapter {adapter}".format(adapter=self._ethernet_adapter... | def function[stop_capture, parameter[self, port_number]]:
constant[
Stops a packet capture.
:param port_number: port number
]
if <ast.UnaryOp object at 0x7da2044c1240> begin[:]
<ast.Raise object at 0x7da20e955570>
variable[nio] assign[=] call[name[self]._ethernet... | keyword[def] identifier[stop_capture] ( identifier[self] , identifier[port_number] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_ethernet_adapter] . identifier[port_exists] ( identifier[port_number] ):
keyword[raise] identifier[VPCSError] ( literal[stri... | def stop_capture(self, port_number):
"""
Stops a packet capture.
:param port_number: port number
"""
if not self._ethernet_adapter.port_exists(port_number):
raise VPCSError("Port {port_number} doesn't exist in adapter {adapter}".format(adapter=self._ethernet_adapter, port_number... |
def update(self, pbar):
'Updates the widget to show the ETA or total time when finished.'
if pbar.currval == 0:
return 'ETA: --:--:--'
elif pbar.finished:
return 'Time: %s' % self.format_time(pbar.seconds_elapsed)
else:
return 'ETA: %s' % self.forma... | def function[update, parameter[self, pbar]]:
constant[Updates the widget to show the ETA or total time when finished.]
if compare[name[pbar].currval equal[==] constant[0]] begin[:]
return[constant[ETA: --:--:--]] | keyword[def] identifier[update] ( identifier[self] , identifier[pbar] ):
literal[string]
keyword[if] identifier[pbar] . identifier[currval] == literal[int] :
keyword[return] literal[string]
keyword[elif] identifier[pbar] . identifier[finished] :
keyword[retur... | def update(self, pbar):
"""Updates the widget to show the ETA or total time when finished."""
if pbar.currval == 0:
return 'ETA: --:--:--' # depends on [control=['if'], data=[]]
elif pbar.finished:
return 'Time: %s' % self.format_time(pbar.seconds_elapsed) # depends on [control=['if'], da... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.