code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _tr_above(self):
"""
The tr element prior in sequence to the tr this cell appears in.
Raises |ValueError| if called on a cell in the top-most row.
"""
tr_lst = self._tbl.tr_lst
tr_idx = tr_lst.index(self._tr)
if tr_idx == 0:
raise ValueError('no tr... | def function[_tr_above, parameter[self]]:
constant[
The tr element prior in sequence to the tr this cell appears in.
Raises |ValueError| if called on a cell in the top-most row.
]
variable[tr_lst] assign[=] name[self]._tbl.tr_lst
variable[tr_idx] assign[=] call[name[tr_ls... | keyword[def] identifier[_tr_above] ( identifier[self] ):
literal[string]
identifier[tr_lst] = identifier[self] . identifier[_tbl] . identifier[tr_lst]
identifier[tr_idx] = identifier[tr_lst] . identifier[index] ( identifier[self] . identifier[_tr] )
keyword[if] identifier[tr_idx... | def _tr_above(self):
"""
The tr element prior in sequence to the tr this cell appears in.
Raises |ValueError| if called on a cell in the top-most row.
"""
tr_lst = self._tbl.tr_lst
tr_idx = tr_lst.index(self._tr)
if tr_idx == 0:
raise ValueError('no tr above topmost tr') ... |
def message(self, category, subject, msg_file):
"""Send message to all users in `category`."""
users = getattr(self.sub, category)
if not users:
print('There are no {} users on {}.'.format(category, self.sub))
return
if msg_file:
try:
... | def function[message, parameter[self, category, subject, msg_file]]:
constant[Send message to all users in `category`.]
variable[users] assign[=] call[name[getattr], parameter[name[self].sub, name[category]]]
if <ast.UnaryOp object at 0x7da20e9b2b60> begin[:]
call[name[print], pa... | keyword[def] identifier[message] ( identifier[self] , identifier[category] , identifier[subject] , identifier[msg_file] ):
literal[string]
identifier[users] = identifier[getattr] ( identifier[self] . identifier[sub] , identifier[category] )
keyword[if] keyword[not] identifier[users] :
... | def message(self, category, subject, msg_file):
"""Send message to all users in `category`."""
users = getattr(self.sub, category)
if not users:
print('There are no {} users on {}.'.format(category, self.sub))
return # depends on [control=['if'], data=[]]
if msg_file:
try:
... |
def register(key, initializer: callable, param=None):
'''Adds resolver to global container'''
get_current_scope().container.register(key, initializer, param) | def function[register, parameter[key, initializer, param]]:
constant[Adds resolver to global container]
call[call[name[get_current_scope], parameter[]].container.register, parameter[name[key], name[initializer], name[param]]] | keyword[def] identifier[register] ( identifier[key] , identifier[initializer] : identifier[callable] , identifier[param] = keyword[None] ):
literal[string]
identifier[get_current_scope] (). identifier[container] . identifier[register] ( identifier[key] , identifier[initializer] , identifier[param] ) | def register(key, initializer: callable, param=None):
"""Adds resolver to global container"""
get_current_scope().container.register(key, initializer, param) |
def retrieve_asset(filename):
""" Retrieves a non-image asset associated with an entry """
record = model.Image.get(asset_name=filename)
if not record:
raise http_error.NotFound("File not found")
if not record.is_asset:
raise http_error.Forbidden()
return flask.send_file(record.fil... | def function[retrieve_asset, parameter[filename]]:
constant[ Retrieves a non-image asset associated with an entry ]
variable[record] assign[=] call[name[model].Image.get, parameter[]]
if <ast.UnaryOp object at 0x7da18c4ce2c0> begin[:]
<ast.Raise object at 0x7da18c4cf5b0>
if <ast.... | keyword[def] identifier[retrieve_asset] ( identifier[filename] ):
literal[string]
identifier[record] = identifier[model] . identifier[Image] . identifier[get] ( identifier[asset_name] = identifier[filename] )
keyword[if] keyword[not] identifier[record] :
keyword[raise] identifier[http_err... | def retrieve_asset(filename):
""" Retrieves a non-image asset associated with an entry """
record = model.Image.get(asset_name=filename)
if not record:
raise http_error.NotFound('File not found') # depends on [control=['if'], data=[]]
if not record.is_asset:
raise http_error.Forbidden()... |
def nvmlUnitGetTemperature(unit, type):
r"""
/**
* Retrieves the temperature readings for the unit, in degrees C.
*
* For S-class products.
*
* Depending on the product, readings may be available for intake (type=0),
* exhaust (type=1) and board (type=2).
*
* @param unit ... | def function[nvmlUnitGetTemperature, parameter[unit, type]]:
constant[
/**
* Retrieves the temperature readings for the unit, in degrees C.
*
* For S-class products.
*
* Depending on the product, readings may be available for intake (type=0),
* exhaust (type=1) and board (type=... | keyword[def] identifier[nvmlUnitGetTemperature] ( identifier[unit] , identifier[type] ):
literal[string]
literal[string]
identifier[c_temp] = identifier[c_uint] ()
identifier[fn] = identifier[_nvmlGetFunctionPointer] ( literal[string] )
identifier[ret] = identifier[fn] ( identifier[unit] , ... | def nvmlUnitGetTemperature(unit, type):
"""
/**
* Retrieves the temperature readings for the unit, in degrees C.
*
* For S-class products.
*
* Depending on the product, readings may be available for intake (type=0),
* exhaust (type=1) and board (type=2).
*
* @param unit ... |
def do_action_openstack_upgrade(package, upgrade_callback, configs):
"""Perform action-managed OpenStack upgrade.
Upgrades packages to the configured openstack-origin version and sets
the corresponding action status as a result.
If the charm was installed from source we cannot upgrade it.
For back... | def function[do_action_openstack_upgrade, parameter[package, upgrade_callback, configs]]:
constant[Perform action-managed OpenStack upgrade.
Upgrades packages to the configured openstack-origin version and sets
the corresponding action status as a result.
If the charm was installed from source we ... | keyword[def] identifier[do_action_openstack_upgrade] ( identifier[package] , identifier[upgrade_callback] , identifier[configs] ):
literal[string]
identifier[ret] = keyword[False]
keyword[if] identifier[openstack_upgrade_available] ( identifier[package] ):
keyword[if] identifier[config] (... | def do_action_openstack_upgrade(package, upgrade_callback, configs):
"""Perform action-managed OpenStack upgrade.
Upgrades packages to the configured openstack-origin version and sets
the corresponding action status as a result.
If the charm was installed from source we cannot upgrade it.
For back... |
def HslToRgb(h, s, l):
'''Convert the color from HSL coordinates to RGB.
Parameters:
:h:
The Hue component value [0...1]
:s:
The Saturation component value [0...1]
:l:
The Lightness component value [0...1]
Returns:
The color as an (r, g, b) tuple in the rang... | def function[HslToRgb, parameter[h, s, l]]:
constant[Convert the color from HSL coordinates to RGB.
Parameters:
:h:
The Hue component value [0...1]
:s:
The Saturation component value [0...1]
:l:
The Lightness component value [0...1]
Returns:
The color as... | keyword[def] identifier[HslToRgb] ( identifier[h] , identifier[s] , identifier[l] ):
literal[string]
keyword[if] identifier[s] == literal[int] : keyword[return] ( identifier[l] , identifier[l] , identifier[l] )
keyword[if] identifier[l] < literal[int] : identifier[n2] = identifier[l] *( literal[int... | def HslToRgb(h, s, l):
"""Convert the color from HSL coordinates to RGB.
Parameters:
:h:
The Hue component value [0...1]
:s:
The Saturation component value [0...1]
:l:
The Lightness component value [0...1]
Returns:
The color as an (r, g, b) tuple in the rang... |
def m2o_to_m2m(cr, model, table, field, source_field):
"""
Recreate relations in many2many fields that were formerly
many2one fields. Use rename_columns in your pre-migrate
script to retain the column's old value, then call m2o_to_m2m
in your post-migrate script.
:param model: The target model ... | def function[m2o_to_m2m, parameter[cr, model, table, field, source_field]]:
constant[
Recreate relations in many2many fields that were formerly
many2one fields. Use rename_columns in your pre-migrate
script to retain the column's old value, then call m2o_to_m2m
in your post-migrate script.
... | keyword[def] identifier[m2o_to_m2m] ( identifier[cr] , identifier[model] , identifier[table] , identifier[field] , identifier[source_field] ):
literal[string]
keyword[return] identifier[m2o_to_x2m] ( identifier[cr] , identifier[model] , identifier[table] , identifier[field] , identifier[source_field] ) | def m2o_to_m2m(cr, model, table, field, source_field):
"""
Recreate relations in many2many fields that were formerly
many2one fields. Use rename_columns in your pre-migrate
script to retain the column's old value, then call m2o_to_m2m
in your post-migrate script.
:param model: The target model ... |
def convert_bytes(n):
"""
Convert a size number to 'K', 'M', .etc
"""
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / pre... | def function[convert_bytes, parameter[n]]:
constant[
Convert a size number to 'K', 'M', .etc
]
variable[symbols] assign[=] tuple[[<ast.Constant object at 0x7da2041db5e0>, <ast.Constant object at 0x7da2041db010>, <ast.Constant object at 0x7da2041d9510>, <ast.Constant object at 0x7da2041d97b0>, <a... | keyword[def] identifier[convert_bytes] ( identifier[n] ):
literal[string]
identifier[symbols] =( literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] )
identifier[prefix] ={}
keyword[for] identifier[i] , ide... | def convert_bytes(n):
"""
Convert a size number to 'K', 'M', .etc
"""
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for (i, s) in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10 # depends on [control=['for'], data=[]]
for s in reversed(symbols):
if n >= pr... |
def get_child(self, streamId, childId, options={}):
"""Get the child of a stream."""
return self.get('stream/' + streamId + '/children/' + childId, options) | def function[get_child, parameter[self, streamId, childId, options]]:
constant[Get the child of a stream.]
return[call[name[self].get, parameter[binary_operation[binary_operation[binary_operation[constant[stream/] + name[streamId]] + constant[/children/]] + name[childId]], name[options]]]] | keyword[def] identifier[get_child] ( identifier[self] , identifier[streamId] , identifier[childId] , identifier[options] ={}):
literal[string]
keyword[return] identifier[self] . identifier[get] ( literal[string] + identifier[streamId] + literal[string] + identifier[childId] , identifier[options] ) | def get_child(self, streamId, childId, options={}):
"""Get the child of a stream."""
return self.get('stream/' + streamId + '/children/' + childId, options) |
def rate(self):
"""Get the sample rate in Hz.
Returns
---------
rate : float
The sample rate, in Hz, calculated from the timestamps
"""
N = len(self.timestamps)
t = self.timestamps[-1] - self.timestamps[0]
rate = 1.0 * N / ... | def function[rate, parameter[self]]:
constant[Get the sample rate in Hz.
Returns
---------
rate : float
The sample rate, in Hz, calculated from the timestamps
]
variable[N] assign[=] call[name[len], parameter[name[self].timestamps]]
... | keyword[def] identifier[rate] ( identifier[self] ):
literal[string]
identifier[N] = identifier[len] ( identifier[self] . identifier[timestamps] )
identifier[t] = identifier[self] . identifier[timestamps] [- literal[int] ]- identifier[self] . identifier[timestamps] [ literal[int] ]
... | def rate(self):
"""Get the sample rate in Hz.
Returns
---------
rate : float
The sample rate, in Hz, calculated from the timestamps
"""
N = len(self.timestamps)
t = self.timestamps[-1] - self.timestamps[0]
rate = 1.0 * N / t
return rat... |
def variance(numbers, type='population'):
"""
Calculates the population or sample variance of a list of numbers.
A large number means the results are all over the place, while a
small number means the results are comparatively close to the average.
Args:
numbers: a list of integers or floa... | def function[variance, parameter[numbers, type]]:
constant[
Calculates the population or sample variance of a list of numbers.
A large number means the results are all over the place, while a
small number means the results are comparatively close to the average.
Args:
numbers: a list o... | keyword[def] identifier[variance] ( identifier[numbers] , identifier[type] = literal[string] ):
literal[string]
identifier[mean] = identifier[average] ( identifier[numbers] )
identifier[variance] = literal[int]
keyword[for] identifier[number] keyword[in] identifier[numbers] :
identif... | def variance(numbers, type='population'):
"""
Calculates the population or sample variance of a list of numbers.
A large number means the results are all over the place, while a
small number means the results are comparatively close to the average.
Args:
numbers: a list of integers or floa... |
def set_frustum(self, l, r, b, t, n, f):
"""Set the frustum
Parameters
----------
l : float
Left.
r : float
Right.
b : float
Bottom.
t : float
Top.
n : float
Near.
f : float
F... | def function[set_frustum, parameter[self, l, r, b, t, n, f]]:
constant[Set the frustum
Parameters
----------
l : float
Left.
r : float
Right.
b : float
Bottom.
t : float
Top.
n : float
Near.
... | keyword[def] identifier[set_frustum] ( identifier[self] , identifier[l] , identifier[r] , identifier[b] , identifier[t] , identifier[n] , identifier[f] ):
literal[string]
identifier[self] . identifier[matrix] = identifier[transforms] . identifier[frustum] ( identifier[l] , identifier[r] , identifie... | def set_frustum(self, l, r, b, t, n, f):
"""Set the frustum
Parameters
----------
l : float
Left.
r : float
Right.
b : float
Bottom.
t : float
Top.
n : float
Near.
f : float
Far.
... |
def serialize_with_sampled_logs(self, logs_limit=-1):
"""serialize a result with up to `logs_limit` logs.
If `logs_limit` is -1, this function will return a result with all its
logs.
"""
return {
'id': self.id,
'pathName': self.path_name,
'na... | def function[serialize_with_sampled_logs, parameter[self, logs_limit]]:
constant[serialize a result with up to `logs_limit` logs.
If `logs_limit` is -1, this function will return a result with all its
logs.
]
return[dictionary[[<ast.Constant object at 0x7da18bc734c0>, <ast.Constant ... | keyword[def] identifier[serialize_with_sampled_logs] ( identifier[self] , identifier[logs_limit] =- literal[int] ):
literal[string]
keyword[return] {
literal[string] : identifier[self] . identifier[id] ,
literal[string] : identifier[self] . identifier[path_name] ,
litera... | def serialize_with_sampled_logs(self, logs_limit=-1):
"""serialize a result with up to `logs_limit` logs.
If `logs_limit` is -1, this function will return a result with all its
logs.
"""
return {'id': self.id, 'pathName': self.path_name, 'name': self.name, 'isUnregistered': self.is_unre... |
def iterator(self):
"""
An iterator over the results from applying this QuerySet to the api.
"""
for item in self.query.results():
obj = self.resource(**item)
yield obj | def function[iterator, parameter[self]]:
constant[
An iterator over the results from applying this QuerySet to the api.
]
for taget[name[item]] in starred[call[name[self].query.results, parameter[]]] begin[:]
variable[obj] assign[=] call[name[self].resource, parameter[]]
... | keyword[def] identifier[iterator] ( identifier[self] ):
literal[string]
keyword[for] identifier[item] keyword[in] identifier[self] . identifier[query] . identifier[results] ():
identifier[obj] = identifier[self] . identifier[resource] (** identifier[item] )
keyword[yi... | def iterator(self):
"""
An iterator over the results from applying this QuerySet to the api.
"""
for item in self.query.results():
obj = self.resource(**item)
yield obj # depends on [control=['for'], data=['item']] |
def raise_if_error(frame):
"""
Checks a frame and raises the relevant exception if required.
"""
if "status" not in frame or frame["status"] == b"\x00":
return
codes_and_exceptions = {
b"\x01": exceptions.ZigBeeUnknownError,
b"\x02": exceptions.ZigBeeInvalidCommand,
b... | def function[raise_if_error, parameter[frame]]:
constant[
Checks a frame and raises the relevant exception if required.
]
if <ast.BoolOp object at 0x7da1b23d25f0> begin[:]
return[None]
variable[codes_and_exceptions] assign[=] dictionary[[<ast.Constant object at 0x7da1b23d2b90>, <... | keyword[def] identifier[raise_if_error] ( identifier[frame] ):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[frame] keyword[or] identifier[frame] [ literal[string] ]== literal[string] :
keyword[return]
identifier[codes_and_exceptions] ={
literal[s... | def raise_if_error(frame):
"""
Checks a frame and raises the relevant exception if required.
"""
if 'status' not in frame or frame['status'] == b'\x00':
return # depends on [control=['if'], data=[]]
codes_and_exceptions = {b'\x01': exceptions.ZigBeeUnknownError, b'\x02': exceptions.ZigBeeIn... |
def _make_request(self, opener, request, timeout=None):
"""Make the API call and return the response. This is separated into
it's own function, so we can mock it easily for testing.
:param opener:
:type opener:
:param request: url payload to request
:type request: url... | def function[_make_request, parameter[self, opener, request, timeout]]:
constant[Make the API call and return the response. This is separated into
it's own function, so we can mock it easily for testing.
:param opener:
:type opener:
:param request: url payload to request
... | keyword[def] identifier[_make_request] ( identifier[self] , identifier[opener] , identifier[request] , identifier[timeout] = keyword[None] ):
literal[string]
identifier[timeout] = identifier[timeout] keyword[or] identifier[self] . identifier[timeout]
keyword[try] :
keyword[... | def _make_request(self, opener, request, timeout=None):
"""Make the API call and return the response. This is separated into
it's own function, so we can mock it easily for testing.
:param opener:
:type opener:
:param request: url payload to request
:type request: urllib.... |
def save(self):
"""
Save the project configuration
This method dumps the configuration for each project and the project
paths (see the :attr:`all_projects` attribute) to the hard drive
"""
project_paths = OrderedDict()
for project, d in OrderedDict(self).items():... | def function[save, parameter[self]]:
constant[
Save the project configuration
This method dumps the configuration for each project and the project
paths (see the :attr:`all_projects` attribute) to the hard drive
]
variable[project_paths] assign[=] call[name[OrderedDict],... | keyword[def] identifier[save] ( identifier[self] ):
literal[string]
identifier[project_paths] = identifier[OrderedDict] ()
keyword[for] identifier[project] , identifier[d] keyword[in] identifier[OrderedDict] ( identifier[self] ). identifier[items] ():
keyword[if] identifie... | def save(self):
"""
Save the project configuration
This method dumps the configuration for each project and the project
paths (see the :attr:`all_projects` attribute) to the hard drive
"""
project_paths = OrderedDict()
for (project, d) in OrderedDict(self).items():
i... |
def add_target(self, target_text, name='', drop_behavior_type=None):
"""stub"""
if not isinstance(target_text, DisplayText):
raise InvalidArgument('target_text is not a DisplayText object')
if not isinstance(name, DisplayText):
# if default ''
name = self._str... | def function[add_target, parameter[self, target_text, name, drop_behavior_type]]:
constant[stub]
if <ast.UnaryOp object at 0x7da1b0a22530> begin[:]
<ast.Raise object at 0x7da1b0a210f0>
if <ast.UnaryOp object at 0x7da1b0a220e0> begin[:]
variable[name] assign[=] call[name[s... | keyword[def] identifier[add_target] ( identifier[self] , identifier[target_text] , identifier[name] = literal[string] , identifier[drop_behavior_type] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[target_text] , identifier[DisplayText] ):
... | def add_target(self, target_text, name='', drop_behavior_type=None):
"""stub"""
if not isinstance(target_text, DisplayText):
raise InvalidArgument('target_text is not a DisplayText object') # depends on [control=['if'], data=[]]
if not isinstance(name, DisplayText):
# if default ''
... |
def exec_(self, columns=(), by=(), where=(), **kwds):
"""exec from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.exec_('a', where='b > 10').show()
2 3
"""
return self._seu('exec', columns, by, where, kwds) | def function[exec_, parameter[self, columns, by, where]]:
constant[exec from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.exec_('a', where='b > 10').show()
2 3
]
return[call[name[self]._seu, parameter[constant[exec], name[columns], name[by], name[where], name[kwds]]]] | keyword[def] identifier[exec_] ( identifier[self] , identifier[columns] =(), identifier[by] =(), identifier[where] =(),** identifier[kwds] ):
literal[string]
keyword[return] identifier[self] . identifier[_seu] ( literal[string] , identifier[columns] , identifier[by] , identifier[where] , identifie... | def exec_(self, columns=(), by=(), where=(), **kwds):
"""exec from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.exec_('a', where='b > 10').show()
2 3
"""
return self._seu('exec', columns, by, where, kwds) |
def _context_data(data, request=None):
"""
Add admin global context, for compatibility with Django 1.7
"""
try:
return dict(site.each_context(request).items() + data.items())
except AttributeError:
return data | def function[_context_data, parameter[data, request]]:
constant[
Add admin global context, for compatibility with Django 1.7
]
<ast.Try object at 0x7da1b021f340> | keyword[def] identifier[_context_data] ( identifier[data] , identifier[request] = keyword[None] ):
literal[string]
keyword[try] :
keyword[return] identifier[dict] ( identifier[site] . identifier[each_context] ( identifier[request] ). identifier[items] ()+ identifier[data] . identifier[items] ())
... | def _context_data(data, request=None):
"""
Add admin global context, for compatibility with Django 1.7
"""
try:
return dict(site.each_context(request).items() + data.items()) # depends on [control=['try'], data=[]]
except AttributeError:
return data # depends on [control=['except']... |
def list_sections(self):
"""List all sections."""
if not os.path.exists(self._full_base):
return []
return [
name for name in os.listdir(self._full_base)
if os.path.isdir(os.path.join(self._full_base, name))
] | def function[list_sections, parameter[self]]:
constant[List all sections.]
if <ast.UnaryOp object at 0x7da1b0948130> begin[:]
return[list[[]]]
return[<ast.ListComp object at 0x7da1b09487c0>] | keyword[def] identifier[list_sections] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[self] . identifier[_full_base] ):
keyword[return] []
keyword[return] [
identifier[name] keyword... | def list_sections(self):
"""List all sections."""
if not os.path.exists(self._full_base):
return [] # depends on [control=['if'], data=[]]
return [name for name in os.listdir(self._full_base) if os.path.isdir(os.path.join(self._full_base, name))] |
def main() -> None:
"""
Command-line processor. See ``--help`` for details.
"""
parser = ArgumentParser(
description="Remove duplicate files"
)
parser.add_argument(
"directory", nargs="+",
help="Files and/or directories to check and remove duplicates from."
)
pars... | def function[main, parameter[]]:
constant[
Command-line processor. See ``--help`` for details.
]
variable[parser] assign[=] call[name[ArgumentParser], parameter[]]
call[name[parser].add_argument, parameter[constant[directory]]]
call[name[parser].add_argument, parameter[constant[-... | keyword[def] identifier[main] ()-> keyword[None] :
literal[string]
identifier[parser] = identifier[ArgumentParser] (
identifier[description] = literal[string]
)
identifier[parser] . identifier[add_argument] (
literal[string] , identifier[nargs] = literal[string] ,
identifier[help] ... | def main() -> None:
"""
Command-line processor. See ``--help`` for details.
"""
parser = ArgumentParser(description='Remove duplicate files')
parser.add_argument('directory', nargs='+', help='Files and/or directories to check and remove duplicates from.')
parser.add_argument('--recursive', actio... |
def _remove_buffers(state):
"""Return (state_without_buffers, buffer_paths, buffers) for binary message parts
A binary message part is a memoryview, bytearray, or python 3 bytes object.
As an example:
>>> state = {'plain': [0, 'text'], 'x': {'ar': memoryview(ar1)}, 'y': {'shape': (10,10), 'data': memo... | def function[_remove_buffers, parameter[state]]:
constant[Return (state_without_buffers, buffer_paths, buffers) for binary message parts
A binary message part is a memoryview, bytearray, or python 3 bytes object.
As an example:
>>> state = {'plain': [0, 'text'], 'x': {'ar': memoryview(ar1)}, 'y': ... | keyword[def] identifier[_remove_buffers] ( identifier[state] ):
literal[string]
identifier[buffer_paths] , identifier[buffers] =[],[]
identifier[state] = identifier[_separate_buffers] ( identifier[state] ,[], identifier[buffer_paths] , identifier[buffers] )
keyword[return] identifier[state] , id... | def _remove_buffers(state):
"""Return (state_without_buffers, buffer_paths, buffers) for binary message parts
A binary message part is a memoryview, bytearray, or python 3 bytes object.
As an example:
>>> state = {'plain': [0, 'text'], 'x': {'ar': memoryview(ar1)}, 'y': {'shape': (10,10), 'data': memo... |
def ed(s1, s2):
'''edit distance
>>> ed('', ''), ed('a', 'a'), ed('','a'), ed('a', ''), ed('a!a', 'a.a')
(0, 0, 1, 1, 1)
This implementation takes only O(min(|s1|,|s2|)) space.
'''
m, n = len(s1), len(s2)
if m < n:
m, n = n, m # ensure n <= m, to use O(min(n,m)) space
... | def function[ed, parameter[s1, s2]]:
constant[edit distance
>>> ed('', ''), ed('a', 'a'), ed('','a'), ed('a', ''), ed('a!a', 'a.a')
(0, 0, 1, 1, 1)
This implementation takes only O(min(|s1|,|s2|)) space.
]
<ast.Tuple object at 0x7da20e956d40> assign[=] tuple[[<ast.Call object at 0x7da2... | keyword[def] identifier[ed] ( identifier[s1] , identifier[s2] ):
literal[string]
identifier[m] , identifier[n] = identifier[len] ( identifier[s1] ), identifier[len] ( identifier[s2] )
keyword[if] identifier[m] < identifier[n] :
identifier[m] , identifier[n] = identifier[n] , identifier[m]
... | def ed(s1, s2):
"""edit distance
>>> ed('', ''), ed('a', 'a'), ed('','a'), ed('a', ''), ed('a!a', 'a.a')
(0, 0, 1, 1, 1)
This implementation takes only O(min(|s1|,|s2|)) space.
"""
(m, n) = (len(s1), len(s2))
if m < n:
(m, n) = (n, m) # ensure n <= m, to use O(min(n,m)) space
... |
def is_within(self, cutoff_dist, point, ligands=True):
"""Returns all atoms in AMPAL object within `cut-off` distance from the `point`."""
return find_atoms_within_distance(self.get_atoms(ligands=ligands), cutoff_dist, point) | def function[is_within, parameter[self, cutoff_dist, point, ligands]]:
constant[Returns all atoms in AMPAL object within `cut-off` distance from the `point`.]
return[call[name[find_atoms_within_distance], parameter[call[name[self].get_atoms, parameter[]], name[cutoff_dist], name[point]]]] | keyword[def] identifier[is_within] ( identifier[self] , identifier[cutoff_dist] , identifier[point] , identifier[ligands] = keyword[True] ):
literal[string]
keyword[return] identifier[find_atoms_within_distance] ( identifier[self] . identifier[get_atoms] ( identifier[ligands] = identifier[ligands]... | def is_within(self, cutoff_dist, point, ligands=True):
"""Returns all atoms in AMPAL object within `cut-off` distance from the `point`."""
return find_atoms_within_distance(self.get_atoms(ligands=ligands), cutoff_dist, point) |
def get_speaker_info(self, refresh=False, timeout=None):
"""Get information about the Sonos speaker.
Arguments:
refresh(bool): Refresh the speaker info cache.
timeout: How long to wait for the server to send
data before giving up, as a float, or a
... | def function[get_speaker_info, parameter[self, refresh, timeout]]:
constant[Get information about the Sonos speaker.
Arguments:
refresh(bool): Refresh the speaker info cache.
timeout: How long to wait for the server to send
data before giving up, as a float, or a... | keyword[def] identifier[get_speaker_info] ( identifier[self] , identifier[refresh] = keyword[False] , identifier[timeout] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[speaker_info] keyword[and] identifier[refresh] keyword[is] keyword[False] :
keywor... | def get_speaker_info(self, refresh=False, timeout=None):
"""Get information about the Sonos speaker.
Arguments:
refresh(bool): Refresh the speaker info cache.
timeout: How long to wait for the server to send
data before giving up, as a float, or a
`(c... |
def SLH_to_qutip(slh, full_space=None, time_symbol=None,
convert_as='pyfunc'):
"""Generate and return QuTiP representation matrices for the Hamiltonian
and the collapse operators. Any inhomogeneities in the Lindblad operators
(resulting from coherent drives) will be moved into the Hamiltoni... | def function[SLH_to_qutip, parameter[slh, full_space, time_symbol, convert_as]]:
constant[Generate and return QuTiP representation matrices for the Hamiltonian
and the collapse operators. Any inhomogeneities in the Lindblad operators
(resulting from coherent drives) will be moved into the Hamiltonian, c... | keyword[def] identifier[SLH_to_qutip] ( identifier[slh] , identifier[full_space] = keyword[None] , identifier[time_symbol] = keyword[None] ,
identifier[convert_as] = literal[string] ):
literal[string]
keyword[if] identifier[full_space] :
keyword[if] keyword[not] identifier[full_space] >= ident... | def SLH_to_qutip(slh, full_space=None, time_symbol=None, convert_as='pyfunc'):
"""Generate and return QuTiP representation matrices for the Hamiltonian
and the collapse operators. Any inhomogeneities in the Lindblad operators
(resulting from coherent drives) will be moved into the Hamiltonian, cf.
:func... |
def ScanFiles(theFile, target, paths, file_tests, file_tests_search, env, graphics_extensions, targetdir, aux_files):
""" For theFile (a Node) update any file_tests and search for graphics files
then find all included files and call ScanFiles recursively for each of them"""
content = theFile.get_text_conte... | def function[ScanFiles, parameter[theFile, target, paths, file_tests, file_tests_search, env, graphics_extensions, targetdir, aux_files]]:
constant[ For theFile (a Node) update any file_tests and search for graphics files
then find all included files and call ScanFiles recursively for each of them]
... | keyword[def] identifier[ScanFiles] ( identifier[theFile] , identifier[target] , identifier[paths] , identifier[file_tests] , identifier[file_tests_search] , identifier[env] , identifier[graphics_extensions] , identifier[targetdir] , identifier[aux_files] ):
literal[string]
identifier[content] = identifier... | def ScanFiles(theFile, target, paths, file_tests, file_tests_search, env, graphics_extensions, targetdir, aux_files):
""" For theFile (a Node) update any file_tests and search for graphics files
then find all included files and call ScanFiles recursively for each of them"""
content = theFile.get_text_conten... |
def rfxcom(device):
"""Start the event loop to collect data from the serial device."""
# If the device isn't passed in, look for it in the config.
if device is None:
device = app.config.get('DEVICE')
# If the device is *still* none, error.
if device is None:
print("The serial devic... | def function[rfxcom, parameter[device]]:
constant[Start the event loop to collect data from the serial device.]
if compare[name[device] is constant[None]] begin[:]
variable[device] assign[=] call[name[app].config.get, parameter[constant[DEVICE]]]
if compare[name[device] is consta... | keyword[def] identifier[rfxcom] ( identifier[device] ):
literal[string]
keyword[if] identifier[device] keyword[is] keyword[None] :
identifier[device] = identifier[app] . identifier[config] . identifier[get] ( literal[string] )
keyword[if] identifier[device] keyword[is] k... | def rfxcom(device):
"""Start the event loop to collect data from the serial device."""
# If the device isn't passed in, look for it in the config.
if device is None:
device = app.config.get('DEVICE') # depends on [control=['if'], data=['device']]
# If the device is *still* none, error.
if d... |
def may_contain_matches(self, path):
"""Tests whether it's possible for paths under the given one to match.
If this method returns None, no path under the given one will match the
pattern.
"""
path = self._prepare_path(path)
return self.int_regex.search(path) is not None | def function[may_contain_matches, parameter[self, path]]:
constant[Tests whether it's possible for paths under the given one to match.
If this method returns None, no path under the given one will match the
pattern.
]
variable[path] assign[=] call[name[self]._prepare_path, param... | keyword[def] identifier[may_contain_matches] ( identifier[self] , identifier[path] ):
literal[string]
identifier[path] = identifier[self] . identifier[_prepare_path] ( identifier[path] )
keyword[return] identifier[self] . identifier[int_regex] . identifier[search] ( identifier[path] ) key... | def may_contain_matches(self, path):
"""Tests whether it's possible for paths under the given one to match.
If this method returns None, no path under the given one will match the
pattern.
"""
path = self._prepare_path(path)
return self.int_regex.search(path) is not None |
def prof_altitude(pressure, p_coef=(-0.028389, -0.0493698, 0.485718, 0.278656,
-17.5703, 48.0926)):
"""
Return altitude for given pressure.
This function evaluates a polynomial at log10(pressure) values.
Parameters
----------
pressure : array-like
pr... | def function[prof_altitude, parameter[pressure, p_coef]]:
constant[
Return altitude for given pressure.
This function evaluates a polynomial at log10(pressure) values.
Parameters
----------
pressure : array-like
pressure values [hPa].
p_coef : array-like
coefficients of... | keyword[def] identifier[prof_altitude] ( identifier[pressure] , identifier[p_coef] =(- literal[int] ,- literal[int] , literal[int] , literal[int] ,
- literal[int] , literal[int] )):
literal[string]
identifier[pressure] = identifier[np] . identifier[asarray] ( identifier[pressure] )
identifier[altitude... | def prof_altitude(pressure, p_coef=(-0.028389, -0.0493698, 0.485718, 0.278656, -17.5703, 48.0926)):
"""
Return altitude for given pressure.
This function evaluates a polynomial at log10(pressure) values.
Parameters
----------
pressure : array-like
pressure values [hPa].
p_coef : ar... |
def time_vs_parameter(self, parameter, bp, merge=False, merge_method='mean', masked=False):
"""To get the parameter of either a specfic base-pair/step or a DNA segment as a function of time.
parameters
----------
parameter : str
Name of a base-pair or base-step or helical pa... | def function[time_vs_parameter, parameter[self, parameter, bp, merge, merge_method, masked]]:
constant[To get the parameter of either a specfic base-pair/step or a DNA segment as a function of time.
parameters
----------
parameter : str
Name of a base-pair or base-step or he... | keyword[def] identifier[time_vs_parameter] ( identifier[self] , identifier[parameter] , identifier[bp] , identifier[merge] = keyword[False] , identifier[merge_method] = literal[string] , identifier[masked] = keyword[False] ):
literal[string]
keyword[if] keyword[not] ( identifier[isinstance] ( iden... | def time_vs_parameter(self, parameter, bp, merge=False, merge_method='mean', masked=False):
"""To get the parameter of either a specfic base-pair/step or a DNA segment as a function of time.
parameters
----------
parameter : str
Name of a base-pair or base-step or helical parame... |
def _choose_front_id_from_candidates(candidate_offset_front_ids, offset_fronts, offsets_corresponding_to_onsets):
"""
Returns a front ID which is the id of the offset front that contains the most overlap
with offsets that correspond to the given onset front ID.
"""
noverlaps = [] # will contain tup... | def function[_choose_front_id_from_candidates, parameter[candidate_offset_front_ids, offset_fronts, offsets_corresponding_to_onsets]]:
constant[
Returns a front ID which is the id of the offset front that contains the most overlap
with offsets that correspond to the given onset front ID.
]
v... | keyword[def] identifier[_choose_front_id_from_candidates] ( identifier[candidate_offset_front_ids] , identifier[offset_fronts] , identifier[offsets_corresponding_to_onsets] ):
literal[string]
identifier[noverlaps] =[]
keyword[for] identifier[offset_front_id] keyword[in] identifier[candidate_offset_... | def _choose_front_id_from_candidates(candidate_offset_front_ids, offset_fronts, offsets_corresponding_to_onsets):
"""
Returns a front ID which is the id of the offset front that contains the most overlap
with offsets that correspond to the given onset front ID.
"""
noverlaps = [] # will contain tup... |
def bool(self):
"""Return the bool of a single element PandasObject.
This must be a boolean scalar value, either True or False. Raise a
ValueError if the PandasObject does not have exactly 1 element, or that
element is not boolean
"""
shape = self.shape
... | def function[bool, parameter[self]]:
constant[Return the bool of a single element PandasObject.
This must be a boolean scalar value, either True or False. Raise a
ValueError if the PandasObject does not have exactly 1 element, or that
element is not boolean
]
variable[s... | keyword[def] identifier[bool] ( identifier[self] ):
literal[string]
identifier[shape] = identifier[self] . identifier[shape]
keyword[if] identifier[shape] !=( literal[int] ,) keyword[and] identifier[shape] !=( literal[int] , literal[int] ):
keyword[raise] identifier[Va... | def bool(self):
"""Return the bool of a single element PandasObject.
This must be a boolean scalar value, either True or False. Raise a
ValueError if the PandasObject does not have exactly 1 element, or that
element is not boolean
"""
shape = self.shape
if shape != (1,) and... |
def SignalAbort(self):
"""Signals the process to abort."""
self._abort = True
if self._extraction_worker:
self._extraction_worker.SignalAbort()
if self._parser_mediator:
self._parser_mediator.SignalAbort() | def function[SignalAbort, parameter[self]]:
constant[Signals the process to abort.]
name[self]._abort assign[=] constant[True]
if name[self]._extraction_worker begin[:]
call[name[self]._extraction_worker.SignalAbort, parameter[]]
if name[self]._parser_mediator begin[:]
... | keyword[def] identifier[SignalAbort] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_abort] = keyword[True]
keyword[if] identifier[self] . identifier[_extraction_worker] :
identifier[self] . identifier[_extraction_worker] . identifier[SignalAbort] ()
keyword[if] ide... | def SignalAbort(self):
"""Signals the process to abort."""
self._abort = True
if self._extraction_worker:
self._extraction_worker.SignalAbort() # depends on [control=['if'], data=[]]
if self._parser_mediator:
self._parser_mediator.SignalAbort() # depends on [control=['if'], data=[]] |
def create_model_package_from_algorithm(self, name, description, algorithm_arn, model_data):
"""Create a SageMaker Model Package from the results of training with an Algorithm Package
Args:
name (str): ModelPackage name
description (str): Model Package description
al... | def function[create_model_package_from_algorithm, parameter[self, name, description, algorithm_arn, model_data]]:
constant[Create a SageMaker Model Package from the results of training with an Algorithm Package
Args:
name (str): ModelPackage name
description (str): Model Package... | keyword[def] identifier[create_model_package_from_algorithm] ( identifier[self] , identifier[name] , identifier[description] , identifier[algorithm_arn] , identifier[model_data] ):
literal[string]
identifier[request] ={
literal[string] : identifier[name] ,
literal[string] : identi... | def create_model_package_from_algorithm(self, name, description, algorithm_arn, model_data):
"""Create a SageMaker Model Package from the results of training with an Algorithm Package
Args:
name (str): ModelPackage name
description (str): Model Package description
algori... |
def current_human_transaction(self):
"""Current ongoing human transaction"""
try:
tx, _, _, _, _ = self._callstack[0]
if tx.result is not None:
#That tx finished. No current tx.
return None
assert tx.depth == 0
return tx
... | def function[current_human_transaction, parameter[self]]:
constant[Current ongoing human transaction]
<ast.Try object at 0x7da204963430> | keyword[def] identifier[current_human_transaction] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[tx] , identifier[_] , identifier[_] , identifier[_] , identifier[_] = identifier[self] . identifier[_callstack] [ literal[int] ]
keyword[if] identifier[tx] .... | def current_human_transaction(self):
"""Current ongoing human transaction"""
try:
(tx, _, _, _, _) = self._callstack[0]
if tx.result is not None:
#That tx finished. No current tx.
return None # depends on [control=['if'], data=[]]
assert tx.depth == 0
ret... |
def _mock_request(self, **kwargs):
"""
A mocked out make_request call that bypasses all network calls
and simply returns any mocked responses defined.
"""
model = kwargs.get('model')
service = model.service_model.endpoint_prefix
operation = model.name
LOG.... | def function[_mock_request, parameter[self]]:
constant[
A mocked out make_request call that bypasses all network calls
and simply returns any mocked responses defined.
]
variable[model] assign[=] call[name[kwargs].get, parameter[constant[model]]]
variable[service] assign[... | keyword[def] identifier[_mock_request] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[model] = identifier[kwargs] . identifier[get] ( literal[string] )
identifier[service] = identifier[model] . identifier[service_model] . identifier[endpoint_prefix]
ident... | def _mock_request(self, **kwargs):
"""
A mocked out make_request call that bypasses all network calls
and simply returns any mocked responses defined.
"""
model = kwargs.get('model')
service = model.service_model.endpoint_prefix
operation = model.name
LOG.debug('_make_request... |
def broadcast(self, bot, channel_type, text):
"""
Use this method to broadcast text message to all users of bot.
:param bot: bot that will push user
:type bot: Bot
:param channel_type: one of [telegram, facebook, slack]
:type channel_type: str
:param text: text m... | def function[broadcast, parameter[self, bot, channel_type, text]]:
constant[
Use this method to broadcast text message to all users of bot.
:param bot: bot that will push user
:type bot: Bot
:param channel_type: one of [telegram, facebook, slack]
:type channel_type: str
... | keyword[def] identifier[broadcast] ( identifier[self] , identifier[bot] , identifier[channel_type] , identifier[text] ):
literal[string]
identifier[self] . identifier[client] . identifier[broadcast] . identifier[__getattr__] ( identifier[bot] . identifier[name] ). identifier[__call__] ( identifier[... | def broadcast(self, bot, channel_type, text):
"""
Use this method to broadcast text message to all users of bot.
:param bot: bot that will push user
:type bot: Bot
:param channel_type: one of [telegram, facebook, slack]
:type channel_type: str
:param text: text messa... |
def all(self, typ, **kwargs):
"""
List all of type
Valid arguments:
skip : number of records to skip
limit : number of records to limit request to
"""
return self._load(self._request(typ, params=kwargs)) | def function[all, parameter[self, typ]]:
constant[
List all of type
Valid arguments:
skip : number of records to skip
limit : number of records to limit request to
]
return[call[name[self]._load, parameter[call[name[self]._request, parameter[name[typ]]]]]] | keyword[def] identifier[all] ( identifier[self] , identifier[typ] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[_load] ( identifier[self] . identifier[_request] ( identifier[typ] , identifier[params] = identifier[kwargs] )) | def all(self, typ, **kwargs):
"""
List all of type
Valid arguments:
skip : number of records to skip
limit : number of records to limit request to
"""
return self._load(self._request(typ, params=kwargs)) |
def find_one(cls, *args, **kwargs):
"""Run a find_one on this model's collection. The arguments to
``Model.find_one`` are the same as to ``pymongo.Collection.find_one``."""
database, collection = cls._collection_key.split('.')
return current()[database][collection].find_one(*args, **kwa... | def function[find_one, parameter[cls]]:
constant[Run a find_one on this model's collection. The arguments to
``Model.find_one`` are the same as to ``pymongo.Collection.find_one``.]
<ast.Tuple object at 0x7da18f00e500> assign[=] call[name[cls]._collection_key.split, parameter[constant[.]]]
r... | keyword[def] identifier[find_one] ( identifier[cls] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[database] , identifier[collection] = identifier[cls] . identifier[_collection_key] . identifier[split] ( literal[string] )
keyword[return] identifier[current] ()[ i... | def find_one(cls, *args, **kwargs):
"""Run a find_one on this model's collection. The arguments to
``Model.find_one`` are the same as to ``pymongo.Collection.find_one``."""
(database, collection) = cls._collection_key.split('.')
return current()[database][collection].find_one(*args, **kwargs) |
def list(self, container_or_share_name, container=None, account=None):
"""List the blobs/files inside a container/share_name.
Args:
container_or_share_name(str): Name of the container/share_name where we want to list the blobs/files.
container(bool): flag to know it you are li... | def function[list, parameter[self, container_or_share_name, container, account]]:
constant[List the blobs/files inside a container/share_name.
Args:
container_or_share_name(str): Name of the container/share_name where we want to list the blobs/files.
container(bool): flag to k... | keyword[def] identifier[list] ( identifier[self] , identifier[container_or_share_name] , identifier[container] = keyword[None] , identifier[account] = keyword[None] ):
literal[string]
identifier[key] = identifier[self] . identifier[storage_client] . identifier[storage_accounts] . identifier[list_ke... | def list(self, container_or_share_name, container=None, account=None):
"""List the blobs/files inside a container/share_name.
Args:
container_or_share_name(str): Name of the container/share_name where we want to list the blobs/files.
container(bool): flag to know it you are listin... |
def libvlc_video_set_subtitle_file(p_mi, psz_subtitle):
'''Set new video subtitle file.
@param p_mi: the media player.
@param psz_subtitle: new video subtitle file.
@return: the success status (boolean).
'''
f = _Cfunctions.get('libvlc_video_set_subtitle_file', None) or \
_Cfunction('lib... | def function[libvlc_video_set_subtitle_file, parameter[p_mi, psz_subtitle]]:
constant[Set new video subtitle file.
@param p_mi: the media player.
@param psz_subtitle: new video subtitle file.
@return: the success status (boolean).
]
variable[f] assign[=] <ast.BoolOp object at 0x7da1b2344... | keyword[def] identifier[libvlc_video_set_subtitle_file] ( identifier[p_mi] , identifier[psz_subtitle] ):
literal[string]
identifier[f] = identifier[_Cfunctions] . identifier[get] ( literal[string] , keyword[None] ) keyword[or] identifier[_Cfunction] ( literal[string] ,(( literal[int] ,),( literal[int] ,),... | def libvlc_video_set_subtitle_file(p_mi, psz_subtitle):
"""Set new video subtitle file.
@param p_mi: the media player.
@param psz_subtitle: new video subtitle file.
@return: the success status (boolean).
"""
f = _Cfunctions.get('libvlc_video_set_subtitle_file', None) or _Cfunction('libvlc_video_... |
def _resolve_rule_refs(self, grammar_parser, model_parser):
"""Resolves parser ParsingExpression crossrefs."""
def _resolve_rule(rule):
"""
Recursively resolve peg rule references.
Args:
rule(ParsingExpression or RuleCrossRef)
"""
... | def function[_resolve_rule_refs, parameter[self, grammar_parser, model_parser]]:
constant[Resolves parser ParsingExpression crossrefs.]
def function[_resolve_rule, parameter[rule]]:
constant[
Recursively resolve peg rule references.
Args:
rule(Par... | keyword[def] identifier[_resolve_rule_refs] ( identifier[self] , identifier[grammar_parser] , identifier[model_parser] ):
literal[string]
keyword[def] identifier[_resolve_rule] ( identifier[rule] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( ide... | def _resolve_rule_refs(self, grammar_parser, model_parser):
"""Resolves parser ParsingExpression crossrefs."""
def _resolve_rule(rule):
"""
Recursively resolve peg rule references.
Args:
rule(ParsingExpression or RuleCrossRef)
"""
if not isin... |
def get_tile(self, x_tile, y_tile, zoom,
bands=None, masked=None, resampling=Resampling.cubic):
"""Convert mercator tile to raster window.
:param x_tile: x coordinate of tile
:param y_tile: y coordinate of tile
:param zoom: zoom level
:param bands: list of indic... | def function[get_tile, parameter[self, x_tile, y_tile, zoom, bands, masked, resampling]]:
constant[Convert mercator tile to raster window.
:param x_tile: x coordinate of tile
:param y_tile: y coordinate of tile
:param zoom: zoom level
:param bands: list of indices of requested b... | keyword[def] identifier[get_tile] ( identifier[self] , identifier[x_tile] , identifier[y_tile] , identifier[zoom] ,
identifier[bands] = keyword[None] , identifier[masked] = keyword[None] , identifier[resampling] = identifier[Resampling] . identifier[cubic] ):
literal[string]
keyword[if] identifie... | def get_tile(self, x_tile, y_tile, zoom, bands=None, masked=None, resampling=Resampling.cubic):
"""Convert mercator tile to raster window.
:param x_tile: x coordinate of tile
:param y_tile: y coordinate of tile
:param zoom: zoom level
:param bands: list of indices of requested bands... |
def get_geo_top_artists(self, country, limit=None, cacheable=True):
"""Get the most popular artists on Last.fm by country.
Parameters:
country (Required) : A country name, as defined by the ISO 3166-1
country names standard.
limit (Optional) : The number of results to fetch p... | def function[get_geo_top_artists, parameter[self, country, limit, cacheable]]:
constant[Get the most popular artists on Last.fm by country.
Parameters:
country (Required) : A country name, as defined by the ISO 3166-1
country names standard.
limit (Optional) : The number of r... | keyword[def] identifier[get_geo_top_artists] ( identifier[self] , identifier[country] , identifier[limit] = keyword[None] , identifier[cacheable] = keyword[True] ):
literal[string]
identifier[params] ={ literal[string] : identifier[country] }
keyword[if] identifier[limit] :
... | def get_geo_top_artists(self, country, limit=None, cacheable=True):
"""Get the most popular artists on Last.fm by country.
Parameters:
country (Required) : A country name, as defined by the ISO 3166-1
country names standard.
limit (Optional) : The number of results to fetch per p... |
def tail(self, limit=25, **fetch_kwargs):
"""
shortcut to fetch the last few entries from query expression.
Equivalent to fetch(order_by="KEY DESC", limit=25)[::-1]
:param limit: number of entries
:param fetch_kwargs: kwargs for fetch
:return: query result
"""
... | def function[tail, parameter[self, limit]]:
constant[
shortcut to fetch the last few entries from query expression.
Equivalent to fetch(order_by="KEY DESC", limit=25)[::-1]
:param limit: number of entries
:param fetch_kwargs: kwargs for fetch
:return: query result
... | keyword[def] identifier[tail] ( identifier[self] , identifier[limit] = literal[int] ,** identifier[fetch_kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[fetch] ( identifier[order_by] = literal[string] , identifier[limit] = identifier[limit] ,** identifier[fetch_kwargs] )[:... | def tail(self, limit=25, **fetch_kwargs):
"""
shortcut to fetch the last few entries from query expression.
Equivalent to fetch(order_by="KEY DESC", limit=25)[::-1]
:param limit: number of entries
:param fetch_kwargs: kwargs for fetch
:return: query result
"""
re... |
def restart(self, restart_only_stale_services=None,
redeploy_client_configuration=None,
restart_service_names=None):
"""
Restart all services in the cluster.
Services are restarted in the appropriate order given their dependencies.
@param restart_only_stale_services: Only restart services that ... | def function[restart, parameter[self, restart_only_stale_services, redeploy_client_configuration, restart_service_names]]:
constant[
Restart all services in the cluster.
Services are restarted in the appropriate order given their dependencies.
@param restart_only_stale_services: Only restart servic... | keyword[def] identifier[restart] ( identifier[self] , identifier[restart_only_stale_services] = keyword[None] ,
identifier[redeploy_client_configuration] = keyword[None] ,
identifier[restart_service_names] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[_get_resource_root] (... | def restart(self, restart_only_stale_services=None, redeploy_client_configuration=None, restart_service_names=None):
"""
Restart all services in the cluster.
Services are restarted in the appropriate order given their dependencies.
@param restart_only_stale_services: Only restart services that have sta... |
def receive_trial_result(self, parameter_id, parameters, value):
""" Record an observation of the objective function.
Parameters
----------
parameter_id : int
parameters : dict
value : dict/float
if value is dict, it should have "default" key.
"""... | def function[receive_trial_result, parameter[self, parameter_id, parameters, value]]:
constant[ Record an observation of the objective function.
Parameters
----------
parameter_id : int
parameters : dict
value : dict/float
if value is dict, it should have... | keyword[def] identifier[receive_trial_result] ( identifier[self] , identifier[parameter_id] , identifier[parameters] , identifier[value] ):
literal[string]
identifier[reward] = identifier[extract_scalar_reward] ( identifier[value] )
keyword[if] identifier[parameter_id] keyword[not] key... | def receive_trial_result(self, parameter_id, parameters, value):
""" Record an observation of the objective function.
Parameters
----------
parameter_id : int
parameters : dict
value : dict/float
if value is dict, it should have "default" key.
"""
... |
def stage():
"""Option to do something on the staging server."""
common_conf()
env.user = settings.LOGIN_USER_STAGE
env.machine = 'stage'
env.host_string = settings.HOST_STAGE
env.hosts = [env.host_string, ] | def function[stage, parameter[]]:
constant[Option to do something on the staging server.]
call[name[common_conf], parameter[]]
name[env].user assign[=] name[settings].LOGIN_USER_STAGE
name[env].machine assign[=] constant[stage]
name[env].host_string assign[=] name[settings].HOST_... | keyword[def] identifier[stage] ():
literal[string]
identifier[common_conf] ()
identifier[env] . identifier[user] = identifier[settings] . identifier[LOGIN_USER_STAGE]
identifier[env] . identifier[machine] = literal[string]
identifier[env] . identifier[host_string] = identifier[settings] . ... | def stage():
"""Option to do something on the staging server."""
common_conf()
env.user = settings.LOGIN_USER_STAGE
env.machine = 'stage'
env.host_string = settings.HOST_STAGE
env.hosts = [env.host_string] |
def has(cmd):
"""Returns true if the give shell command is available.
**Examples**:
::
auxly.shell.has("ls") # True
"""
helps = ["--help", "-h", "--version"]
if "nt" == os.name:
helps.insert(0, "/?")
fakecmd = "fakecmd"
cmderr = strerr(fakecmd).replace(fakecmd, cmd)
... | def function[has, parameter[cmd]]:
constant[Returns true if the give shell command is available.
**Examples**:
::
auxly.shell.has("ls") # True
]
variable[helps] assign[=] list[[<ast.Constant object at 0x7da18bc72f80>, <ast.Constant object at 0x7da18bc73250>, <ast.Constant object at... | keyword[def] identifier[has] ( identifier[cmd] ):
literal[string]
identifier[helps] =[ literal[string] , literal[string] , literal[string] ]
keyword[if] literal[string] == identifier[os] . identifier[name] :
identifier[helps] . identifier[insert] ( literal[int] , literal[string] )
ident... | def has(cmd):
"""Returns true if the give shell command is available.
**Examples**:
::
auxly.shell.has("ls") # True
"""
helps = ['--help', '-h', '--version']
if 'nt' == os.name:
helps.insert(0, '/?') # depends on [control=['if'], data=[]]
fakecmd = 'fakecmd'
cmderr = s... |
def p_valueInitializer(p):
"""valueInitializer : identifier defaultValue ';'
| qualifierList identifier defaultValue ';'
"""
if len(p) == 4:
id_ = p[1]
val = p[2]
quals = []
else:
quals = p[1]
id_ = p[2]
val = p[... | def function[p_valueInitializer, parameter[p]]:
constant[valueInitializer : identifier defaultValue ';'
| qualifierList identifier defaultValue ';'
]
if compare[call[name[len], parameter[name[p]]] equal[==] constant[4]] begin[:]
variable[id... | keyword[def] identifier[p_valueInitializer] ( identifier[p] ):
literal[string]
keyword[if] identifier[len] ( identifier[p] )== literal[int] :
identifier[id_] = identifier[p] [ literal[int] ]
identifier[val] = identifier[p] [ literal[int] ]
identifier[quals] =[]
keyword[else... | def p_valueInitializer(p):
"""valueInitializer : identifier defaultValue ';'
| qualifierList identifier defaultValue ';'
"""
if len(p) == 4:
id_ = p[1]
val = p[2]
quals = [] # depends on [control=['if'], data=[]]
else:
quals = ... |
def window_poisson(N, alpha=2):
r"""Poisson tapering window
:param int N: window length
.. math:: w(n) = \exp^{-\alpha \frac{|n|}{N/2} }
with :math:`-N/2 \leq n \leq N/2`.
.. plot::
:width: 80%
:include-source:
from spectrum import window_visu
window_visu(64, 'po... | def function[window_poisson, parameter[N, alpha]]:
constant[Poisson tapering window
:param int N: window length
.. math:: w(n) = \exp^{-\alpha \frac{|n|}{N/2} }
with :math:`-N/2 \leq n \leq N/2`.
.. plot::
:width: 80%
:include-source:
from spectrum import window_visu... | keyword[def] identifier[window_poisson] ( identifier[N] , identifier[alpha] = literal[int] ):
literal[string]
identifier[n] = identifier[linspace] (- identifier[N] / literal[int] ,( identifier[N] )/ literal[int] , identifier[N] )
identifier[w] = identifier[exp] (- identifier[alpha] * identifier[abs] (... | def window_poisson(N, alpha=2):
"""Poisson tapering window
:param int N: window length
.. math:: w(n) = \\exp^{-\\alpha \\frac{|n|}{N/2} }
with :math:`-N/2 \\leq n \\leq N/2`.
.. plot::
:width: 80%
:include-source:
from spectrum import window_visu
window_visu(64,... |
def return_msg(self, reply_code, reply_text, exchange, routing_key):
'''
Return a failed message. Not named "return" because python interpreter
can't deal with that.
'''
args = Writer()
args.write_short(reply_code).\
write_shortstr(reply_text).\
w... | def function[return_msg, parameter[self, reply_code, reply_text, exchange, routing_key]]:
constant[
Return a failed message. Not named "return" because python interpreter
can't deal with that.
]
variable[args] assign[=] call[name[Writer], parameter[]]
call[call[call[call... | keyword[def] identifier[return_msg] ( identifier[self] , identifier[reply_code] , identifier[reply_text] , identifier[exchange] , identifier[routing_key] ):
literal[string]
identifier[args] = identifier[Writer] ()
identifier[args] . identifier[write_short] ( identifier[reply_code] ). ident... | def return_msg(self, reply_code, reply_text, exchange, routing_key):
"""
Return a failed message. Not named "return" because python interpreter
can't deal with that.
"""
args = Writer()
args.write_short(reply_code).write_shortstr(reply_text).write_shortstr(exchange).write_shortstr(r... |
def suggestions(self,index=None):
"""Get suggestions for correction.
Yields:
:class:`Suggestion` element that encapsulate the suggested annotations (if index is ``None``, default)
Returns:
a :class:`Suggestion` element that encapsulate the suggested annotations (if inde... | def function[suggestions, parameter[self, index]]:
constant[Get suggestions for correction.
Yields:
:class:`Suggestion` element that encapsulate the suggested annotations (if index is ``None``, default)
Returns:
a :class:`Suggestion` element that encapsulate the suggest... | keyword[def] identifier[suggestions] ( identifier[self] , identifier[index] = keyword[None] ):
literal[string]
keyword[if] identifier[index] keyword[is] keyword[None] :
keyword[return] identifier[self] . identifier[select] ( identifier[Suggestion] , keyword[None] , keyword[False] ,... | def suggestions(self, index=None):
"""Get suggestions for correction.
Yields:
:class:`Suggestion` element that encapsulate the suggested annotations (if index is ``None``, default)
Returns:
a :class:`Suggestion` element that encapsulate the suggested annotations (if index i... |
def human(value):
"If val>=1000 return val/1024+KiB, etc."
if value >= 1073741824000:
return '{:.1f} T'.format(value / 1099511627776.0)
if value >= 1048576000:
return '{:.1f} G'.format(value / 1073741824.0)
if value >= 1024000:
return '{:.1f} M'.format(value / 1048576.0)
if v... | def function[human, parameter[value]]:
constant[If val>=1000 return val/1024+KiB, etc.]
if compare[name[value] greater_or_equal[>=] constant[1073741824000]] begin[:]
return[call[constant[{:.1f} T].format, parameter[binary_operation[name[value] / constant[1099511627776.0]]]]]
if compare[n... | keyword[def] identifier[human] ( identifier[value] ):
literal[string]
keyword[if] identifier[value] >= literal[int] :
keyword[return] literal[string] . identifier[format] ( identifier[value] / literal[int] )
keyword[if] identifier[value] >= literal[int] :
keyword[return] literal[... | def human(value):
"""If val>=1000 return val/1024+KiB, etc."""
if value >= 1073741824000:
return '{:.1f} T'.format(value / 1099511627776.0) # depends on [control=['if'], data=['value']]
if value >= 1048576000:
return '{:.1f} G'.format(value / 1073741824.0) # depends on [control=['if'], dat... |
def remove_from_context(self, name, *args):
"""Remove attributes from a context.
"""
context = self.get_context(name=name)
attrs_ = context['context']
for a in args:
del attrs_[a] | def function[remove_from_context, parameter[self, name]]:
constant[Remove attributes from a context.
]
variable[context] assign[=] call[name[self].get_context, parameter[]]
variable[attrs_] assign[=] call[name[context]][constant[context]]
for taget[name[a]] in starred[name[args]]... | keyword[def] identifier[remove_from_context] ( identifier[self] , identifier[name] ,* identifier[args] ):
literal[string]
identifier[context] = identifier[self] . identifier[get_context] ( identifier[name] = identifier[name] )
identifier[attrs_] = identifier[context] [ literal[string] ]
... | def remove_from_context(self, name, *args):
"""Remove attributes from a context.
"""
context = self.get_context(name=name)
attrs_ = context['context']
for a in args:
del attrs_[a] # depends on [control=['for'], data=['a']] |
def _check_nested_blocks(self, node):
"""Update and check the number of nested blocks
"""
# only check block levels inside functions or methods
if not isinstance(node.scope(), astroid.FunctionDef):
return
# messages are triggered on leaving the nested block. Here we s... | def function[_check_nested_blocks, parameter[self, node]]:
constant[Update and check the number of nested blocks
]
if <ast.UnaryOp object at 0x7da1b028d600> begin[:]
return[None]
variable[nested_blocks] assign[=] call[name[self]._nested_blocks][<ast.Slice object at 0x7da1b028d900... | keyword[def] identifier[_check_nested_blocks] ( identifier[self] , identifier[node] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[node] . identifier[scope] (), identifier[astroid] . identifier[FunctionDef] ):
keyword[return]
... | def _check_nested_blocks(self, node):
"""Update and check the number of nested blocks
"""
# only check block levels inside functions or methods
if not isinstance(node.scope(), astroid.FunctionDef):
return # depends on [control=['if'], data=[]]
# messages are triggered on leaving the nes... |
def path(self, *args: typing.List[str]) -> typing.Union[None, str]:
"""
Creates an absolute path in the project source directory from the
relative path components.
:param args:
Relative components for creating a path within the project source
directory
:r... | def function[path, parameter[self]]:
constant[
Creates an absolute path in the project source directory from the
relative path components.
:param args:
Relative components for creating a path within the project source
directory
:return:
An abs... | keyword[def] identifier[path] ( identifier[self] ,* identifier[args] : identifier[typing] . identifier[List] [ identifier[str] ])-> identifier[typing] . identifier[Union] [ keyword[None] , identifier[str] ]:
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_project] :
... | def path(self, *args: typing.List[str]) -> typing.Union[None, str]:
"""
Creates an absolute path in the project source directory from the
relative path components.
:param args:
Relative components for creating a path within the project source
directory
:retur... |
def ng_dissim(a, b, X=None, membship=None):
"""Ng et al.'s dissimilarity measure, as presented in
Michael K. Ng, Mark Junjie Li, Joshua Zhexue Huang, and Zengyou He, "On the
Impact of Dissimilarity Measure in k-Modes Clustering Algorithm", IEEE
Transactions on Pattern Analysis and Machine Intelligence, ... | def function[ng_dissim, parameter[a, b, X, membship]]:
constant[Ng et al.'s dissimilarity measure, as presented in
Michael K. Ng, Mark Junjie Li, Joshua Zhexue Huang, and Zengyou He, "On the
Impact of Dissimilarity Measure in k-Modes Clustering Algorithm", IEEE
Transactions on Pattern Analysis and M... | keyword[def] identifier[ng_dissim] ( identifier[a] , identifier[b] , identifier[X] = keyword[None] , identifier[membship] = keyword[None] ):
literal[string]
keyword[if] identifier[membship] keyword[is] keyword[None] :
keyword[return] identifier[matching_dissim] ( identifier[a] , identifie... | def ng_dissim(a, b, X=None, membship=None):
"""Ng et al.'s dissimilarity measure, as presented in
Michael K. Ng, Mark Junjie Li, Joshua Zhexue Huang, and Zengyou He, "On the
Impact of Dissimilarity Measure in k-Modes Clustering Algorithm", IEEE
Transactions on Pattern Analysis and Machine Intelligence, ... |
def get_pfam_accession_numbers_from_pdb_id(self, pdb_id):
'''Note: an alternative is to use the RCSB API e.g. http://www.rcsb.org/pdb/rest/hmmer?structureId=1cdg.'''
pdb_id = pdb_id.lower()
if self.pdb_chain_to_pfam_mapping.get(pdb_id):
return self.pdb_chain_to_pfam_mapping[pdb_id].c... | def function[get_pfam_accession_numbers_from_pdb_id, parameter[self, pdb_id]]:
constant[Note: an alternative is to use the RCSB API e.g. http://www.rcsb.org/pdb/rest/hmmer?structureId=1cdg.]
variable[pdb_id] assign[=] call[name[pdb_id].lower, parameter[]]
if call[name[self].pdb_chain_to_pfam_map... | keyword[def] identifier[get_pfam_accession_numbers_from_pdb_id] ( identifier[self] , identifier[pdb_id] ):
literal[string]
identifier[pdb_id] = identifier[pdb_id] . identifier[lower] ()
keyword[if] identifier[self] . identifier[pdb_chain_to_pfam_mapping] . identifier[get] ( identifier[pdb... | def get_pfam_accession_numbers_from_pdb_id(self, pdb_id):
"""Note: an alternative is to use the RCSB API e.g. http://www.rcsb.org/pdb/rest/hmmer?structureId=1cdg."""
pdb_id = pdb_id.lower()
if self.pdb_chain_to_pfam_mapping.get(pdb_id):
return self.pdb_chain_to_pfam_mapping[pdb_id].copy() # depends... |
def path_to_node(tree, path):
"""FST node located at the given path"""
if path is None:
return None
node = tree
for key in path:
node = child_by_key(node, key)
return node | def function[path_to_node, parameter[tree, path]]:
constant[FST node located at the given path]
if compare[name[path] is constant[None]] begin[:]
return[constant[None]]
variable[node] assign[=] name[tree]
for taget[name[key]] in starred[name[path]] begin[:]
variab... | keyword[def] identifier[path_to_node] ( identifier[tree] , identifier[path] ):
literal[string]
keyword[if] identifier[path] keyword[is] keyword[None] :
keyword[return] keyword[None]
identifier[node] = identifier[tree]
keyword[for] identifier[key] keyword[in] identifier[path] :... | def path_to_node(tree, path):
"""FST node located at the given path"""
if path is None:
return None # depends on [control=['if'], data=[]]
node = tree
for key in path:
node = child_by_key(node, key) # depends on [control=['for'], data=['key']]
return node |
def gradient_lonlat(self, data, nit=3, tol=1.0e-3, guarantee_convergence=False):
"""
Return the lon / lat components of the gradient
of a scalar field on the surface of the sphere.
The method consists of minimizing a quadratic functional Q(G) over
gradient vectors, where Q is a... | def function[gradient_lonlat, parameter[self, data, nit, tol, guarantee_convergence]]:
constant[
Return the lon / lat components of the gradient
of a scalar field on the surface of the sphere.
The method consists of minimizing a quadratic functional Q(G) over
gradient vectors, ... | keyword[def] identifier[gradient_lonlat] ( identifier[self] , identifier[data] , identifier[nit] = literal[int] , identifier[tol] = literal[int] , identifier[guarantee_convergence] = keyword[False] ):
literal[string]
identifier[dfxs] , identifier[dfys] , identifier[dfzs] = identifier[self] . ident... | def gradient_lonlat(self, data, nit=3, tol=0.001, guarantee_convergence=False):
"""
Return the lon / lat components of the gradient
of a scalar field on the surface of the sphere.
The method consists of minimizing a quadratic functional Q(G) over
gradient vectors, where Q is an app... |
def encode(self, key):
"""Encodes a user key into a particular format. The result of this method
will be used by swauth for storing user credentials.
If salt is not manually set in conf file, a random salt will be
generated and used.
:param key: User's secret key
:retur... | def function[encode, parameter[self, key]]:
constant[Encodes a user key into a particular format. The result of this method
will be used by swauth for storing user credentials.
If salt is not manually set in conf file, a random salt will be
generated and used.
:param key: User'... | keyword[def] identifier[encode] ( identifier[self] , identifier[key] ):
literal[string]
identifier[salt] = identifier[self] . identifier[salt] keyword[or] identifier[os] . identifier[urandom] ( literal[int] ). identifier[encode] ( literal[string] ). identifier[rstrip] ()
keyword[return] ... | def encode(self, key):
"""Encodes a user key into a particular format. The result of this method
will be used by swauth for storing user credentials.
If salt is not manually set in conf file, a random salt will be
generated and used.
:param key: User's secret key
:returns: ... |
def on_result(self, task, result):
'''Called every result'''
if not result:
return
if 'taskid' in task and 'project' in task and 'url' in task:
logger.info('result %s:%s %s -> %.30r' % (
task['project'], task['taskid'], task['url'], result))
pr... | def function[on_result, parameter[self, task, result]]:
constant[Called every result]
if <ast.UnaryOp object at 0x7da207f9ae60> begin[:]
return[None]
if <ast.BoolOp object at 0x7da207f9a680> begin[:]
call[name[logger].info, parameter[binary_operation[constant[result %s:%s... | keyword[def] identifier[on_result] ( identifier[self] , identifier[task] , identifier[result] ):
literal[string]
keyword[if] keyword[not] identifier[result] :
keyword[return]
keyword[if] literal[string] keyword[in] identifier[task] keyword[and] literal[string] keyword... | def on_result(self, task, result):
"""Called every result"""
if not result:
return # depends on [control=['if'], data=[]]
if 'taskid' in task and 'project' in task and ('url' in task):
logger.info('result %s:%s %s -> %.30r' % (task['project'], task['taskid'], task['url'], result))
p... |
def sym_log_map(cls, q, p):
"""Quaternion symmetrized logarithm map.
Find the symmetrized logarithm map on the quaternion Riemannian manifold.
Params:
q: the base point at which the logarithm is computed, i.e.
a Quaternion object
p: the argument of the... | def function[sym_log_map, parameter[cls, q, p]]:
constant[Quaternion symmetrized logarithm map.
Find the symmetrized logarithm map on the quaternion Riemannian manifold.
Params:
q: the base point at which the logarithm is computed, i.e.
a Quaternion object
... | keyword[def] identifier[sym_log_map] ( identifier[cls] , identifier[q] , identifier[p] ):
literal[string]
identifier[inv_sqrt_q] =( identifier[q] **(- literal[int] ))
keyword[return] identifier[Quaternion] . identifier[log] ( identifier[inv_sqrt_q] * identifier[p] * identifier[inv_sqrt_q]... | def sym_log_map(cls, q, p):
"""Quaternion symmetrized logarithm map.
Find the symmetrized logarithm map on the quaternion Riemannian manifold.
Params:
q: the base point at which the logarithm is computed, i.e.
a Quaternion object
p: the argument of the qua... |
def _find_source(method):
''' find source code of a given method
Find and extract the source code of a given method in a module.
Uses inspect.findsource to get all source code and performs some
selection magic to identify method source code. Doing it this way
because in... | def function[_find_source, parameter[method]]:
constant[ find source code of a given method
Find and extract the source code of a given method in a module.
Uses inspect.findsource to get all source code and performs some
selection magic to identify method source code. Doing it ... | keyword[def] identifier[_find_source] ( identifier[method] ):
literal[string]
identifier[source] = identifier[inspect] . identifier[findsource] ( identifier[method] )
identifier[is_method] = identifier[inspect] . identifier[ismethod] ( identifier[method] )
ident... | def _find_source(method):
""" find source code of a given method
Find and extract the source code of a given method in a module.
Uses inspect.findsource to get all source code and performs some
selection magic to identify method source code. Doing it this way
because inspec... |
def assignValue(cfg, playerValue, otherValue):
"""artificially determine match results given match circumstances.
WARNING: cheating will be detected and your player will be banned from server"""
player = cfg.whoAmI()
result = {}
for p in cfg.players:
if p.name == player.name: val = playerV... | def function[assignValue, parameter[cfg, playerValue, otherValue]]:
constant[artificially determine match results given match circumstances.
WARNING: cheating will be detected and your player will be banned from server]
variable[player] assign[=] call[name[cfg].whoAmI, parameter[]]
variable[... | keyword[def] identifier[assignValue] ( identifier[cfg] , identifier[playerValue] , identifier[otherValue] ):
literal[string]
identifier[player] = identifier[cfg] . identifier[whoAmI] ()
identifier[result] ={}
keyword[for] identifier[p] keyword[in] identifier[cfg] . identifier[players] :
... | def assignValue(cfg, playerValue, otherValue):
"""artificially determine match results given match circumstances.
WARNING: cheating will be detected and your player will be banned from server"""
player = cfg.whoAmI()
result = {}
for p in cfg.players:
if p.name == player.name:
val... |
def f(self, y, t):
"""Deterministic term f of the complete network system
dy = f(y, t)dt + G(y, t).dot(dW)
(or for an ODE network system without noise, dy/dt = f(y, t))
Args:
y (array of shape (d,)): where d is the dimension of the overall
state space of the compl... | def function[f, parameter[self, y, t]]:
constant[Deterministic term f of the complete network system
dy = f(y, t)dt + G(y, t).dot(dW)
(or for an ODE network system without noise, dy/dt = f(y, t))
Args:
y (array of shape (d,)): where d is the dimension of the overall
... | keyword[def] identifier[f] ( identifier[self] , identifier[y] , identifier[t] ):
literal[string]
identifier[coupling] = identifier[self] . identifier[coupling_function] [ literal[int] ]
identifier[res] = identifier[np] . identifier[empty_like] ( identifier[self] . identifier[y0] )
... | def f(self, y, t):
"""Deterministic term f of the complete network system
dy = f(y, t)dt + G(y, t).dot(dW)
(or for an ODE network system without noise, dy/dt = f(y, t))
Args:
y (array of shape (d,)): where d is the dimension of the overall
state space of the complete ... |
def decode(enc):
'''Decode a base58 string (ex: a Monero address) into hexidecimal form.'''
enc = bytearray(enc, encoding='ascii')
l_enc = len(enc)
if l_enc == 0:
return ""
full_block_count = l_enc // __fullEncodedBlockSize
last_block_size = l_enc % __fullEncodedBlockSize
try:
... | def function[decode, parameter[enc]]:
constant[Decode a base58 string (ex: a Monero address) into hexidecimal form.]
variable[enc] assign[=] call[name[bytearray], parameter[name[enc]]]
variable[l_enc] assign[=] call[name[len], parameter[name[enc]]]
if compare[name[l_enc] equal[==] consta... | keyword[def] identifier[decode] ( identifier[enc] ):
literal[string]
identifier[enc] = identifier[bytearray] ( identifier[enc] , identifier[encoding] = literal[string] )
identifier[l_enc] = identifier[len] ( identifier[enc] )
keyword[if] identifier[l_enc] == literal[int] :
keyword[retu... | def decode(enc):
"""Decode a base58 string (ex: a Monero address) into hexidecimal form."""
enc = bytearray(enc, encoding='ascii')
l_enc = len(enc)
if l_enc == 0:
return '' # depends on [control=['if'], data=[]]
full_block_count = l_enc // __fullEncodedBlockSize
last_block_size = l_enc ... |
def get_collection(self, session, query, api_key):
"""
Fetch a collection of resources of a specified type.
:param session: SQLAlchemy session
:param query: Dict of query args
:param api_type: The type of the model
"""
model = self._fetch_model(api_key)
i... | def function[get_collection, parameter[self, session, query, api_key]]:
constant[
Fetch a collection of resources of a specified type.
:param session: SQLAlchemy session
:param query: Dict of query args
:param api_type: The type of the model
]
variable[model] ass... | keyword[def] identifier[get_collection] ( identifier[self] , identifier[session] , identifier[query] , identifier[api_key] ):
literal[string]
identifier[model] = identifier[self] . identifier[_fetch_model] ( identifier[api_key] )
identifier[include] = identifier[self] . identifier[_parse_i... | def get_collection(self, session, query, api_key):
"""
Fetch a collection of resources of a specified type.
:param session: SQLAlchemy session
:param query: Dict of query args
:param api_type: The type of the model
"""
model = self._fetch_model(api_key)
include = sel... |
def _new_mock_response(self, response, file_path):
'''Return a new mock Response with the content.'''
mock_response = copy.copy(response)
mock_response.body = Body(open(file_path, 'rb'))
mock_response.fields = NameValueRecord()
for name, value in response.fields.get_all():
... | def function[_new_mock_response, parameter[self, response, file_path]]:
constant[Return a new mock Response with the content.]
variable[mock_response] assign[=] call[name[copy].copy, parameter[name[response]]]
name[mock_response].body assign[=] call[name[Body], parameter[call[name[open], paramet... | keyword[def] identifier[_new_mock_response] ( identifier[self] , identifier[response] , identifier[file_path] ):
literal[string]
identifier[mock_response] = identifier[copy] . identifier[copy] ( identifier[response] )
identifier[mock_response] . identifier[body] = identifier[Body] ( ident... | def _new_mock_response(self, response, file_path):
"""Return a new mock Response with the content."""
mock_response = copy.copy(response)
mock_response.body = Body(open(file_path, 'rb'))
mock_response.fields = NameValueRecord()
for (name, value) in response.fields.get_all():
mock_response.fi... |
def save(self, filename):
"""
saves the instance of the script to a file using pickle
Args:
filename: target filename
"""
if filename is None:
filename = self.filename('.b26s')
# if len(filename.split('\\\\?\\')) == 1:
# filename = '\... | def function[save, parameter[self, filename]]:
constant[
saves the instance of the script to a file using pickle
Args:
filename: target filename
]
if compare[name[filename] is constant[None]] begin[:]
variable[filename] assign[=] call[name[self].filen... | keyword[def] identifier[save] ( identifier[self] , identifier[filename] ):
literal[string]
keyword[if] identifier[filename] keyword[is] keyword[None] :
identifier[filename] = identifier[self] . identifier[filename] ( literal[string] )
keyword[with... | def save(self, filename):
"""
saves the instance of the script to a file using pickle
Args:
filename: target filename
"""
if filename is None:
filename = self.filename('.b26s') # depends on [control=['if'], data=['filename']]
# if len(filename.split('\\\\?\\')) ... |
def GetConsoleOriginalTitle() -> str:
"""
GetConsoleOriginalTitle from Win32.
Return str.
Only available on Windows Vista or higher.
"""
if IsNT6orHigher:
arrayType = ctypes.c_wchar * MAX_PATH
values = arrayType()
ctypes.windll.kernel32.GetConsoleOriginalTitleW(values, MA... | def function[GetConsoleOriginalTitle, parameter[]]:
constant[
GetConsoleOriginalTitle from Win32.
Return str.
Only available on Windows Vista or higher.
]
if name[IsNT6orHigher] begin[:]
variable[arrayType] assign[=] binary_operation[name[ctypes].c_wchar * name[MAX_PATH]]... | keyword[def] identifier[GetConsoleOriginalTitle] ()-> identifier[str] :
literal[string]
keyword[if] identifier[IsNT6orHigher] :
identifier[arrayType] = identifier[ctypes] . identifier[c_wchar] * identifier[MAX_PATH]
identifier[values] = identifier[arrayType] ()
identifier[ctype... | def GetConsoleOriginalTitle() -> str:
"""
GetConsoleOriginalTitle from Win32.
Return str.
Only available on Windows Vista or higher.
"""
if IsNT6orHigher:
arrayType = ctypes.c_wchar * MAX_PATH
values = arrayType()
ctypes.windll.kernel32.GetConsoleOriginalTitleW(values, MA... |
def refresh(self):
"""Refresh the cache by deleting the old one and creating a new one.
"""
if self.exists:
self.delete()
self.populate()
self.open() | def function[refresh, parameter[self]]:
constant[Refresh the cache by deleting the old one and creating a new one.
]
if name[self].exists begin[:]
call[name[self].delete, parameter[]]
call[name[self].populate, parameter[]]
call[name[self].open, parameter[]] | keyword[def] identifier[refresh] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[exists] :
identifier[self] . identifier[delete] ()
identifier[self] . identifier[populate] ()
identifier[self] . identifier[open] () | def refresh(self):
"""Refresh the cache by deleting the old one and creating a new one.
"""
if self.exists:
self.delete() # depends on [control=['if'], data=[]]
self.populate()
self.open() |
def _calculate(cls, start=None, end=None):
"""
calculate the difference between starting and ending time.
:param start: A starting time.
:type start: int|str
:param stop: A ending time.
:type stop: int|str
:return:
A dict with following as index.
... | def function[_calculate, parameter[cls, start, end]]:
constant[
calculate the difference between starting and ending time.
:param start: A starting time.
:type start: int|str
:param stop: A ending time.
:type stop: int|str
:return:
A dict with follo... | keyword[def] identifier[_calculate] ( identifier[cls] , identifier[start] = keyword[None] , identifier[end] = keyword[None] ):
literal[string]
keyword[if] identifier[start] keyword[and] identifier[end] :
identifier[time_difference] = identifier[int] ( identifier[... | def _calculate(cls, start=None, end=None):
"""
calculate the difference between starting and ending time.
:param start: A starting time.
:type start: int|str
:param stop: A ending time.
:type stop: int|str
:return:
A dict with following as index.
... |
def get_runs_by_id(self, config_id):
"""
returns a list of runs for a given config id
The runs are sorted by ascending budget, so '-1' will give
the longest run for this config.
"""
d = self.data[config_id]
runs = []
for b in d.results.keys():
try:
err_logs = d.exceptions.get(b, None)
if d... | def function[get_runs_by_id, parameter[self, config_id]]:
constant[
returns a list of runs for a given config id
The runs are sorted by ascending budget, so '-1' will give
the longest run for this config.
]
variable[d] assign[=] call[name[self].data][name[config_id]]
variable[runs] assi... | keyword[def] identifier[get_runs_by_id] ( identifier[self] , identifier[config_id] ):
literal[string]
identifier[d] = identifier[self] . identifier[data] [ identifier[config_id] ]
identifier[runs] =[]
keyword[for] identifier[b] keyword[in] identifier[d] . identifier[results] . identifier[keys] ():
... | def get_runs_by_id(self, config_id):
"""
returns a list of runs for a given config id
The runs are sorted by ascending budget, so '-1' will give
the longest run for this config.
"""
d = self.data[config_id]
runs = []
for b in d.results.keys():
try:
err_logs = d.exceptions.ge... |
def write_geoff(discoursegraph, output_file):
"""
converts a DiscourseDocumentGraph into a Geoff file and
writes it to the given file (or file path).
"""
if isinstance(output_file, str):
with open(output_file, 'w') as outfile:
outfile.write(convert_to_geoff(discoursegraph))
e... | def function[write_geoff, parameter[discoursegraph, output_file]]:
constant[
converts a DiscourseDocumentGraph into a Geoff file and
writes it to the given file (or file path).
]
if call[name[isinstance], parameter[name[output_file], name[str]]] begin[:]
with call[name[open],... | keyword[def] identifier[write_geoff] ( identifier[discoursegraph] , identifier[output_file] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[output_file] , identifier[str] ):
keyword[with] identifier[open] ( identifier[output_file] , literal[string] ) keyword[as] identifier[ou... | def write_geoff(discoursegraph, output_file):
"""
converts a DiscourseDocumentGraph into a Geoff file and
writes it to the given file (or file path).
"""
if isinstance(output_file, str):
with open(output_file, 'w') as outfile:
outfile.write(convert_to_geoff(discoursegraph)) # de... |
def loudness(self):
"""bool: The Sonos speaker's loudness compensation.
True if on, False otherwise.
Loudness is a complicated topic. You can find a nice summary about this
feature here: http://forums.sonos.com/showthread.php?p=4698#post4698
"""
response = self.renderin... | def function[loudness, parameter[self]]:
constant[bool: The Sonos speaker's loudness compensation.
True if on, False otherwise.
Loudness is a complicated topic. You can find a nice summary about this
feature here: http://forums.sonos.com/showthread.php?p=4698#post4698
]
... | keyword[def] identifier[loudness] ( identifier[self] ):
literal[string]
identifier[response] = identifier[self] . identifier[renderingControl] . identifier[GetLoudness] ([
( literal[string] , literal[int] ),
( literal[string] , literal[string] ),
])
identifier[loudn... | def loudness(self):
"""bool: The Sonos speaker's loudness compensation.
True if on, False otherwise.
Loudness is a complicated topic. You can find a nice summary about this
feature here: http://forums.sonos.com/showthread.php?p=4698#post4698
"""
response = self.renderingControl... |
def id_generator(size=15, random_state=None):
"""Helper function to generate random div ids. This is useful for embedding
HTML into ipython notebooks."""
chars = list(string.ascii_uppercase + string.digits)
return ''.join(random_state.choice(chars, size, replace=True)) | def function[id_generator, parameter[size, random_state]]:
constant[Helper function to generate random div ids. This is useful for embedding
HTML into ipython notebooks.]
variable[chars] assign[=] call[name[list], parameter[binary_operation[name[string].ascii_uppercase + name[string].digits]]]
r... | keyword[def] identifier[id_generator] ( identifier[size] = literal[int] , identifier[random_state] = keyword[None] ):
literal[string]
identifier[chars] = identifier[list] ( identifier[string] . identifier[ascii_uppercase] + identifier[string] . identifier[digits] )
keyword[return] literal[string] . i... | def id_generator(size=15, random_state=None):
"""Helper function to generate random div ids. This is useful for embedding
HTML into ipython notebooks."""
chars = list(string.ascii_uppercase + string.digits)
return ''.join(random_state.choice(chars, size, replace=True)) |
def red(self, value):
"""gets/sets the red value"""
if value != self._red and \
isinstance(value, int):
self._red = value | def function[red, parameter[self, value]]:
constant[gets/sets the red value]
if <ast.BoolOp object at 0x7da18dc9ba30> begin[:]
name[self]._red assign[=] name[value] | keyword[def] identifier[red] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[value] != identifier[self] . identifier[_red] keyword[and] identifier[isinstance] ( identifier[value] , identifier[int] ):
identifier[self] . identifier[_red] = identifier[v... | def red(self, value):
"""gets/sets the red value"""
if value != self._red and isinstance(value, int):
self._red = value # depends on [control=['if'], data=[]] |
def auto_complete_paths(current, completion_type):
"""If ``completion_type`` is ``file`` or ``path``, list all regular files
and directories starting with ``current``; otherwise only list directories
starting with ``current``.
:param current: The word to be completed
:param completion_type: path co... | def function[auto_complete_paths, parameter[current, completion_type]]:
constant[If ``completion_type`` is ``file`` or ``path``, list all regular files
and directories starting with ``current``; otherwise only list directories
starting with ``current``.
:param current: The word to be completed
... | keyword[def] identifier[auto_complete_paths] ( identifier[current] , identifier[completion_type] ):
literal[string]
identifier[directory] , identifier[filename] = identifier[os] . identifier[path] . identifier[split] ( identifier[current] )
identifier[current_path] = identifier[os] . identifier[path] ... | def auto_complete_paths(current, completion_type):
"""If ``completion_type`` is ``file`` or ``path``, list all regular files
and directories starting with ``current``; otherwise only list directories
starting with ``current``.
:param current: The word to be completed
:param completion_type: path co... |
def request(self, *args, **kwargs):
"""
Define a Decorate to be called before a request.
eg: @middleware.request
"""
middleware = args[0]
@wraps(middleware)
def register_middleware(*args, **kwargs):
self.request_middleware.append(middleware)
... | def function[request, parameter[self]]:
constant[
Define a Decorate to be called before a request.
eg: @middleware.request
]
variable[middleware] assign[=] call[name[args]][constant[0]]
def function[register_middleware, parameter[]]:
call[name[self].reques... | keyword[def] identifier[request] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[middleware] = identifier[args] [ literal[int] ]
@ identifier[wraps] ( identifier[middleware] )
keyword[def] identifier[register_middleware] (* identifier[a... | def request(self, *args, **kwargs):
"""
Define a Decorate to be called before a request.
eg: @middleware.request
"""
middleware = args[0]
@wraps(middleware)
def register_middleware(*args, **kwargs):
self.request_middleware.append(middleware)
return middleware
... |
def parse_file(infile, exit_on_error=True):
"""Parse a comma-separated file with columns "ra,dec,magnitude".
"""
try:
a, b, mag = np.atleast_2d(
np.genfromtxt(
infile,
usecols=[0, 1, 2],
... | def function[parse_file, parameter[infile, exit_on_error]]:
constant[Parse a comma-separated file with columns "ra,dec,magnitude".
]
<ast.Try object at 0x7da1b0b82c50>
return[tuple[[<ast.Name object at 0x7da1b0a22290>, <ast.Name object at 0x7da1b0a22bc0>, <ast.Name object at 0x7da1b0a22110>]]] | keyword[def] identifier[parse_file] ( identifier[infile] , identifier[exit_on_error] = keyword[True] ):
literal[string]
keyword[try] :
identifier[a] , identifier[b] , identifier[mag] = identifier[np] . identifier[atleast_2d] (
identifier[np] . identifier[genfromtxt] (
identifier[... | def parse_file(infile, exit_on_error=True):
"""Parse a comma-separated file with columns "ra,dec,magnitude".
"""
try:
(a, b, mag) = np.atleast_2d(np.genfromtxt(infile, usecols=[0, 1, 2], delimiter=',')).T # depends on [control=['try'], data=[]]
except IOError as e:
if exit_on_error:
... |
def as_dict(self):
"""
A JSON serializable dict representation of self.
"""
return {"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"operation": self.operation, "title": self.title,
"xc": self.xc.as_dict(), "basis_s... | def function[as_dict, parameter[self]]:
constant[
A JSON serializable dict representation of self.
]
return[dictionary[[<ast.Constant object at 0x7da18bc700d0>, <ast.Constant object at 0x7da18bc73d90>, <ast.Constant object at 0x7da18bc72a10>, <ast.Constant object at 0x7da18bc73070>, <ast.Con... | keyword[def] identifier[as_dict] ( identifier[self] ):
literal[string]
keyword[return] { literal[string] : identifier[self] . identifier[__class__] . identifier[__module__] ,
literal[string] : identifier[self] . identifier[__class__] . identifier[__name__] ,
literal[string] : iden... | def as_dict(self):
"""
A JSON serializable dict representation of self.
"""
return {'@module': self.__class__.__module__, '@class': self.__class__.__name__, 'operation': self.operation, 'title': self.title, 'xc': self.xc.as_dict(), 'basis_set': self.basis_set.as_dict(), 'units': self.units.as_di... |
async def commission(
self, *, enable_ssh: bool = None, skip_networking: bool = None,
skip_storage: bool = None,
commissioning_scripts: typing.Sequence[str] = None,
testing_scripts: typing.Sequence[str] = None,
wait: bool = False, wait_interval: int = 5):
... | <ast.AsyncFunctionDef object at 0x7da20c6c4c40> | keyword[async] keyword[def] identifier[commission] (
identifier[self] ,*, identifier[enable_ssh] : identifier[bool] = keyword[None] , identifier[skip_networking] : identifier[bool] = keyword[None] ,
identifier[skip_storage] : identifier[bool] = keyword[None] ,
identifier[commissioning_scripts] : identifier[typing... | async def commission(self, *, enable_ssh: bool=None, skip_networking: bool=None, skip_storage: bool=None, commissioning_scripts: typing.Sequence[str]=None, testing_scripts: typing.Sequence[str]=None, wait: bool=False, wait_interval: int=5):
"""Commission this machine.
:param enable_ssh: Prevent the machine... |
def download_links(self, dir_path):
"""Download web pages or images from search result links.
Args:
dir_path (str):
Path of directory to save downloads of :class:`api.results`.links
"""
links = self.links
if not path.exists(dir_path):
makedirs(dir_path)
for i, url in enu... | def function[download_links, parameter[self, dir_path]]:
constant[Download web pages or images from search result links.
Args:
dir_path (str):
Path of directory to save downloads of :class:`api.results`.links
]
variable[links] assign[=] name[self].links
if <ast.UnaryOp... | keyword[def] identifier[download_links] ( identifier[self] , identifier[dir_path] ):
literal[string]
identifier[links] = identifier[self] . identifier[links]
keyword[if] keyword[not] identifier[path] . identifier[exists] ( identifier[dir_path] ):
identifier[makedirs] ( identifier[dir_path] )... | def download_links(self, dir_path):
"""Download web pages or images from search result links.
Args:
dir_path (str):
Path of directory to save downloads of :class:`api.results`.links
"""
links = self.links
if not path.exists(dir_path):
makedirs(dir_path) # depends on [cont... |
def get_security_file(filename, profile='default'):
"""Return the absolute path of a security file given by filename and profile
This allows users and developers to find security files without
knowledge of the IPython directory structure. The search path
will be ['.', profile.security_dir]
... | def function[get_security_file, parameter[filename, profile]]:
constant[Return the absolute path of a security file given by filename and profile
This allows users and developers to find security files without
knowledge of the IPython directory structure. The search path
will be ['.', profile.s... | keyword[def] identifier[get_security_file] ( identifier[filename] , identifier[profile] = literal[string] ):
literal[string]
keyword[from] identifier[IPython] . identifier[core] . identifier[profiledir] keyword[import] identifier[ProfileDir]
keyword[try] :
identifier[pd] = identifier... | def get_security_file(filename, profile='default'):
"""Return the absolute path of a security file given by filename and profile
This allows users and developers to find security files without
knowledge of the IPython directory structure. The search path
will be ['.', profile.security_dir]
... |
def _populate_bunch_with_element(element):
"""
Helper function to recursively populates a Bunch from an XML tree.
Returns leaf XML elements as a simple value, branch elements are returned
as Bunches containing their subelements as value or recursively generated
Bunch members.
"""
if 'value' ... | def function[_populate_bunch_with_element, parameter[element]]:
constant[
Helper function to recursively populates a Bunch from an XML tree.
Returns leaf XML elements as a simple value, branch elements are returned
as Bunches containing their subelements as value or recursively generated
Bunch m... | keyword[def] identifier[_populate_bunch_with_element] ( identifier[element] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[element] . identifier[attrib] :
keyword[return] identifier[element] . identifier[get] ( literal[string] )
identifier[current_bunch] = identifie... | def _populate_bunch_with_element(element):
"""
Helper function to recursively populates a Bunch from an XML tree.
Returns leaf XML elements as a simple value, branch elements are returned
as Bunches containing their subelements as value or recursively generated
Bunch members.
"""
if 'value' ... |
def compare_nouns(self, word1, word2):
"""
compare word1 and word2 for equality regardless of plurality
word1 and word2 are to be treated as nouns
return values:
eq - the strings are equal
p:s - word1 is the plural of word2
s:p - word2 is the plural of word1
... | def function[compare_nouns, parameter[self, word1, word2]]:
constant[
compare word1 and word2 for equality regardless of plurality
word1 and word2 are to be treated as nouns
return values:
eq - the strings are equal
p:s - word1 is the plural of word2
s:p - word2 ... | keyword[def] identifier[compare_nouns] ( identifier[self] , identifier[word1] , identifier[word2] ):
literal[string]
keyword[return] identifier[self] . identifier[_plequal] ( identifier[word1] , identifier[word2] , identifier[self] . identifier[plural_noun] ) | def compare_nouns(self, word1, word2):
"""
compare word1 and word2 for equality regardless of plurality
word1 and word2 are to be treated as nouns
return values:
eq - the strings are equal
p:s - word1 is the plural of word2
s:p - word2 is the plural of word1
... |
def loss(self, xs, ys):
"""Computes the loss of the network."""
return float(
self.sess.run(
self.cross_entropy, feed_dict={
self.x: xs,
self.y_: ys
})) | def function[loss, parameter[self, xs, ys]]:
constant[Computes the loss of the network.]
return[call[name[float], parameter[call[name[self].sess.run, parameter[name[self].cross_entropy]]]]] | keyword[def] identifier[loss] ( identifier[self] , identifier[xs] , identifier[ys] ):
literal[string]
keyword[return] identifier[float] (
identifier[self] . identifier[sess] . identifier[run] (
identifier[self] . identifier[cross_entropy] , identifier[feed_dict] ={
ident... | def loss(self, xs, ys):
"""Computes the loss of the network."""
return float(self.sess.run(self.cross_entropy, feed_dict={self.x: xs, self.y_: ys})) |
def main():
"""
Command line interface.
"""
parser = argparse.ArgumentParser(
description='monoseq: pretty-printing DNA and protein sequences',
epilog='If INPUT is in FASTA format, each record is pretty-printed '
'after printing its name and ANNOTATION (if supplied) is used by '
... | def function[main, parameter[]]:
constant[
Command line interface.
]
variable[parser] assign[=] call[name[argparse].ArgumentParser, parameter[]]
call[name[parser].add_argument, parameter[constant[sequence_file]]]
call[name[parser].add_argument, parameter[constant[-b], constant[--... | keyword[def] identifier[main] ():
literal[string]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] (
identifier[description] = literal[string] ,
identifier[epilog] = literal[string]
literal[string]
literal[string]
literal[string] )
identifier[parser] .... | def main():
"""
Command line interface.
"""
parser = argparse.ArgumentParser(description='monoseq: pretty-printing DNA and protein sequences', epilog='If INPUT is in FASTA format, each record is pretty-printed after printing its name and ANNOTATION (if supplied) is used by matching chromosome/record nam... |
def _dereference(cls, documents, references):
"""Dereference one or more documents"""
# Dereference each reference
for path, projection in references.items():
# Check there is a $ref in the projection, else skip it
if '$ref' not in projection:
continue
... | def function[_dereference, parameter[cls, documents, references]]:
constant[Dereference one or more documents]
for taget[tuple[[<ast.Name object at 0x7da1b0c77f70>, <ast.Name object at 0x7da1b0c77b50>]]] in starred[call[name[references].items, parameter[]]] begin[:]
if compare[constant[$... | keyword[def] identifier[_dereference] ( identifier[cls] , identifier[documents] , identifier[references] ):
literal[string]
keyword[for] identifier[path] , identifier[projection] keyword[in] identifier[references] . identifier[items] ():
keyword[if] literal[stri... | def _dereference(cls, documents, references):
"""Dereference one or more documents"""
# Dereference each reference
for (path, projection) in references.items():
# Check there is a $ref in the projection, else skip it
if '$ref' not in projection:
continue # depends on [control=['... |
def block_specification_to_number(block: BlockSpecification, web3: Web3) -> BlockNumber:
""" Converts a block specification to an actual block number """
if isinstance(block, str):
msg = f"string block specification can't contain {block}"
assert block in ('latest', 'pending'), msg
number... | def function[block_specification_to_number, parameter[block, web3]]:
constant[ Converts a block specification to an actual block number ]
if call[name[isinstance], parameter[name[block], name[str]]] begin[:]
variable[msg] assign[=] <ast.JoinedStr object at 0x7da1b19b80d0>
assert[... | keyword[def] identifier[block_specification_to_number] ( identifier[block] : identifier[BlockSpecification] , identifier[web3] : identifier[Web3] )-> identifier[BlockNumber] :
literal[string]
keyword[if] identifier[isinstance] ( identifier[block] , identifier[str] ):
identifier[msg] = literal[str... | def block_specification_to_number(block: BlockSpecification, web3: Web3) -> BlockNumber:
""" Converts a block specification to an actual block number """
if isinstance(block, str):
msg = f"string block specification can't contain {block}"
assert block in ('latest', 'pending'), msg
number... |
def select_option(self):
""" Select this node if it is an option element inside a select tag. """
if self.disabled:
warn("Attempt to select disabled option: {}".format(self.value or self.text))
self.base.select_option() | def function[select_option, parameter[self]]:
constant[ Select this node if it is an option element inside a select tag. ]
if name[self].disabled begin[:]
call[name[warn], parameter[call[constant[Attempt to select disabled option: {}].format, parameter[<ast.BoolOp object at 0x7da1b021686... | keyword[def] identifier[select_option] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[disabled] :
identifier[warn] ( literal[string] . identifier[format] ( identifier[self] . identifier[value] keyword[or] identifier[self] . identifier[text] ))
... | def select_option(self):
""" Select this node if it is an option element inside a select tag. """
if self.disabled:
warn('Attempt to select disabled option: {}'.format(self.value or self.text)) # depends on [control=['if'], data=[]]
self.base.select_option() |
def modem_configuration(self, host, port):
"""Set the host:port for the Cellular device to send data to.
Returns True if the command was successful.
"""
request = {
"command": "modem_configuration",
"host": host,
"port": port
}
status ... | def function[modem_configuration, parameter[self, host, port]]:
constant[Set the host:port for the Cellular device to send data to.
Returns True if the command was successful.
]
variable[request] assign[=] dictionary[[<ast.Constant object at 0x7da1b1b84730>, <ast.Constant object at 0x7d... | keyword[def] identifier[modem_configuration] ( identifier[self] , identifier[host] , identifier[port] ):
literal[string]
identifier[request] ={
literal[string] : literal[string] ,
literal[string] : identifier[host] ,
literal[string] : identifier[port]
}
... | def modem_configuration(self, host, port):
"""Set the host:port for the Cellular device to send data to.
Returns True if the command was successful.
"""
request = {'command': 'modem_configuration', 'host': host, 'port': port}
status = self._check_command_response_status(request)
return ... |
def to_chunks(self, df, chunk_size='D', func=None, **kwargs):
"""
chunks the dataframe/series by dates
Parameters
----------
df: pandas dataframe or series
chunk_size: str
any valid Pandas frequency string
func: function
func will be appli... | def function[to_chunks, parameter[self, df, chunk_size, func]]:
constant[
chunks the dataframe/series by dates
Parameters
----------
df: pandas dataframe or series
chunk_size: str
any valid Pandas frequency string
func: function
func will ... | keyword[def] identifier[to_chunks] ( identifier[self] , identifier[df] , identifier[chunk_size] = literal[string] , identifier[func] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[df] . identifier[index] . identifier[names] :
... | def to_chunks(self, df, chunk_size='D', func=None, **kwargs):
"""
chunks the dataframe/series by dates
Parameters
----------
df: pandas dataframe or series
chunk_size: str
any valid Pandas frequency string
func: function
func will be applied t... |
def errinfo(msmt):
"""Return (limtype, repval, errval1, errval2). Like m_liminfo, but also
provides error bar information for values that have it."""
if isinstance(msmt, Textual):
msmt = msmt.unwrap()
if np.isscalar(msmt):
return 0, msmt, msmt, msmt
if isinstance(msmt, Uval):
... | def function[errinfo, parameter[msmt]]:
constant[Return (limtype, repval, errval1, errval2). Like m_liminfo, but also
provides error bar information for values that have it.]
if call[name[isinstance], parameter[name[msmt], name[Textual]]] begin[:]
variable[msmt] assign[=] call[name[m... | keyword[def] identifier[errinfo] ( identifier[msmt] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[msmt] , identifier[Textual] ):
identifier[msmt] = identifier[msmt] . identifier[unwrap] ()
keyword[if] identifier[np] . identifier[isscalar] ( identifier[msmt] ):
... | def errinfo(msmt):
"""Return (limtype, repval, errval1, errval2). Like m_liminfo, but also
provides error bar information for values that have it."""
if isinstance(msmt, Textual):
msmt = msmt.unwrap() # depends on [control=['if'], data=[]]
if np.isscalar(msmt):
return (0, msmt, msmt, ms... |
def from_passphrase(cls, passphrase=None):
""" Create keypair from a passphrase input (a brain wallet keypair)."""
if not passphrase:
# run a rejection sampling algorithm to ensure the private key is
# less than the curve order
while True:
passphrase =... | def function[from_passphrase, parameter[cls, passphrase]]:
constant[ Create keypair from a passphrase input (a brain wallet keypair).]
if <ast.UnaryOp object at 0x7da1b1042650> begin[:]
while constant[True] begin[:]
variable[passphrase] assign[=] call[name[create_... | keyword[def] identifier[from_passphrase] ( identifier[cls] , identifier[passphrase] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[passphrase] :
keyword[while] keyword[True] :
identifier[passphrase] = identifier[create_passp... | def from_passphrase(cls, passphrase=None):
""" Create keypair from a passphrase input (a brain wallet keypair)."""
if not passphrase:
# run a rejection sampling algorithm to ensure the private key is
# less than the curve order
while True:
passphrase = create_passphrase(bits_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.