code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def matrix_at_check(self, original, loc, tokens):
"""Check for Python 3.5 matrix multiplication."""
return self.check_py("35", "matrix multiplication", original, loc, tokens) | def function[matrix_at_check, parameter[self, original, loc, tokens]]:
constant[Check for Python 3.5 matrix multiplication.]
return[call[name[self].check_py, parameter[constant[35], constant[matrix multiplication], name[original], name[loc], name[tokens]]]] | keyword[def] identifier[matrix_at_check] ( identifier[self] , identifier[original] , identifier[loc] , identifier[tokens] ):
literal[string]
keyword[return] identifier[self] . identifier[check_py] ( literal[string] , literal[string] , identifier[original] , identifier[loc] , identifier[tokens] ) | def matrix_at_check(self, original, loc, tokens):
"""Check for Python 3.5 matrix multiplication."""
return self.check_py('35', 'matrix multiplication', original, loc, tokens) |
def manipulate(self, stored_instance, component_instance):
"""
Manipulates the component instance
:param stored_instance: The iPOPO component StoredInstance
:param component_instance: The component instance
"""
# Store the stored instance
self._ipopo_instance = s... | def function[manipulate, parameter[self, stored_instance, component_instance]]:
constant[
Manipulates the component instance
:param stored_instance: The iPOPO component StoredInstance
:param component_instance: The component instance
]
name[self]._ipopo_instance assign[=... | keyword[def] identifier[manipulate] ( identifier[self] , identifier[stored_instance] , identifier[component_instance] ):
literal[string]
identifier[self] . identifier[_ipopo_instance] = identifier[stored_instance]
keyword[if] identifier[self] . identifier[__controller] keyword... | def manipulate(self, stored_instance, component_instance):
"""
Manipulates the component instance
:param stored_instance: The iPOPO component StoredInstance
:param component_instance: The component instance
"""
# Store the stored instance
self._ipopo_instance = stored_instan... |
def _get_hosts_from_ports(self, ports):
""" validate hostnames from a list of ports
"""
hosts = map(lambda x: 'localhost:%d' % int(x.strip()), ports.split(','))
return list(set(hosts)) | def function[_get_hosts_from_ports, parameter[self, ports]]:
constant[ validate hostnames from a list of ports
]
variable[hosts] assign[=] call[name[map], parameter[<ast.Lambda object at 0x7da18f09fdf0>, call[name[ports].split, parameter[constant[,]]]]]
return[call[name[list], parameter[call... | keyword[def] identifier[_get_hosts_from_ports] ( identifier[self] , identifier[ports] ):
literal[string]
identifier[hosts] = identifier[map] ( keyword[lambda] identifier[x] : literal[string] % identifier[int] ( identifier[x] . identifier[strip] ()), identifier[ports] . identifier[split] ( literal[... | def _get_hosts_from_ports(self, ports):
""" validate hostnames from a list of ports
"""
hosts = map(lambda x: 'localhost:%d' % int(x.strip()), ports.split(','))
return list(set(hosts)) |
def to_ini(self):
""" Get the ini string of the current parser.
:return: The ini string of the current parser
:rtype: str
"""
fake_io = io.StringIO()
self.write(fake_io)
return fake_io.getvalue() | def function[to_ini, parameter[self]]:
constant[ Get the ini string of the current parser.
:return: The ini string of the current parser
:rtype: str
]
variable[fake_io] assign[=] call[name[io].StringIO, parameter[]]
call[name[self].write, parameter[name[fake_io]]]
re... | keyword[def] identifier[to_ini] ( identifier[self] ):
literal[string]
identifier[fake_io] = identifier[io] . identifier[StringIO] ()
identifier[self] . identifier[write] ( identifier[fake_io] )
keyword[return] identifier[fake_io] . identifier[getvalue] () | def to_ini(self):
""" Get the ini string of the current parser.
:return: The ini string of the current parser
:rtype: str
"""
fake_io = io.StringIO()
self.write(fake_io)
return fake_io.getvalue() |
def plot_gender(data, options):
"""Plots the gender.
:param data: the data to plot.
:param options: the options.
:type data: numpy.recarray
:type options: argparse.Namespace
Plots the summarized intensities of the markers on the Y chromosomes in
function of the markers on the X chromosome... | def function[plot_gender, parameter[data, options]]:
constant[Plots the gender.
:param data: the data to plot.
:param options: the options.
:type data: numpy.recarray
:type options: argparse.Namespace
Plots the summarized intensities of the markers on the Y chromosomes in
function of ... | keyword[def] identifier[plot_gender] ( identifier[data] , identifier[options] ):
literal[string]
keyword[if] identifier[data] keyword[is] keyword[None] :
identifier[msg] =( literal[string]
literal[string] )
keyword[raise] identifier[ProgramError] ( identifier[msg] )
... | def plot_gender(data, options):
"""Plots the gender.
:param data: the data to plot.
:param options: the options.
:type data: numpy.recarray
:type options: argparse.Namespace
Plots the summarized intensities of the markers on the Y chromosomes in
function of the markers on the X chromosome... |
def _add_node(self, node):
"""Add a new node to node_list and give the node an ID.
Args:
node: An instance of Node.
Returns:
node_id: An integer.
"""
node_id = len(self.node_list)
self.node_to_id[node] = node_id
self.node_list.append(node)
... | def function[_add_node, parameter[self, node]]:
constant[Add a new node to node_list and give the node an ID.
Args:
node: An instance of Node.
Returns:
node_id: An integer.
]
variable[node_id] assign[=] call[name[len], parameter[name[self].node_list]]
... | keyword[def] identifier[_add_node] ( identifier[self] , identifier[node] ):
literal[string]
identifier[node_id] = identifier[len] ( identifier[self] . identifier[node_list] )
identifier[self] . identifier[node_to_id] [ identifier[node] ]= identifier[node_id]
identifier[self] . id... | def _add_node(self, node):
"""Add a new node to node_list and give the node an ID.
Args:
node: An instance of Node.
Returns:
node_id: An integer.
"""
node_id = len(self.node_list)
self.node_to_id[node] = node_id
self.node_list.append(node)
self.adj_lis... |
def token(self):
"""
Token given by Transbank for payment initialization url.
Will raise PaymentError when an error ocurred.
"""
if not self._token:
self._token = self.fetch_token()
logger.payment(self)
return self._token | def function[token, parameter[self]]:
constant[
Token given by Transbank for payment initialization url.
Will raise PaymentError when an error ocurred.
]
if <ast.UnaryOp object at 0x7da18f722050> begin[:]
name[self]._token assign[=] call[name[self].fetch_token, p... | keyword[def] identifier[token] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_token] :
identifier[self] . identifier[_token] = identifier[self] . identifier[fetch_token] ()
identifier[logger] . identifier[payment] ( identifi... | def token(self):
"""
Token given by Transbank for payment initialization url.
Will raise PaymentError when an error ocurred.
"""
if not self._token:
self._token = self.fetch_token()
logger.payment(self) # depends on [control=['if'], data=[]]
return self._token |
def _set_error_counters(self, v, load=False):
"""
Setter method for error_counters, mapped from YANG variable /mpls_state/rsvp/interfaces/error_counters (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_error_counters is considered as a private
method. Back... | def function[_set_error_counters, parameter[self, v, load]]:
constant[
Setter method for error_counters, mapped from YANG variable /mpls_state/rsvp/interfaces/error_counters (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_error_counters is considered as a... | keyword[def] identifier[_set_error_counters] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
... | def _set_error_counters(self, v, load=False):
"""
Setter method for error_counters, mapped from YANG variable /mpls_state/rsvp/interfaces/error_counters (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_error_counters is considered as a private
method. Back... |
def connect(self, *names):
"""
Connects a list of names, one to the next.
"""
fromName, toName, rest = names[0], names[1], names[2:]
self.connectAt(fromName, toName)
if len(rest) != 0:
self.connect(toName, *rest) | def function[connect, parameter[self]]:
constant[
Connects a list of names, one to the next.
]
<ast.Tuple object at 0x7da1b0358af0> assign[=] tuple[[<ast.Subscript object at 0x7da1b035a380>, <ast.Subscript object at 0x7da1b035abf0>, <ast.Subscript object at 0x7da1b0359c60>]]
call... | keyword[def] identifier[connect] ( identifier[self] ,* identifier[names] ):
literal[string]
identifier[fromName] , identifier[toName] , identifier[rest] = identifier[names] [ literal[int] ], identifier[names] [ literal[int] ], identifier[names] [ literal[int] :]
identifier[self] . identifi... | def connect(self, *names):
"""
Connects a list of names, one to the next.
"""
(fromName, toName, rest) = (names[0], names[1], names[2:])
self.connectAt(fromName, toName)
if len(rest) != 0:
self.connect(toName, *rest) # depends on [control=['if'], data=[]] |
def set_cloexec(fd):
"""Set the file descriptor `fd` to automatically close on
:func:`os.execve`. This has no effect on file descriptors inherited across
:func:`os.fork`, they must be explicitly closed through some other means,
such as :func:`mitogen.fork.on_fork`."""
flags = fcntl.fcntl(fd, fcntl.F... | def function[set_cloexec, parameter[fd]]:
constant[Set the file descriptor `fd` to automatically close on
:func:`os.execve`. This has no effect on file descriptors inherited across
:func:`os.fork`, they must be explicitly closed through some other means,
such as :func:`mitogen.fork.on_fork`.]
... | keyword[def] identifier[set_cloexec] ( identifier[fd] ):
literal[string]
identifier[flags] = identifier[fcntl] . identifier[fcntl] ( identifier[fd] , identifier[fcntl] . identifier[F_GETFD] )
keyword[assert] identifier[fd] > literal[int]
identifier[fcntl] . identifier[fcntl] ( identifier[fd] , ... | def set_cloexec(fd):
"""Set the file descriptor `fd` to automatically close on
:func:`os.execve`. This has no effect on file descriptors inherited across
:func:`os.fork`, they must be explicitly closed through some other means,
such as :func:`mitogen.fork.on_fork`."""
flags = fcntl.fcntl(fd, fcntl.F... |
def set_word_at_rva(self, rva, word):
"""Set the word value at the file offset corresponding to the given RVA."""
return self.set_bytes_at_rva(rva, self.get_data_from_word(word)) | def function[set_word_at_rva, parameter[self, rva, word]]:
constant[Set the word value at the file offset corresponding to the given RVA.]
return[call[name[self].set_bytes_at_rva, parameter[name[rva], call[name[self].get_data_from_word, parameter[name[word]]]]]] | keyword[def] identifier[set_word_at_rva] ( identifier[self] , identifier[rva] , identifier[word] ):
literal[string]
keyword[return] identifier[self] . identifier[set_bytes_at_rva] ( identifier[rva] , identifier[self] . identifier[get_data_from_word] ( identifier[word] )) | def set_word_at_rva(self, rva, word):
"""Set the word value at the file offset corresponding to the given RVA."""
return self.set_bytes_at_rva(rva, self.get_data_from_word(word)) |
def timedelta_to_seconds(delta):
'''Convert a timedelta to seconds with the microseconds as fraction
Note that this method has become largely obsolete with the
`timedelta.total_seconds()` method introduced in Python 2.7.
>>> from datetime import timedelta
>>> '%d' % timedelta_to_seconds(timedelta(... | def function[timedelta_to_seconds, parameter[delta]]:
constant[Convert a timedelta to seconds with the microseconds as fraction
Note that this method has become largely obsolete with the
`timedelta.total_seconds()` method introduced in Python 2.7.
>>> from datetime import timedelta
>>> '%d' % ... | keyword[def] identifier[timedelta_to_seconds] ( identifier[delta] ):
literal[string]
keyword[if] identifier[delta] . identifier[microseconds] :
identifier[total] = identifier[delta] . identifier[microseconds] * literal[int]
keyword[else] :
identifier[total] = literal[int]
... | def timedelta_to_seconds(delta):
"""Convert a timedelta to seconds with the microseconds as fraction
Note that this method has become largely obsolete with the
`timedelta.total_seconds()` method introduced in Python 2.7.
>>> from datetime import timedelta
>>> '%d' % timedelta_to_seconds(timedelta(... |
def plot(self, x=None, y=None, z=None, what="count(*)", vwhat=None, reduce=["colormap"], f=None,
normalize="normalize", normalize_axis="what",
vmin=None, vmax=None,
shape=256, vshape=32, limits=None, grid=None, colormap="afmhot", # colors=["red", "green", "blue"],
figsize=None, xlab... | def function[plot, parameter[self, x, y, z, what, vwhat, reduce, f, normalize, normalize_axis, vmin, vmax, shape, vshape, limits, grid, colormap, figsize, xlabel, ylabel, aspect, tight_layout, interpolation, show, colorbar, colorbar_label, selection, selection_labels, title, background_color, pre_blend, background_alph... | keyword[def] identifier[plot] ( identifier[self] , identifier[x] = keyword[None] , identifier[y] = keyword[None] , identifier[z] = keyword[None] , identifier[what] = literal[string] , identifier[vwhat] = keyword[None] , identifier[reduce] =[ literal[string] ], identifier[f] = keyword[None] ,
identifier[normalize] = ... | def plot(self, x=None, y=None, z=None, what='count(*)', vwhat=None, reduce=['colormap'], f=None, normalize='normalize', normalize_axis='what', vmin=None, vmax=None, shape=256, vshape=32, limits=None, grid=None, colormap='afmhot', figsize=None, xlabel=None, ylabel=None, aspect='auto', tight_layout=True, interpolation='n... |
def fetch_open_data(cls, ifo, start, end, sample_rate=4096,
tag=None, version=None,
format='hdf5', host=GWOSC_DEFAULT_HOST,
verbose=False, cache=None, **kwargs):
"""Fetch open-access data from the LIGO Open Science Center
Parameter... | def function[fetch_open_data, parameter[cls, ifo, start, end, sample_rate, tag, version, format, host, verbose, cache]]:
constant[Fetch open-access data from the LIGO Open Science Center
Parameters
----------
ifo : `str`
the two-character prefix of the IFO in which you are i... | keyword[def] identifier[fetch_open_data] ( identifier[cls] , identifier[ifo] , identifier[start] , identifier[end] , identifier[sample_rate] = literal[int] ,
identifier[tag] = keyword[None] , identifier[version] = keyword[None] ,
identifier[format] = literal[string] , identifier[host] = identifier[GWOSC_DEFAULT_HOS... | def fetch_open_data(cls, ifo, start, end, sample_rate=4096, tag=None, version=None, format='hdf5', host=GWOSC_DEFAULT_HOST, verbose=False, cache=None, **kwargs):
"""Fetch open-access data from the LIGO Open Science Center
Parameters
----------
ifo : `str`
the two-character prefi... |
def train(train_dir=None, train_csv=None, epochs=30, batch_size=32):
"""Function responsible for running the training the model."""
if not train_dir or not os.path.exists(train_dir) or not train_csv:
warnings.warn("No train directory could be found ")
return
# Make a dataset from the local ... | def function[train, parameter[train_dir, train_csv, epochs, batch_size]]:
constant[Function responsible for running the training the model.]
if <ast.BoolOp object at 0x7da2054a7d60> begin[:]
call[name[warnings].warn, parameter[constant[No train directory could be found ]]]
return... | keyword[def] identifier[train] ( identifier[train_dir] = keyword[None] , identifier[train_csv] = keyword[None] , identifier[epochs] = literal[int] , identifier[batch_size] = literal[int] ):
literal[string]
keyword[if] keyword[not] identifier[train_dir] keyword[or] keyword[not] identifier[os] . identi... | def train(train_dir=None, train_csv=None, epochs=30, batch_size=32):
"""Function responsible for running the training the model."""
if not train_dir or not os.path.exists(train_dir) or (not train_csv):
warnings.warn('No train directory could be found ')
return # depends on [control=['if'], data... |
def is_date(value,
minimum = None,
maximum = None,
coerce_value = False,
**kwargs):
"""Indicate whether ``value`` is a :class:`date <python:datetime.date>`.
:param value: The value to evaluate.
:param minimum: If supplied, will make sure that ``value`` is on... | def function[is_date, parameter[value, minimum, maximum, coerce_value]]:
constant[Indicate whether ``value`` is a :class:`date <python:datetime.date>`.
:param value: The value to evaluate.
:param minimum: If supplied, will make sure that ``value`` is on or after
this value.
:type minimum: :c... | keyword[def] identifier[is_date] ( identifier[value] ,
identifier[minimum] = keyword[None] ,
identifier[maximum] = keyword[None] ,
identifier[coerce_value] = keyword[False] ,
** identifier[kwargs] ):
literal[string]
keyword[try] :
identifier[value] = identifier[validators] . identifier[date] ( ... | def is_date(value, minimum=None, maximum=None, coerce_value=False, **kwargs):
"""Indicate whether ``value`` is a :class:`date <python:datetime.date>`.
:param value: The value to evaluate.
:param minimum: If supplied, will make sure that ``value`` is on or after
this value.
:type minimum: :class:... |
def flatten_fieldsets(fieldsets):
"""Returns a list of field names from an admin fieldsets structure."""
field_names = []
for _, opts in fieldsets or ():
if 'fieldsets' in opts:
field_names += flatten_fieldsets(opts.get('fieldsets'))
else:
for field in opts.get('field... | def function[flatten_fieldsets, parameter[fieldsets]]:
constant[Returns a list of field names from an admin fieldsets structure.]
variable[field_names] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da204621840>, <ast.Name object at 0x7da204623340>]]] in starred[<ast.BoolOp object at... | keyword[def] identifier[flatten_fieldsets] ( identifier[fieldsets] ):
literal[string]
identifier[field_names] =[]
keyword[for] identifier[_] , identifier[opts] keyword[in] identifier[fieldsets] keyword[or] ():
keyword[if] literal[string] keyword[in] identifier[opts] :
iden... | def flatten_fieldsets(fieldsets):
"""Returns a list of field names from an admin fieldsets structure."""
field_names = []
for (_, opts) in fieldsets or ():
if 'fieldsets' in opts:
field_names += flatten_fieldsets(opts.get('fieldsets')) # depends on [control=['if'], data=['opts']]
... |
def exit_on_error(self, message, exit_code=1):
# pylint: disable=no-self-use
"""Log generic message when getting an error and exit
:param exit_code: if not None, exit with the provided value as exit code
:type exit_code: int
:param message: message for the exit reason
:t... | def function[exit_on_error, parameter[self, message, exit_code]]:
constant[Log generic message when getting an error and exit
:param exit_code: if not None, exit with the provided value as exit code
:type exit_code: int
:param message: message for the exit reason
:type message: ... | keyword[def] identifier[exit_on_error] ( identifier[self] , identifier[message] , identifier[exit_code] = literal[int] ):
literal[string]
identifier[log] = literal[string]
keyword[if] identifier[message] :
identifier[log] += literal[string] % identifier[message]
... | def exit_on_error(self, message, exit_code=1):
# pylint: disable=no-self-use
'Log generic message when getting an error and exit\n\n :param exit_code: if not None, exit with the provided value as exit code\n :type exit_code: int\n :param message: message for the exit reason\n :type m... |
def main(command_line=True, **kwargs):
"""
NAME
_2g_bin_magic.py
DESCRIPTION
takes the binary 2g format magnetometer files and converts them to magic_measurements, er_samples.txt and er_sites.txt file
SYNTAX
2g_bin_magic.py [command line options]
OPTIONS
-f FILE: s... | def function[main, parameter[command_line]]:
constant[
NAME
_2g_bin_magic.py
DESCRIPTION
takes the binary 2g format magnetometer files and converts them to magic_measurements, er_samples.txt and er_sites.txt file
SYNTAX
2g_bin_magic.py [command line options]
OPTIONS
... | keyword[def] identifier[main] ( identifier[command_line] = keyword[True] ,** identifier[kwargs] ):
literal[string]
identifier[mag_file] = literal[string]
identifier[specnum] = literal[int]
identifier[ub_file] , identifier[samp_file] , identifier[or_con] , identifier[corr] , ident... | def main(command_line=True, **kwargs):
"""
NAME
_2g_bin_magic.py
DESCRIPTION
takes the binary 2g format magnetometer files and converts them to magic_measurements, er_samples.txt and er_sites.txt file
SYNTAX
2g_bin_magic.py [command line options]
OPTIONS
-f FILE: s... |
def ConvCnstrMODOptionsDefaults(method='fista'):
"""Get defaults dict for the ConvCnstrMOD class specified by the
``method`` parameter.
"""
dflt = copy.deepcopy(ccmod_class_label_lookup(method).Options.defaults)
if method == 'fista':
dflt.update({'MaxMainIter': 1, 'BackTrack':
... | def function[ConvCnstrMODOptionsDefaults, parameter[method]]:
constant[Get defaults dict for the ConvCnstrMOD class specified by the
``method`` parameter.
]
variable[dflt] assign[=] call[name[copy].deepcopy, parameter[call[name[ccmod_class_label_lookup], parameter[name[method]]].Options.defaults... | keyword[def] identifier[ConvCnstrMODOptionsDefaults] ( identifier[method] = literal[string] ):
literal[string]
identifier[dflt] = identifier[copy] . identifier[deepcopy] ( identifier[ccmod_class_label_lookup] ( identifier[method] ). identifier[Options] . identifier[defaults] )
keyword[if] identifier... | def ConvCnstrMODOptionsDefaults(method='fista'):
"""Get defaults dict for the ConvCnstrMOD class specified by the
``method`` parameter.
"""
dflt = copy.deepcopy(ccmod_class_label_lookup(method).Options.defaults)
if method == 'fista':
dflt.update({'MaxMainIter': 1, 'BackTrack': {'gamma_u': 1.... |
def get_allowance(self, asset_name: str, from_address: str, to_address: str, is_full: bool = False) -> str:
"""
This interface is used to get the the allowance
from transfer-from account to transfer-to account in current network.
:param asset_name:
:param from_address: a base58 ... | def function[get_allowance, parameter[self, asset_name, from_address, to_address, is_full]]:
constant[
This interface is used to get the the allowance
from transfer-from account to transfer-to account in current network.
:param asset_name:
:param from_address: a base58 encoded a... | keyword[def] identifier[get_allowance] ( identifier[self] , identifier[asset_name] : identifier[str] , identifier[from_address] : identifier[str] , identifier[to_address] : identifier[str] , identifier[is_full] : identifier[bool] = keyword[False] )-> identifier[str] :
literal[string]
identifier[pay... | def get_allowance(self, asset_name: str, from_address: str, to_address: str, is_full: bool=False) -> str:
"""
This interface is used to get the the allowance
from transfer-from account to transfer-to account in current network.
:param asset_name:
:param from_address: a base58 encode... |
def _version_checker(module, minver):
"""Checks that module has a higher version that minver.
params:
- module: a module to test
- minver: a tuple of versions
"""
# We could use LooseVersion, but distutils imports imp which is deprecated
version_regexp = r'[a-z]?((?:\d|\.)+\d+)(?:\.dev[0-... | def function[_version_checker, parameter[module, minver]]:
constant[Checks that module has a higher version that minver.
params:
- module: a module to test
- minver: a tuple of versions
]
variable[version_regexp] assign[=] constant[[a-z]?((?:\d|\.)+\d+)(?:\.dev[0-9]+)?]
variab... | keyword[def] identifier[_version_checker] ( identifier[module] , identifier[minver] ):
literal[string]
identifier[version_regexp] = literal[string]
identifier[version_tags] = identifier[re] . identifier[match] ( identifier[version_regexp] , identifier[module] . identifier[__version__] )
key... | def _version_checker(module, minver):
"""Checks that module has a higher version that minver.
params:
- module: a module to test
- minver: a tuple of versions
"""
# We could use LooseVersion, but distutils imports imp which is deprecated
version_regexp = '[a-z]?((?:\\d|\\.)+\\d+)(?:\\.dev... |
def delete_role(resource_root, service_name, name, cluster_name="default"):
"""
Delete a role by name
@param resource_root: The root Resource object.
@param service_name: Service name
@param name: Role name
@param cluster_name: Cluster name
@return: The deleted ApiRole object
"""
return call(resource_... | def function[delete_role, parameter[resource_root, service_name, name, cluster_name]]:
constant[
Delete a role by name
@param resource_root: The root Resource object.
@param service_name: Service name
@param name: Role name
@param cluster_name: Cluster name
@return: The deleted ApiRole object
]
... | keyword[def] identifier[delete_role] ( identifier[resource_root] , identifier[service_name] , identifier[name] , identifier[cluster_name] = literal[string] ):
literal[string]
keyword[return] identifier[call] ( identifier[resource_root] . identifier[delete] ,
identifier[_get_role_path] ( identifier[cluster_... | def delete_role(resource_root, service_name, name, cluster_name='default'):
"""
Delete a role by name
@param resource_root: The root Resource object.
@param service_name: Service name
@param name: Role name
@param cluster_name: Cluster name
@return: The deleted ApiRole object
"""
return call(resou... |
def get_all_regions_with_tiles(self):
"""
Generator which yields a set of (rx, ry) tuples which describe
all regions for which the world has tile data
"""
for key in self.get_all_keys():
(layer, rx, ry) = struct.unpack('>BHH', key)
if layer == 1:
... | def function[get_all_regions_with_tiles, parameter[self]]:
constant[
Generator which yields a set of (rx, ry) tuples which describe
all regions for which the world has tile data
]
for taget[name[key]] in starred[call[name[self].get_all_keys, parameter[]]] begin[:]
... | keyword[def] identifier[get_all_regions_with_tiles] ( identifier[self] ):
literal[string]
keyword[for] identifier[key] keyword[in] identifier[self] . identifier[get_all_keys] ():
( identifier[layer] , identifier[rx] , identifier[ry] )= identifier[struct] . identifier[unpack] ( litera... | def get_all_regions_with_tiles(self):
"""
Generator which yields a set of (rx, ry) tuples which describe
all regions for which the world has tile data
"""
for key in self.get_all_keys():
(layer, rx, ry) = struct.unpack('>BHH', key)
if layer == 1:
yield (rx, ry... |
def as_id_dict(self):
"""
Return table as a dictionary mapping experiment_id, time_slide_id,
veto_def_name, and sim_proc_id (if it exists) to the expr_summ_id.
"""
d = {}
for row in self:
if row.experiment_id not in d:
d[row.experiment_id] = {}
if (row.time_slide_id, row.veto_def_name, row.datatyp... | def function[as_id_dict, parameter[self]]:
constant[
Return table as a dictionary mapping experiment_id, time_slide_id,
veto_def_name, and sim_proc_id (if it exists) to the expr_summ_id.
]
variable[d] assign[=] dictionary[[], []]
for taget[name[row]] in starred[name[self]] begin[:]
... | keyword[def] identifier[as_id_dict] ( identifier[self] ):
literal[string]
identifier[d] ={}
keyword[for] identifier[row] keyword[in] identifier[self] :
keyword[if] identifier[row] . identifier[experiment_id] keyword[not] keyword[in] identifier[d] :
identifier[d] [ identifier[row] . identifie... | def as_id_dict(self):
"""
Return table as a dictionary mapping experiment_id, time_slide_id,
veto_def_name, and sim_proc_id (if it exists) to the expr_summ_id.
"""
d = {}
for row in self:
if row.experiment_id not in d:
d[row.experiment_id] = {} # depends on [control=['if'], data=[... |
def print_duplicate_anchor_information(duplicate_tags):
"""
Prints information about duplicate AnchorHub tags found during collection.
:param duplicate_tags: Dictionary mapping string file path keys to a list of
tuples. The tuples contain the following information, in order:
1. The string ... | def function[print_duplicate_anchor_information, parameter[duplicate_tags]]:
constant[
Prints information about duplicate AnchorHub tags found during collection.
:param duplicate_tags: Dictionary mapping string file path keys to a list of
tuples. The tuples contain the following information, in... | keyword[def] identifier[print_duplicate_anchor_information] ( identifier[duplicate_tags] ):
literal[string]
identifier[print] ( literal[string] )
identifier[print] ( literal[string] )
keyword[for] identifier[file_path] keyword[in] identifier[duplicate_tags] :
identifier[print] ( liter... | def print_duplicate_anchor_information(duplicate_tags):
"""
Prints information about duplicate AnchorHub tags found during collection.
:param duplicate_tags: Dictionary mapping string file path keys to a list of
tuples. The tuples contain the following information, in order:
1. The string ... |
def diagnostics_plot_chisq(self, ds, figname = "modelfit_chisqs.png"):
""" Produce a set of diagnostic plots for the model
Parameters
----------
(optional) chisq_dist_plot_name: str
Filename of output saved plot
"""
label_names = ds.get_plotting_labels()
... | def function[diagnostics_plot_chisq, parameter[self, ds, figname]]:
constant[ Produce a set of diagnostic plots for the model
Parameters
----------
(optional) chisq_dist_plot_name: str
Filename of output saved plot
]
variable[label_names] assign[=] call[name... | keyword[def] identifier[diagnostics_plot_chisq] ( identifier[self] , identifier[ds] , identifier[figname] = literal[string] ):
literal[string]
identifier[label_names] = identifier[ds] . identifier[get_plotting_labels] ()
identifier[lams] = identifier[ds] . identifier[wl]
identifi... | def diagnostics_plot_chisq(self, ds, figname='modelfit_chisqs.png'):
""" Produce a set of diagnostic plots for the model
Parameters
----------
(optional) chisq_dist_plot_name: str
Filename of output saved plot
"""
label_names = ds.get_plotting_labels()
lams = ds... |
def thermal_state(omega_level, T, return_diagonal=False):
r"""Return a thermal state for a given set of levels.
INPUT:
- ``omega_level`` - The angular frequencies of each state.
- ``T`` - The temperature of the ensemble (in Kelvin).
- ``return_diagonal`` - Whether to return only the populations... | def function[thermal_state, parameter[omega_level, T, return_diagonal]]:
constant[Return a thermal state for a given set of levels.
INPUT:
- ``omega_level`` - The angular frequencies of each state.
- ``T`` - The temperature of the ensemble (in Kelvin).
- ``return_diagonal`` - Whether to ret... | keyword[def] identifier[thermal_state] ( identifier[omega_level] , identifier[T] , identifier[return_diagonal] = keyword[False] ):
literal[string]
identifier[Ne] = identifier[len] ( identifier[omega_level] )
identifier[E] = identifier[np] . identifier[array] ([ identifier[hbar] * identifier[omega_leve... | def thermal_state(omega_level, T, return_diagonal=False):
"""Return a thermal state for a given set of levels.
INPUT:
- ``omega_level`` - The angular frequencies of each state.
- ``T`` - The temperature of the ensemble (in Kelvin).
- ``return_diagonal`` - Whether to return only the populations.... |
def rank_items(self, userid, user_items, selected_items, recalculate_user=False):
""" Rank given items for a user and returns sorted item list """
# check if selected_items contains itemids that are not in the model(user_items)
if max(selected_items) >= user_items.shape[1] or min(selected_items)... | def function[rank_items, parameter[self, userid, user_items, selected_items, recalculate_user]]:
constant[ Rank given items for a user and returns sorted item list ]
if <ast.BoolOp object at 0x7da2047e9060> begin[:]
<ast.Raise object at 0x7da2047e8340>
variable[liked_vector] assign[=] ca... | keyword[def] identifier[rank_items] ( identifier[self] , identifier[userid] , identifier[user_items] , identifier[selected_items] , identifier[recalculate_user] = keyword[False] ):
literal[string]
keyword[if] identifier[max] ( identifier[selected_items] )>= identifier[user_items] . identi... | def rank_items(self, userid, user_items, selected_items, recalculate_user=False):
""" Rank given items for a user and returns sorted item list """
# check if selected_items contains itemids that are not in the model(user_items)
if max(selected_items) >= user_items.shape[1] or min(selected_items) < 0:
... |
def from_info(cls, container, info_obj):
"""Create from subdirectory or file info object."""
create_fn = cls.from_subdir if 'subdir' in info_obj \
else cls.from_file_info
return create_fn(container, info_obj) | def function[from_info, parameter[cls, container, info_obj]]:
constant[Create from subdirectory or file info object.]
variable[create_fn] assign[=] <ast.IfExp object at 0x7da18f813310>
return[call[name[create_fn], parameter[name[container], name[info_obj]]]] | keyword[def] identifier[from_info] ( identifier[cls] , identifier[container] , identifier[info_obj] ):
literal[string]
identifier[create_fn] = identifier[cls] . identifier[from_subdir] keyword[if] literal[string] keyword[in] identifier[info_obj] keyword[else] identifier[cls] . identifier[from... | def from_info(cls, container, info_obj):
"""Create from subdirectory or file info object."""
create_fn = cls.from_subdir if 'subdir' in info_obj else cls.from_file_info
return create_fn(container, info_obj) |
def stopService(self):
"""
Stop the writer thread, wait for it to finish.
"""
Service.stopService(self)
removeDestination(self)
self._reactor.callFromThread(self._reactor.stop)
return deferToThreadPool(
self._mainReactor,
self._mainReactor.... | def function[stopService, parameter[self]]:
constant[
Stop the writer thread, wait for it to finish.
]
call[name[Service].stopService, parameter[name[self]]]
call[name[removeDestination], parameter[name[self]]]
call[name[self]._reactor.callFromThread, parameter[name[self]... | keyword[def] identifier[stopService] ( identifier[self] ):
literal[string]
identifier[Service] . identifier[stopService] ( identifier[self] )
identifier[removeDestination] ( identifier[self] )
identifier[self] . identifier[_reactor] . identifier[callFromThread] ( identifier[self] ... | def stopService(self):
"""
Stop the writer thread, wait for it to finish.
"""
Service.stopService(self)
removeDestination(self)
self._reactor.callFromThread(self._reactor.stop)
return deferToThreadPool(self._mainReactor, self._mainReactor.getThreadPool(), self._thread.join) |
def get_string(dev, index, langid = None):
r"""Retrieve a string descriptor from the device.
dev is the Device object which the string will be read from.
index is the string descriptor index and langid is the Language
ID of the descriptor. If langid is omitted, the string descriptor
of the first L... | def function[get_string, parameter[dev, index, langid]]:
constant[Retrieve a string descriptor from the device.
dev is the Device object which the string will be read from.
index is the string descriptor index and langid is the Language
ID of the descriptor. If langid is omitted, the string descri... | keyword[def] identifier[get_string] ( identifier[dev] , identifier[index] , identifier[langid] = keyword[None] ):
literal[string]
keyword[if] literal[int] == identifier[index] :
keyword[return] keyword[None]
keyword[from] identifier[usb] . identifier[control] keyword[import] identifier... | def get_string(dev, index, langid=None):
"""Retrieve a string descriptor from the device.
dev is the Device object which the string will be read from.
index is the string descriptor index and langid is the Language
ID of the descriptor. If langid is omitted, the string descriptor
of the first Lang... |
def startup(self):
"""Startup the ec2 instance
"""
import boto.ec2
if not self.browser_config.get('launch'):
self.warning_log("Skipping launch")
return True
self.info_log("Starting up")
instance = None
try:
# KEY NAME
... | def function[startup, parameter[self]]:
constant[Startup the ec2 instance
]
import module[boto.ec2]
if <ast.UnaryOp object at 0x7da2045645b0> begin[:]
call[name[self].warning_log, parameter[constant[Skipping launch]]]
return[constant[True]]
call[name[self].inf... | keyword[def] identifier[startup] ( identifier[self] ):
literal[string]
keyword[import] identifier[boto] . identifier[ec2]
keyword[if] keyword[not] identifier[self] . identifier[browser_config] . identifier[get] ( literal[string] ):
identifier[self] . identifier[warning_lo... | def startup(self):
"""Startup the ec2 instance
"""
import boto.ec2
if not self.browser_config.get('launch'):
self.warning_log('Skipping launch')
return True # depends on [control=['if'], data=[]]
self.info_log('Starting up')
instance = None
try:
# KEY NAME
... |
def dfs_grid(grid, i, j, mark='X', free='.'):
"""DFS on a grid, mark connected component, iterative version
:param grid: matrix, 4-neighborhood
:param i,j: cell in this matrix, start of DFS exploration
:param free: symbol for walkable cells
:param mark: symbol to overwrite visited vertices
:com... | def function[dfs_grid, parameter[grid, i, j, mark, free]]:
constant[DFS on a grid, mark connected component, iterative version
:param grid: matrix, 4-neighborhood
:param i,j: cell in this matrix, start of DFS exploration
:param free: symbol for walkable cells
:param mark: symbol to overwrite vi... | keyword[def] identifier[dfs_grid] ( identifier[grid] , identifier[i] , identifier[j] , identifier[mark] = literal[string] , identifier[free] = literal[string] ):
literal[string]
identifier[height] = identifier[len] ( identifier[grid] )
identifier[width] = identifier[len] ( identifier[grid] [ literal[i... | def dfs_grid(grid, i, j, mark='X', free='.'):
"""DFS on a grid, mark connected component, iterative version
:param grid: matrix, 4-neighborhood
:param i,j: cell in this matrix, start of DFS exploration
:param free: symbol for walkable cells
:param mark: symbol to overwrite visited vertices
:com... |
def diffPrefsPrior(priorstring):
"""Parses `priorstring` and returns `prior` tuple."""
assert isinstance(priorstring, str)
prior = priorstring.split(',')
if len(prior) == 3 and prior[0] == 'invquadratic':
[c1, c2] = [float(x) for x in prior[1 : ]]
assert c1 > 0 and c2 > 0, "C1 and C2 mus... | def function[diffPrefsPrior, parameter[priorstring]]:
constant[Parses `priorstring` and returns `prior` tuple.]
assert[call[name[isinstance], parameter[name[priorstring], name[str]]]]
variable[prior] assign[=] call[name[priorstring].split, parameter[constant[,]]]
if <ast.BoolOp object at 0x7... | keyword[def] identifier[diffPrefsPrior] ( identifier[priorstring] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[priorstring] , identifier[str] )
identifier[prior] = identifier[priorstring] . identifier[split] ( literal[string] )
keyword[if] identifier[len] ( identifier[... | def diffPrefsPrior(priorstring):
"""Parses `priorstring` and returns `prior` tuple."""
assert isinstance(priorstring, str)
prior = priorstring.split(',')
if len(prior) == 3 and prior[0] == 'invquadratic':
[c1, c2] = [float(x) for x in prior[1:]]
assert c1 > 0 and c2 > 0, 'C1 and C2 must ... |
def ReadClientStartupInfoHistory(self, client_id, timerange=None):
"""Reads the full startup history for a particular client."""
from_time, to_time = self._ParseTimeRange(timerange)
history = self.startup_history.get(client_id)
if not history:
return []
res = []
for ts in sorted(history, ... | def function[ReadClientStartupInfoHistory, parameter[self, client_id, timerange]]:
constant[Reads the full startup history for a particular client.]
<ast.Tuple object at 0x7da2054a4d90> assign[=] call[name[self]._ParseTimeRange, parameter[name[timerange]]]
variable[history] assign[=] call[name[s... | keyword[def] identifier[ReadClientStartupInfoHistory] ( identifier[self] , identifier[client_id] , identifier[timerange] = keyword[None] ):
literal[string]
identifier[from_time] , identifier[to_time] = identifier[self] . identifier[_ParseTimeRange] ( identifier[timerange] )
identifier[history] = iden... | def ReadClientStartupInfoHistory(self, client_id, timerange=None):
"""Reads the full startup history for a particular client."""
(from_time, to_time) = self._ParseTimeRange(timerange)
history = self.startup_history.get(client_id)
if not history:
return [] # depends on [control=['if'], data=[]]
... |
def create_incident(**kwargs):
"""
Creates an incident
"""
incidents = cachet.Incidents(endpoint=ENDPOINT, api_token=API_TOKEN)
if 'component_id' in kwargs:
return incidents.post(name=kwargs['name'],
message=kwargs['message'],
statu... | def function[create_incident, parameter[]]:
constant[
Creates an incident
]
variable[incidents] assign[=] call[name[cachet].Incidents, parameter[]]
if compare[constant[component_id] in name[kwargs]] begin[:]
return[call[name[incidents].post, parameter[]]] | keyword[def] identifier[create_incident] (** identifier[kwargs] ):
literal[string]
identifier[incidents] = identifier[cachet] . identifier[Incidents] ( identifier[endpoint] = identifier[ENDPOINT] , identifier[api_token] = identifier[API_TOKEN] )
keyword[if] literal[string] keyword[in] identifier[kw... | def create_incident(**kwargs):
"""
Creates an incident
"""
incidents = cachet.Incidents(endpoint=ENDPOINT, api_token=API_TOKEN)
if 'component_id' in kwargs:
return incidents.post(name=kwargs['name'], message=kwargs['message'], status=kwargs['status'], component_id=kwargs['component_id'], com... |
def restore_offsets(cls, client, parsed_consumer_offsets):
"""Fetch current offsets from kafka, validate them against given
consumer-offsets data and commit the new offsets.
:param client: Kafka-client
:param parsed_consumer_offsets: Parsed consumer offset data from json file
:t... | def function[restore_offsets, parameter[cls, client, parsed_consumer_offsets]]:
constant[Fetch current offsets from kafka, validate them against given
consumer-offsets data and commit the new offsets.
:param client: Kafka-client
:param parsed_consumer_offsets: Parsed consumer offset dat... | keyword[def] identifier[restore_offsets] ( identifier[cls] , identifier[client] , identifier[parsed_consumer_offsets] ):
literal[string]
keyword[try] :
identifier[consumer_group] = identifier[parsed_consumer_offsets] [ literal[string] ]
identifier[topics_offset_da... | def restore_offsets(cls, client, parsed_consumer_offsets):
"""Fetch current offsets from kafka, validate them against given
consumer-offsets data and commit the new offsets.
:param client: Kafka-client
:param parsed_consumer_offsets: Parsed consumer offset data from json file
:type ... |
def remove_rows_matching(df, column, match):
"""
Return a ``DataFrame`` with rows where `column` values match `match` are removed.
The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared
to `match`, and those rows that match are removed from the DataFrame.
:param ... | def function[remove_rows_matching, parameter[df, column, match]]:
constant[
Return a ``DataFrame`` with rows where `column` values match `match` are removed.
The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared
to `match`, and those rows that match are removed f... | keyword[def] identifier[remove_rows_matching] ( identifier[df] , identifier[column] , identifier[match] ):
literal[string]
identifier[df] = identifier[df] . identifier[copy] ()
identifier[mask] = identifier[df] [ identifier[column] ]. identifier[values] != identifier[match]
keyword[return] iden... | def remove_rows_matching(df, column, match):
"""
Return a ``DataFrame`` with rows where `column` values match `match` are removed.
The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared
to `match`, and those rows that match are removed from the DataFrame.
:param ... |
def parse_url(arg, extract, key=None):
"""
Returns the portion of a URL corresponding to a part specified
by 'extract'
Can optionally specify a key to retrieve an associated value
if extract parameter is 'QUERY'
Parameters
----------
extract : one of {'PROTOCOL', 'HOST', 'PATH', 'REF',
... | def function[parse_url, parameter[arg, extract, key]]:
constant[
Returns the portion of a URL corresponding to a part specified
by 'extract'
Can optionally specify a key to retrieve an associated value
if extract parameter is 'QUERY'
Parameters
----------
extract : one of {'PROTOCOL... | keyword[def] identifier[parse_url] ( identifier[arg] , identifier[extract] , identifier[key] = keyword[None] ):
literal[string]
keyword[return] identifier[ops] . identifier[ParseURL] ( identifier[arg] , identifier[extract] , identifier[key] ). identifier[to_expr] () | def parse_url(arg, extract, key=None):
"""
Returns the portion of a URL corresponding to a part specified
by 'extract'
Can optionally specify a key to retrieve an associated value
if extract parameter is 'QUERY'
Parameters
----------
extract : one of {'PROTOCOL', 'HOST', 'PATH', 'REF',
... |
def get_ticket_for_sns_token(self):
"""This is a shortcut for getting the sns_token, as a post data of
request body."""
self.logger.info("%s\t%s" % (self.request_method, self.request_url))
return {
"openid": self.get_openid(),
"persistent_code": self.get_per... | def function[get_ticket_for_sns_token, parameter[self]]:
constant[This is a shortcut for getting the sns_token, as a post data of
request body.]
call[name[self].logger.info, parameter[binary_operation[constant[%s %s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da1b237d2... | keyword[def] identifier[get_ticket_for_sns_token] ( identifier[self] ):
literal[string]
identifier[self] . identifier[logger] . identifier[info] ( literal[string] %( identifier[self] . identifier[request_method] , identifier[self] . identifier[request_url] ))
keyword[return] {
... | def get_ticket_for_sns_token(self):
"""This is a shortcut for getting the sns_token, as a post data of
request body."""
self.logger.info('%s\t%s' % (self.request_method, self.request_url))
return {'openid': self.get_openid(), 'persistent_code': self.get_persistent_code()} |
def _add_routes(self, settings):
"""
Add BGP routes from given settings.
All valid routes are loaded.
Miss-configured routes are ignored and errors are logged.
"""
for route_settings in settings:
if 'prefix' in route_settings:
prefix_add = sel... | def function[_add_routes, parameter[self, settings]]:
constant[
Add BGP routes from given settings.
All valid routes are loaded.
Miss-configured routes are ignored and errors are logged.
]
for taget[name[route_settings]] in starred[name[settings]] begin[:]
... | keyword[def] identifier[_add_routes] ( identifier[self] , identifier[settings] ):
literal[string]
keyword[for] identifier[route_settings] keyword[in] identifier[settings] :
keyword[if] literal[string] keyword[in] identifier[route_settings] :
identifier[prefix_add... | def _add_routes(self, settings):
"""
Add BGP routes from given settings.
All valid routes are loaded.
Miss-configured routes are ignored and errors are logged.
"""
for route_settings in settings:
if 'prefix' in route_settings:
prefix_add = self.speaker.prefix... |
def element(self, inp=None, order=None, **kwargs):
"""Create an element from ``inp`` or from scratch.
Parameters
----------
inp : optional
Input data to create an element from. It needs to be
understood by either the `sampling` operator of this
instan... | def function[element, parameter[self, inp, order]]:
constant[Create an element from ``inp`` or from scratch.
Parameters
----------
inp : optional
Input data to create an element from. It needs to be
understood by either the `sampling` operator of this
... | keyword[def] identifier[element] ( identifier[self] , identifier[inp] = keyword[None] , identifier[order] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[inp] keyword[is] keyword[None] :
keyword[return] identifier[self] . identifier[element_type] ( ... | def element(self, inp=None, order=None, **kwargs):
"""Create an element from ``inp`` or from scratch.
Parameters
----------
inp : optional
Input data to create an element from. It needs to be
understood by either the `sampling` operator of this
instance o... |
def get_query_kwargs(es_defs):
"""
Reads the es_defs and returns a dict of special kwargs to use when
query for data of an instance of a class
reference: rdfframework.sparl.queries.sparqlAllItemDataTemplate.rq
"""
rtn_dict = {}
if es_defs:
if es_defs.get("kds_esSpecialUnion"):
... | def function[get_query_kwargs, parameter[es_defs]]:
constant[
Reads the es_defs and returns a dict of special kwargs to use when
query for data of an instance of a class
reference: rdfframework.sparl.queries.sparqlAllItemDataTemplate.rq
]
variable[rtn_dict] assign[=] dictionary[[], []]
... | keyword[def] identifier[get_query_kwargs] ( identifier[es_defs] ):
literal[string]
identifier[rtn_dict] ={}
keyword[if] identifier[es_defs] :
keyword[if] identifier[es_defs] . identifier[get] ( literal[string] ):
identifier[rtn_dict] [ literal[string] ]= identifier[es_defs] [ l... | def get_query_kwargs(es_defs):
"""
Reads the es_defs and returns a dict of special kwargs to use when
query for data of an instance of a class
reference: rdfframework.sparl.queries.sparqlAllItemDataTemplate.rq
"""
rtn_dict = {}
if es_defs:
if es_defs.get('kds_esSpecialUnion'):
... |
def is_quota_exceeded(self) -> bool:
'''Return whether the quota is exceeded.'''
if self.quota and self._url_table is not None:
return self.size >= self.quota and \
self._url_table.get_root_url_todo_count() == 0 | def function[is_quota_exceeded, parameter[self]]:
constant[Return whether the quota is exceeded.]
if <ast.BoolOp object at 0x7da1b2347b20> begin[:]
return[<ast.BoolOp object at 0x7da1b2344b80>] | keyword[def] identifier[is_quota_exceeded] ( identifier[self] )-> identifier[bool] :
literal[string]
keyword[if] identifier[self] . identifier[quota] keyword[and] identifier[self] . identifier[_url_table] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[self]... | def is_quota_exceeded(self) -> bool:
"""Return whether the quota is exceeded."""
if self.quota and self._url_table is not None:
return self.size >= self.quota and self._url_table.get_root_url_todo_count() == 0 # depends on [control=['if'], data=[]] |
def get_type(type_):
"""
Gets the declaration for the corresponding custom type.
@raise KeyError: Unknown type.
@see: L{add_type} and L{remove_type}
"""
if isinstance(type_, list):
type_ = tuple(type_)
for k, v in TYPE_MAP.iteritems():
if k == type_:
return v
... | def function[get_type, parameter[type_]]:
constant[
Gets the declaration for the corresponding custom type.
@raise KeyError: Unknown type.
@see: L{add_type} and L{remove_type}
]
if call[name[isinstance], parameter[name[type_], name[list]]] begin[:]
variable[type_] assign... | keyword[def] identifier[get_type] ( identifier[type_] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[type_] , identifier[list] ):
identifier[type_] = identifier[tuple] ( identifier[type_] )
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[TYPE_MAP] . ... | def get_type(type_):
"""
Gets the declaration for the corresponding custom type.
@raise KeyError: Unknown type.
@see: L{add_type} and L{remove_type}
"""
if isinstance(type_, list):
type_ = tuple(type_) # depends on [control=['if'], data=[]]
for (k, v) in TYPE_MAP.iteritems():
... |
def network_from_bbox(lat_min=None, lng_min=None, lat_max=None, lng_max=None,
bbox=None, network_type='walk', two_way=True,
timeout=180, memory=None,
max_query_area_size=50*1000*50*1000,
custom_osm_filter=None):
"""
Make a g... | def function[network_from_bbox, parameter[lat_min, lng_min, lat_max, lng_max, bbox, network_type, two_way, timeout, memory, max_query_area_size, custom_osm_filter]]:
constant[
Make a graph network from a bounding lat/lon box composed of nodes and
edges for use in Pandana street network accessibility cal... | keyword[def] identifier[network_from_bbox] ( identifier[lat_min] = keyword[None] , identifier[lng_min] = keyword[None] , identifier[lat_max] = keyword[None] , identifier[lng_max] = keyword[None] ,
identifier[bbox] = keyword[None] , identifier[network_type] = literal[string] , identifier[two_way] = keyword[True] ,
i... | def network_from_bbox(lat_min=None, lng_min=None, lat_max=None, lng_max=None, bbox=None, network_type='walk', two_way=True, timeout=180, memory=None, max_query_area_size=50 * 1000 * 50 * 1000, custom_osm_filter=None):
"""
Make a graph network from a bounding lat/lon box composed of nodes and
edges for use i... |
def namedb_get_name(cur, name, current_block, include_expired=False, include_history=True, only_registered=True):
"""
Get a name and all of its history. Note: will return a revoked name
Return the name + history on success
Return None if the name doesn't exist, or is expired (NOTE: will return a revoke... | def function[namedb_get_name, parameter[cur, name, current_block, include_expired, include_history, only_registered]]:
constant[
Get a name and all of its history. Note: will return a revoked name
Return the name + history on success
Return None if the name doesn't exist, or is expired (NOTE: will ... | keyword[def] identifier[namedb_get_name] ( identifier[cur] , identifier[name] , identifier[current_block] , identifier[include_expired] = keyword[False] , identifier[include_history] = keyword[True] , identifier[only_registered] = keyword[True] ):
literal[string]
keyword[if] keyword[not] identifier[incl... | def namedb_get_name(cur, name, current_block, include_expired=False, include_history=True, only_registered=True):
"""
Get a name and all of its history. Note: will return a revoked name
Return the name + history on success
Return None if the name doesn't exist, or is expired (NOTE: will return a revoke... |
def cybox_valueset_fact_handler(self, enrichment, fact, attr_info, add_fact_kargs):
"""
Handler for dealing with 'value_set' values.
Unfortunately, CybOX et al. sometimes use comma-separated
value lists rather than an XML structure that can contain
several values.
This ... | def function[cybox_valueset_fact_handler, parameter[self, enrichment, fact, attr_info, add_fact_kargs]]:
constant[
Handler for dealing with 'value_set' values.
Unfortunately, CybOX et al. sometimes use comma-separated
value lists rather than an XML structure that can contain
sev... | keyword[def] identifier[cybox_valueset_fact_handler] ( identifier[self] , identifier[enrichment] , identifier[fact] , identifier[attr_info] , identifier[add_fact_kargs] ):
literal[string]
identifier[value_list] = identifier[attr_info] [ literal[string] ][ identifier[fact] [ literal[string] ]]. ide... | def cybox_valueset_fact_handler(self, enrichment, fact, attr_info, add_fact_kargs):
"""
Handler for dealing with 'value_set' values.
Unfortunately, CybOX et al. sometimes use comma-separated
value lists rather than an XML structure that can contain
several values.
This hand... |
def do_filter(self, arg):
"""Sets the filter for the test cases to include in the plot/table by name. Only those
test cases that include this text are included in plots, tables etc."""
if arg == "list":
msg.info("TEST CASE FILTERS")
for f in self.curargs["tfilter"]:
... | def function[do_filter, parameter[self, arg]]:
constant[Sets the filter for the test cases to include in the plot/table by name. Only those
test cases that include this text are included in plots, tables etc.]
if compare[name[arg] equal[==] constant[list]] begin[:]
call[name[msg]... | keyword[def] identifier[do_filter] ( identifier[self] , identifier[arg] ):
literal[string]
keyword[if] identifier[arg] == literal[string] :
identifier[msg] . identifier[info] ( literal[string] )
keyword[for] identifier[f] keyword[in] identifier[self] . identifier[curar... | def do_filter(self, arg):
"""Sets the filter for the test cases to include in the plot/table by name. Only those
test cases that include this text are included in plots, tables etc."""
if arg == 'list':
msg.info('TEST CASE FILTERS')
for f in self.curargs['tfilter']:
if f == '... |
def CreateChatWith(self, *Usernames):
"""Creates a chat with one or more users.
:Parameters:
Usernames : str
One or more Skypenames of the users.
:return: A chat object
:rtype: `Chat`
:see: `Chat.AddMembers`
"""
return Chat(self, chop(self... | def function[CreateChatWith, parameter[self]]:
constant[Creates a chat with one or more users.
:Parameters:
Usernames : str
One or more Skypenames of the users.
:return: A chat object
:rtype: `Chat`
:see: `Chat.AddMembers`
]
return[call[name[C... | keyword[def] identifier[CreateChatWith] ( identifier[self] ,* identifier[Usernames] ):
literal[string]
keyword[return] identifier[Chat] ( identifier[self] , identifier[chop] ( identifier[self] . identifier[_DoCommand] ( literal[string] % literal[string] . identifier[join] ( identifier[Usernames] )... | def CreateChatWith(self, *Usernames):
"""Creates a chat with one or more users.
:Parameters:
Usernames : str
One or more Skypenames of the users.
:return: A chat object
:rtype: `Chat`
:see: `Chat.AddMembers`
"""
return Chat(self, chop(self._DoComm... |
def _report_command(self, cmd, procs=None):
"""
Writes a command to both stdout and to the commands log file
(self.pipeline_commands_file).
:param str cmd: command to report
:param str | list[str] procs: process numbers for processes in the command
"""
if isinst... | def function[_report_command, parameter[self, cmd, procs]]:
constant[
Writes a command to both stdout and to the commands log file
(self.pipeline_commands_file).
:param str cmd: command to report
:param str | list[str] procs: process numbers for processes in the command
... | keyword[def] identifier[_report_command] ( identifier[self] , identifier[cmd] , identifier[procs] = keyword[None] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[procs] , identifier[list] ):
identifier[procs] = literal[string] . identifier[join] ( identifier[map] ( ... | def _report_command(self, cmd, procs=None):
"""
Writes a command to both stdout and to the commands log file
(self.pipeline_commands_file).
:param str cmd: command to report
:param str | list[str] procs: process numbers for processes in the command
"""
if isinstance(pro... |
def deduplicate(args):
"""
%prog deduplicate fastafile
Wraps `cd-hit-est` to remove duplicate sequences.
"""
p = OptionParser(deduplicate.__doc__)
p.set_align(pctid=96, pctcov=0)
p.add_option("--fast", default=False, action="store_true",
help="Place sequence in the first cl... | def function[deduplicate, parameter[args]]:
constant[
%prog deduplicate fastafile
Wraps `cd-hit-est` to remove duplicate sequences.
]
variable[p] assign[=] call[name[OptionParser], parameter[name[deduplicate].__doc__]]
call[name[p].set_align, parameter[]]
call[name[p].add_op... | keyword[def] identifier[deduplicate] ( identifier[args] ):
literal[string]
identifier[p] = identifier[OptionParser] ( identifier[deduplicate] . identifier[__doc__] )
identifier[p] . identifier[set_align] ( identifier[pctid] = literal[int] , identifier[pctcov] = literal[int] )
identifier[p] . iden... | def deduplicate(args):
"""
%prog deduplicate fastafile
Wraps `cd-hit-est` to remove duplicate sequences.
"""
p = OptionParser(deduplicate.__doc__)
p.set_align(pctid=96, pctcov=0)
p.add_option('--fast', default=False, action='store_true', help='Place sequence in the first cluster')
p.add... |
def is60(msg):
"""Check if a message is likely to be BDS code 6,0
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
"""
if allzeros(msg):
return False
d = hex2bin(data(msg))
# status bit 1, 13, 24, 35, 46
if wrongstatus(d, ... | def function[is60, parameter[msg]]:
constant[Check if a message is likely to be BDS code 6,0
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
]
if call[name[allzeros], parameter[name[msg]]] begin[:]
return[constant[False]]
... | keyword[def] identifier[is60] ( identifier[msg] ):
literal[string]
keyword[if] identifier[allzeros] ( identifier[msg] ):
keyword[return] keyword[False]
identifier[d] = identifier[hex2bin] ( identifier[data] ( identifier[msg] ))
keyword[if] identifier[wrongstatus] ( identifie... | def is60(msg):
"""Check if a message is likely to be BDS code 6,0
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
"""
if allzeros(msg):
return False # depends on [control=['if'], data=[]]
d = hex2bin(data(msg))
# status bit 1, 1... |
def node_to_nodal_planes(node):
"""
Parses the nodal plane distribution to a PMF
"""
if not len(node):
return None
npd_pmf = []
for plane in node.nodes:
if not all(plane.attrib[key] for key in plane.attrib):
# One plane fails - return None
return None
... | def function[node_to_nodal_planes, parameter[node]]:
constant[
Parses the nodal plane distribution to a PMF
]
if <ast.UnaryOp object at 0x7da18f811b40> begin[:]
return[constant[None]]
variable[npd_pmf] assign[=] list[[]]
for taget[name[plane]] in starred[name[node].nodes]... | keyword[def] identifier[node_to_nodal_planes] ( identifier[node] ):
literal[string]
keyword[if] keyword[not] identifier[len] ( identifier[node] ):
keyword[return] keyword[None]
identifier[npd_pmf] =[]
keyword[for] identifier[plane] keyword[in] identifier[node] . identifier[nodes] ... | def node_to_nodal_planes(node):
"""
Parses the nodal plane distribution to a PMF
"""
if not len(node):
return None # depends on [control=['if'], data=[]]
npd_pmf = []
for plane in node.nodes:
if not all((plane.attrib[key] for key in plane.attrib)):
# One plane fails ... |
def read_array(fd, n_row, n_col, dtype):
"""
Read a NumPy array of shape `(n_row, n_col)` from the given file
object and cast it to type `dtype`.
If `n_col` is None, determine the number of columns automatically.
"""
if n_col is None:
idx = fd.tell()
row = fd.readline().split()
... | def function[read_array, parameter[fd, n_row, n_col, dtype]]:
constant[
Read a NumPy array of shape `(n_row, n_col)` from the given file
object and cast it to type `dtype`.
If `n_col` is None, determine the number of columns automatically.
]
if compare[name[n_col] is constant[None]] begi... | keyword[def] identifier[read_array] ( identifier[fd] , identifier[n_row] , identifier[n_col] , identifier[dtype] ):
literal[string]
keyword[if] identifier[n_col] keyword[is] keyword[None] :
identifier[idx] = identifier[fd] . identifier[tell] ()
identifier[row] = identifier[fd] . identi... | def read_array(fd, n_row, n_col, dtype):
"""
Read a NumPy array of shape `(n_row, n_col)` from the given file
object and cast it to type `dtype`.
If `n_col` is None, determine the number of columns automatically.
"""
if n_col is None:
idx = fd.tell()
row = fd.readline().split()
... |
def add_path_part(url, regex=PATH_PART):
"""
replace the variables in a url template with regex named groups
:param url: string of a url template
:param regex: regex of the named group
:returns: regex
"""
formatter = string.Formatter()
url_var_template = "(?P<{var_name}>{regex})"
fo... | def function[add_path_part, parameter[url, regex]]:
constant[
replace the variables in a url template with regex named groups
:param url: string of a url template
:param regex: regex of the named group
:returns: regex
]
variable[formatter] assign[=] call[name[string].Formatter, param... | keyword[def] identifier[add_path_part] ( identifier[url] , identifier[regex] = identifier[PATH_PART] ):
literal[string]
identifier[formatter] = identifier[string] . identifier[Formatter] ()
identifier[url_var_template] = literal[string]
keyword[for] identifier[part] keyword[in] identifier[fo... | def add_path_part(url, regex=PATH_PART):
"""
replace the variables in a url template with regex named groups
:param url: string of a url template
:param regex: regex of the named group
:returns: regex
"""
formatter = string.Formatter()
url_var_template = '(?P<{var_name}>{regex})'
for... |
def read(self, handle):
'''Read binary data for this parameter from a file handle.
This reads exactly enough data from the current position in the file to
initialize the parameter.
'''
self.bytes_per_element, = struct.unpack('b', handle.read(1))
dims, = struct.unpack('B'... | def function[read, parameter[self, handle]]:
constant[Read binary data for this parameter from a file handle.
This reads exactly enough data from the current position in the file to
initialize the parameter.
]
<ast.Tuple object at 0x7da207f99a20> assign[=] call[name[struct].unpa... | keyword[def] identifier[read] ( identifier[self] , identifier[handle] ):
literal[string]
identifier[self] . identifier[bytes_per_element] ,= identifier[struct] . identifier[unpack] ( literal[string] , identifier[handle] . identifier[read] ( literal[int] ))
identifier[dims] ,= identifier[st... | def read(self, handle):
"""Read binary data for this parameter from a file handle.
This reads exactly enough data from the current position in the file to
initialize the parameter.
"""
(self.bytes_per_element,) = struct.unpack('b', handle.read(1))
(dims,) = struct.unpack('B', handle... |
def rn(shape, dtype=None, impl='numpy', **kwargs):
"""Return a space of real tensors.
Parameters
----------
shape : positive int or sequence of positive ints
Number of entries per axis for elements in this space. A
single integer results in a space with 1 axis.
dtype : optional
... | def function[rn, parameter[shape, dtype, impl]]:
constant[Return a space of real tensors.
Parameters
----------
shape : positive int or sequence of positive ints
Number of entries per axis for elements in this space. A
single integer results in a space with 1 axis.
dtype : optio... | keyword[def] identifier[rn] ( identifier[shape] , identifier[dtype] = keyword[None] , identifier[impl] = literal[string] ,** identifier[kwargs] ):
literal[string]
identifier[rn_cls] = identifier[tensor_space_impl] ( identifier[impl] )
keyword[if] identifier[dtype] keyword[is] keyword[None] :
... | def rn(shape, dtype=None, impl='numpy', **kwargs):
"""Return a space of real tensors.
Parameters
----------
shape : positive int or sequence of positive ints
Number of entries per axis for elements in this space. A
single integer results in a space with 1 axis.
dtype : optional
... |
def ValidateEmail(email, column_name=None, problems=None):
"""
checks the basic validity of email:
- an empty email is considered valid and no error or warning is issued.
- should start with any string not including @
- then should match a single @
- then matches any string not including @
- the... | def function[ValidateEmail, parameter[email, column_name, problems]]:
constant[
checks the basic validity of email:
- an empty email is considered valid and no error or warning is issued.
- should start with any string not including @
- then should match a single @
- then matches any string no... | keyword[def] identifier[ValidateEmail] ( identifier[email] , identifier[column_name] = keyword[None] , identifier[problems] = keyword[None] ):
literal[string]
keyword[if] identifier[IsEmpty] ( identifier[email] ) keyword[or] identifier[re] . identifier[match] ( literal[string] , identifier[email] ):
key... | def ValidateEmail(email, column_name=None, problems=None):
"""
checks the basic validity of email:
- an empty email is considered valid and no error or warning is issued.
- should start with any string not including @
- then should match a single @
- then matches any string not including @
- t... |
def create_with_virtualenv(self, interpreter, virtualenv_options):
"""Create a virtualenv using the virtualenv lib."""
args = ['virtualenv', '--python', interpreter, self.env_path]
args.extend(virtualenv_options)
if not self.pip_installed:
args.insert(3, '--no-pip')
t... | def function[create_with_virtualenv, parameter[self, interpreter, virtualenv_options]]:
constant[Create a virtualenv using the virtualenv lib.]
variable[args] assign[=] list[[<ast.Constant object at 0x7da1b0f59240>, <ast.Constant object at 0x7da1b0f59c30>, <ast.Name object at 0x7da1b0f5bd30>, <ast.Attri... | keyword[def] identifier[create_with_virtualenv] ( identifier[self] , identifier[interpreter] , identifier[virtualenv_options] ):
literal[string]
identifier[args] =[ literal[string] , literal[string] , identifier[interpreter] , identifier[self] . identifier[env_path] ]
identifier[args] . id... | def create_with_virtualenv(self, interpreter, virtualenv_options):
"""Create a virtualenv using the virtualenv lib."""
args = ['virtualenv', '--python', interpreter, self.env_path]
args.extend(virtualenv_options)
if not self.pip_installed:
args.insert(3, '--no-pip') # depends on [control=['if']... |
def run(self):
"""Run the minimization.
Returns
-------
K : (N,N) ndarray
the optimal rate matrix
"""
if self.verbose:
self.selftest()
self.count = 0
if self.verbose:
logging.info('initial value of the objective functio... | def function[run, parameter[self]]:
constant[Run the minimization.
Returns
-------
K : (N,N) ndarray
the optimal rate matrix
]
if name[self].verbose begin[:]
call[name[self].selftest, parameter[]]
name[self].count assign[=] constant[0]... | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[verbose] :
identifier[self] . identifier[selftest] ()
identifier[self] . identifier[count] = literal[int]
keyword[if] identifier[self] . identifier[verbose]... | def run(self):
"""Run the minimization.
Returns
-------
K : (N,N) ndarray
the optimal rate matrix
"""
if self.verbose:
self.selftest() # depends on [control=['if'], data=[]]
self.count = 0
if self.verbose:
logging.info('initial value of the o... |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: CertificateContext for this CertificateInstance
:rtype: twilio.rest.preview.deployed_devices.flee... | def function[_proxy, parameter[self]]:
constant[
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: CertificateContext for this CertificateInstance
:rtype: twilio.rest.pr... | keyword[def] identifier[_proxy] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_context] keyword[is] keyword[None] :
identifier[self] . identifier[_context] = identifier[CertificateContext] (
identifier[self] . identifier[_version] ,
... | def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: CertificateContext for this CertificateInstance
:rtype: twilio.rest.preview.deployed_devices.fleet.ce... |
def get(self, sid):
"""
Constructs a IpAddressContext
:param sid: A string that identifies the IpAddress resource to fetch
:returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressContext
:rtype: twilio.rest.api.v2010.account.sip.ip_access_control_... | def function[get, parameter[self, sid]]:
constant[
Constructs a IpAddressContext
:param sid: A string that identifies the IpAddress resource to fetch
:returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressContext
:rtype: twilio.rest.api.v2010.acc... | keyword[def] identifier[get] ( identifier[self] , identifier[sid] ):
literal[string]
keyword[return] identifier[IpAddressContext] (
identifier[self] . identifier[_version] ,
identifier[account_sid] = identifier[self] . identifier[_solution] [ literal[string] ],
identifie... | def get(self, sid):
"""
Constructs a IpAddressContext
:param sid: A string that identifies the IpAddress resource to fetch
:returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressContext
:rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list... |
def add_generic_error_message_with_code(request, error_code):
"""
Add message to request indicating that there was an issue processing request.
Arguments:
request: The current request.
error_code: A string error code to be used to point devs to the spot in
the code where... | def function[add_generic_error_message_with_code, parameter[request, error_code]]:
constant[
Add message to request indicating that there was an issue processing request.
Arguments:
request: The current request.
error_code: A string error code to be used to point devs to the spot in
... | keyword[def] identifier[add_generic_error_message_with_code] ( identifier[request] , identifier[error_code] ):
literal[string]
identifier[messages] . identifier[error] (
identifier[request] ,
identifier[_] (
literal[string]
literal[string]
literal[string]
literal[string]
... | def add_generic_error_message_with_code(request, error_code):
"""
Add message to request indicating that there was an issue processing request.
Arguments:
request: The current request.
error_code: A string error code to be used to point devs to the spot in
the code where... |
def handle_error(self, error, req, schema, error_status_code, error_headers):
"""Handles errors during parsing. Aborts the current HTTP request and
responds with a 422 error.
"""
status_code = error_status_code or self.DEFAULT_VALIDATION_STATUS
abort(
status_code,
... | def function[handle_error, parameter[self, error, req, schema, error_status_code, error_headers]]:
constant[Handles errors during parsing. Aborts the current HTTP request and
responds with a 422 error.
]
variable[status_code] assign[=] <ast.BoolOp object at 0x7da1b22cf1c0>
call[n... | keyword[def] identifier[handle_error] ( identifier[self] , identifier[error] , identifier[req] , identifier[schema] , identifier[error_status_code] , identifier[error_headers] ):
literal[string]
identifier[status_code] = identifier[error_status_code] keyword[or] identifier[self] . identifier[DEFA... | def handle_error(self, error, req, schema, error_status_code, error_headers):
"""Handles errors during parsing. Aborts the current HTTP request and
responds with a 422 error.
"""
status_code = error_status_code or self.DEFAULT_VALIDATION_STATUS
abort(status_code, exc=error, messages=error.me... |
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the UsernamePasswordCredential struct and
decode it into its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, suppor... | def function[read, parameter[self, input_stream, kmip_version]]:
constant[
Read the data encoding the UsernamePasswordCredential struct and
decode it into its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, suppor... | keyword[def] identifier[read] ( identifier[self] , identifier[input_stream] , identifier[kmip_version] = identifier[enums] . identifier[KMIPVersion] . identifier[KMIP_1_0] ):
literal[string]
identifier[super] ( identifier[UsernamePasswordCredential] , identifier[self] ). identifier[read] (
... | def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the UsernamePasswordCredential struct and
decode it into its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting... |
def checkout(self):
'''
Checkout the configured branch/tag. We catch an "Exception" class here
instead of a specific exception class because the exceptions raised by
GitPython when running these functions vary in different versions of
GitPython.
'''
tgt_ref = self... | def function[checkout, parameter[self]]:
constant[
Checkout the configured branch/tag. We catch an "Exception" class here
instead of a specific exception class because the exceptions raised by
GitPython when running these functions vary in different versions of
GitPython.
... | keyword[def] identifier[checkout] ( identifier[self] ):
literal[string]
identifier[tgt_ref] = identifier[self] . identifier[get_checkout_target] ()
keyword[try] :
identifier[head_sha] = identifier[self] . identifier[repo] . identifier[rev_parse] ( literal[string] ). identifier... | def checkout(self):
"""
Checkout the configured branch/tag. We catch an "Exception" class here
instead of a specific exception class because the exceptions raised by
GitPython when running these functions vary in different versions of
GitPython.
"""
tgt_ref = self.get_che... |
def _get_color_from_config(config, option):
"""
Helper method to uet an option from the COLOR_SECTION of the config.
Returns None if the value is not present. If the value is present, it tries
to parse the value as a raw string literal, allowing escape sequences in
the egrc.
"""
if not conf... | def function[_get_color_from_config, parameter[config, option]]:
constant[
Helper method to uet an option from the COLOR_SECTION of the config.
Returns None if the value is not present. If the value is present, it tries
to parse the value as a raw string literal, allowing escape sequences in
th... | keyword[def] identifier[_get_color_from_config] ( identifier[config] , identifier[option] ):
literal[string]
keyword[if] keyword[not] identifier[config] . identifier[has_option] ( identifier[COLOR_SECTION] , identifier[option] ):
keyword[return] keyword[None]
keyword[else] :
keyw... | def _get_color_from_config(config, option):
"""
Helper method to uet an option from the COLOR_SECTION of the config.
Returns None if the value is not present. If the value is present, it tries
to parse the value as a raw string literal, allowing escape sequences in
the egrc.
"""
if not conf... |
def yoffset(self, value):
"""gets/sets the yoffset"""
if self._yoffset != value and \
isinstance(value, (int, float, long)):
self._yoffset = value | def function[yoffset, parameter[self, value]]:
constant[gets/sets the yoffset]
if <ast.BoolOp object at 0x7da1b11a8fa0> begin[:]
name[self]._yoffset assign[=] name[value] | keyword[def] identifier[yoffset] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[self] . identifier[_yoffset] != identifier[value] keyword[and] identifier[isinstance] ( identifier[value] ,( identifier[int] , identifier[float] , identifier[long] )):
i... | def yoffset(self, value):
"""gets/sets the yoffset"""
if self._yoffset != value and isinstance(value, (int, float, long)):
self._yoffset = value # depends on [control=['if'], data=[]] |
def _initialize_upload(self):
"""
Initialized the upload on the API server by submitting the information
about the project, the file name, file size and the part size that is
going to be used during multipart upload.
"""
init_data = {
'name': self._file_name,... | def function[_initialize_upload, parameter[self]]:
constant[
Initialized the upload on the API server by submitting the information
about the project, the file name, file size and the part size that is
going to be used during multipart upload.
]
variable[init_data] assign... | keyword[def] identifier[_initialize_upload] ( identifier[self] ):
literal[string]
identifier[init_data] ={
literal[string] : identifier[self] . identifier[_file_name] ,
literal[string] : identifier[self] . identifier[_part_size] ,
literal[string] : identifier[self] . ide... | def _initialize_upload(self):
"""
Initialized the upload on the API server by submitting the information
about the project, the file name, file size and the part size that is
going to be used during multipart upload.
"""
init_data = {'name': self._file_name, 'part_size': self._pa... |
def reconfigure(self, service_id, workers):
"""Reconfigure a service registered in ServiceManager
:param service_id: the service id
:type service_id: uuid.uuid4
:param workers: number of processes/workers for this service
:type workers: int
:raises: ValueError
""... | def function[reconfigure, parameter[self, service_id, workers]]:
constant[Reconfigure a service registered in ServiceManager
:param service_id: the service id
:type service_id: uuid.uuid4
:param workers: number of processes/workers for this service
:type workers: int
:ra... | keyword[def] identifier[reconfigure] ( identifier[self] , identifier[service_id] , identifier[workers] ):
literal[string]
keyword[try] :
identifier[sc] = identifier[self] . identifier[_services] [ identifier[service_id] ]
keyword[except] identifier[KeyError] :
ke... | def reconfigure(self, service_id, workers):
"""Reconfigure a service registered in ServiceManager
:param service_id: the service id
:type service_id: uuid.uuid4
:param workers: number of processes/workers for this service
:type workers: int
:raises: ValueError
"""
... |
def _create_jspath(self) -> Path:
"""Create the source directory for the build."""
src = self._build_dir / 'bowtiejs'
os.makedirs(src, exist_ok=True)
return src | def function[_create_jspath, parameter[self]]:
constant[Create the source directory for the build.]
variable[src] assign[=] binary_operation[name[self]._build_dir / constant[bowtiejs]]
call[name[os].makedirs, parameter[name[src]]]
return[name[src]] | keyword[def] identifier[_create_jspath] ( identifier[self] )-> identifier[Path] :
literal[string]
identifier[src] = identifier[self] . identifier[_build_dir] / literal[string]
identifier[os] . identifier[makedirs] ( identifier[src] , identifier[exist_ok] = keyword[True] )
keyword... | def _create_jspath(self) -> Path:
"""Create the source directory for the build."""
src = self._build_dir / 'bowtiejs'
os.makedirs(src, exist_ok=True)
return src |
def _first_word_not_cmd(self,
first_word: str,
command: str,
args: tuple,
kwargs: dict) -> None:
"""
check to see if this is an author or service.
This method does high level control h... | def function[_first_word_not_cmd, parameter[self, first_word, command, args, kwargs]]:
constant[
check to see if this is an author or service.
This method does high level control handling
]
if call[name[self].service_interface.is_service, parameter[name[first_word]]] begin[:]
... | keyword[def] identifier[_first_word_not_cmd] ( identifier[self] ,
identifier[first_word] : identifier[str] ,
identifier[command] : identifier[str] ,
identifier[args] : identifier[tuple] ,
identifier[kwargs] : identifier[dict] )-> keyword[None] :
literal[string]
keyword[if] identifier[self] . i... | def _first_word_not_cmd(self, first_word: str, command: str, args: tuple, kwargs: dict) -> None:
"""
check to see if this is an author or service.
This method does high level control handling
"""
if self.service_interface.is_service(first_word):
self._logger.debug(' first word is... |
def _pop_digits(char_list):
"""Pop consecutive digits from the front of list and return them
Pops any and all consecutive digits from the start of the provided
character list and returns them as a list of string digits.
Operates on (and possibly alters) the passed list.
:param list char_list: a li... | def function[_pop_digits, parameter[char_list]]:
constant[Pop consecutive digits from the front of list and return them
Pops any and all consecutive digits from the start of the provided
character list and returns them as a list of string digits.
Operates on (and possibly alters) the passed list.
... | keyword[def] identifier[_pop_digits] ( identifier[char_list] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] , identifier[char_list] )
identifier[digits] =[]
keyword[while] identifier[len] ( identifier[char_list] )!= literal[int] keyword[and] identifier[char_list] [... | def _pop_digits(char_list):
"""Pop consecutive digits from the front of list and return them
Pops any and all consecutive digits from the start of the provided
character list and returns them as a list of string digits.
Operates on (and possibly alters) the passed list.
:param list char_list: a li... |
def make_xpath_ranges(html, phrase):
'''Given a HTML string and a `phrase`, build a regex to find offsets
for the phrase, and then build a list of `XPathRange` objects for
it. If this fails, return empty list.
'''
if not html:
return []
if not isinstance(phrase, unicode):
try:
... | def function[make_xpath_ranges, parameter[html, phrase]]:
constant[Given a HTML string and a `phrase`, build a regex to find offsets
for the phrase, and then build a list of `XPathRange` objects for
it. If this fails, return empty list.
]
if <ast.UnaryOp object at 0x7da18dc9ab60> begin[:]
... | keyword[def] identifier[make_xpath_ranges] ( identifier[html] , identifier[phrase] ):
literal[string]
keyword[if] keyword[not] identifier[html] :
keyword[return] []
keyword[if] keyword[not] identifier[isinstance] ( identifier[phrase] , identifier[unicode] ):
keyword[try] :
... | def make_xpath_ranges(html, phrase):
"""Given a HTML string and a `phrase`, build a regex to find offsets
for the phrase, and then build a list of `XPathRange` objects for
it. If this fails, return empty list.
"""
if not html:
return [] # depends on [control=['if'], data=[]]
if not is... |
def merged_type(t, s):
# type: (AbstractType, AbstractType) -> Optional[AbstractType]
"""Return merged type if two items can be merged in to a different, more general type.
Return None if merging is not possible.
"""
if isinstance(t, TupleType) and isinstance(s, TupleType):
if len(t.items) ... | def function[merged_type, parameter[t, s]]:
constant[Return merged type if two items can be merged in to a different, more general type.
Return None if merging is not possible.
]
if <ast.BoolOp object at 0x7da2047e8490> begin[:]
if compare[call[name[len], parameter[name[t].items... | keyword[def] identifier[merged_type] ( identifier[t] , identifier[s] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[t] , identifier[TupleType] ) keyword[and] identifier[isinstance] ( identifier[s] , identifier[TupleType] ):
keyword[if] identifier[len] ( identifier[t] . iden... | def merged_type(t, s):
# type: (AbstractType, AbstractType) -> Optional[AbstractType]
'Return merged type if two items can be merged in to a different, more general type.\n\n Return None if merging is not possible.\n '
if isinstance(t, TupleType) and isinstance(s, TupleType):
if len(t.items) =... |
def count_dimensions(entry):
"""Counts the number of dimensions from a nested list of dimension assignments
that may include function calls.
"""
result = 0
for e in entry:
if isinstance(e, str):
sliced = e.strip(",").split(",")
result += 0 if len(sliced) == 1 and slic... | def function[count_dimensions, parameter[entry]]:
constant[Counts the number of dimensions from a nested list of dimension assignments
that may include function calls.
]
variable[result] assign[=] constant[0]
for taget[name[e]] in starred[name[entry]] begin[:]
if call[nam... | keyword[def] identifier[count_dimensions] ( identifier[entry] ):
literal[string]
identifier[result] = literal[int]
keyword[for] identifier[e] keyword[in] identifier[entry] :
keyword[if] identifier[isinstance] ( identifier[e] , identifier[str] ):
identifier[sliced] = identifi... | def count_dimensions(entry):
"""Counts the number of dimensions from a nested list of dimension assignments
that may include function calls.
"""
result = 0
for e in entry:
if isinstance(e, str):
sliced = e.strip(',').split(',')
result += 0 if len(sliced) == 1 and slic... |
async def get_sound_settings(self, target="") -> List[Setting]:
"""Get the current sound settings.
:param str target: settings target, defaults to all.
"""
res = await self.services["audio"]["getSoundSettings"]({"target": target})
return [Setting.make(**x) for x in res] | <ast.AsyncFunctionDef object at 0x7da18f00d6f0> | keyword[async] keyword[def] identifier[get_sound_settings] ( identifier[self] , identifier[target] = literal[string] )-> identifier[List] [ identifier[Setting] ]:
literal[string]
identifier[res] = keyword[await] identifier[self] . identifier[services] [ literal[string] ][ literal[string] ]({ lite... | async def get_sound_settings(self, target='') -> List[Setting]:
"""Get the current sound settings.
:param str target: settings target, defaults to all.
"""
res = await self.services['audio']['getSoundSettings']({'target': target})
return [Setting.make(**x) for x in res] |
def binom(n, k):
"""
Returns binomial coefficient (n choose k).
"""
# http://blog.plover.com/math/choose.html
if k > n:
return 0
if k == 0:
return 1
result = 1
for denom in range(1, k + 1):
result *= n
result /= denom
n -= 1
return result | def function[binom, parameter[n, k]]:
constant[
Returns binomial coefficient (n choose k).
]
if compare[name[k] greater[>] name[n]] begin[:]
return[constant[0]]
if compare[name[k] equal[==] constant[0]] begin[:]
return[constant[1]]
variable[result] assign[=] const... | keyword[def] identifier[binom] ( identifier[n] , identifier[k] ):
literal[string]
keyword[if] identifier[k] > identifier[n] :
keyword[return] literal[int]
keyword[if] identifier[k] == literal[int] :
keyword[return] literal[int]
identifier[result] = literal[int]
... | def binom(n, k):
"""
Returns binomial coefficient (n choose k).
"""
# http://blog.plover.com/math/choose.html
if k > n:
return 0 # depends on [control=['if'], data=[]]
if k == 0:
return 1 # depends on [control=['if'], data=[]]
result = 1
for denom in range(1, k + 1):
... |
def serialize(self):
"""
Serializes into a bytestring.
:returns: An object of type Bytes.
"""
d = self.__getstate__()
return pickle.dumps({
'name': d['name'],
'seg': pickle.dumps(d['seg'], protocol=-1),
}, protocol=-1) | def function[serialize, parameter[self]]:
constant[
Serializes into a bytestring.
:returns: An object of type Bytes.
]
variable[d] assign[=] call[name[self].__getstate__, parameter[]]
return[call[name[pickle].dumps, parameter[dictionary[[<ast.Constant object at 0x7da1b055016... | keyword[def] identifier[serialize] ( identifier[self] ):
literal[string]
identifier[d] = identifier[self] . identifier[__getstate__] ()
keyword[return] identifier[pickle] . identifier[dumps] ({
literal[string] : identifier[d] [ literal[string] ],
literal[string] : identi... | def serialize(self):
"""
Serializes into a bytestring.
:returns: An object of type Bytes.
"""
d = self.__getstate__()
return pickle.dumps({'name': d['name'], 'seg': pickle.dumps(d['seg'], protocol=-1)}, protocol=-1) |
def css(self, css):
""" Finds another node by a CSS selector relative to the current node. """
return [self.get_node_factory().create(node_id)
for node_id in self._get_css_ids(css).split(",")
if node_id] | def function[css, parameter[self, css]]:
constant[ Finds another node by a CSS selector relative to the current node. ]
return[<ast.ListComp object at 0x7da20c7ca620>] | keyword[def] identifier[css] ( identifier[self] , identifier[css] ):
literal[string]
keyword[return] [ identifier[self] . identifier[get_node_factory] (). identifier[create] ( identifier[node_id] )
keyword[for] identifier[node_id] keyword[in] identifier[self] . identifier[_get_css_ids] ( identifier... | def css(self, css):
""" Finds another node by a CSS selector relative to the current node. """
return [self.get_node_factory().create(node_id) for node_id in self._get_css_ids(css).split(',') if node_id] |
def open_target_group_for_form(self, form):
"""
Makes sure that the first group that should be open is open.
This is either the first group with errors or the first group
in the container, unless that first group was originally set to
active=False.
"""
target = se... | def function[open_target_group_for_form, parameter[self, form]]:
constant[
Makes sure that the first group that should be open is open.
This is either the first group with errors or the first group
in the container, unless that first group was originally set to
active=False.
... | keyword[def] identifier[open_target_group_for_form] ( identifier[self] , identifier[form] ):
literal[string]
identifier[target] = identifier[self] . identifier[first_container_with_errors] ( identifier[form] . identifier[errors] . identifier[keys] ())
keyword[if] identifier[target] keywo... | def open_target_group_for_form(self, form):
"""
Makes sure that the first group that should be open is open.
This is either the first group with errors or the first group
in the container, unless that first group was originally set to
active=False.
"""
target = self.first... |
def connect(self, uuid_value, wait=None):
"""Connect to a specific device by its uuid
Attempt to connect to a device that we have previously scanned using its UUID.
If wait is not None, then it is used in the same was a scan(wait) to override
default wait times with an explicit value.
... | def function[connect, parameter[self, uuid_value, wait]]:
constant[Connect to a specific device by its uuid
Attempt to connect to a device that we have previously scanned using its UUID.
If wait is not None, then it is used in the same was a scan(wait) to override
default wait times wit... | keyword[def] identifier[connect] ( identifier[self] , identifier[uuid_value] , identifier[wait] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[connected] :
keyword[raise] identifier[HardwareError] ( literal[string] )
keyword[if] identifier[uu... | def connect(self, uuid_value, wait=None):
"""Connect to a specific device by its uuid
Attempt to connect to a device that we have previously scanned using its UUID.
If wait is not None, then it is used in the same was a scan(wait) to override
default wait times with an explicit value.
... |
def parse_machine_listing(text: str, convert: bool=True, strict: bool=True) -> \
List[dict]:
'''Parse machine listing.
Args:
text: The listing.
convert: Convert sizes and dates.
strict: Method of handling errors. ``True`` will raise
``ValueError``. ``False`` will ign... | def function[parse_machine_listing, parameter[text, convert, strict]]:
constant[Parse machine listing.
Args:
text: The listing.
convert: Convert sizes and dates.
strict: Method of handling errors. ``True`` will raise
``ValueError``. ``False`` will ignore rows with errors... | keyword[def] identifier[parse_machine_listing] ( identifier[text] : identifier[str] , identifier[convert] : identifier[bool] = keyword[True] , identifier[strict] : identifier[bool] = keyword[True] )-> identifier[List] [ identifier[dict] ]:
literal[string]
identifier[listing] =[]
keyword[for] id... | def parse_machine_listing(text: str, convert: bool=True, strict: bool=True) -> List[dict]:
"""Parse machine listing.
Args:
text: The listing.
convert: Convert sizes and dates.
strict: Method of handling errors. ``True`` will raise
``ValueError``. ``False`` will ignore rows w... |
def _get_asset_content(self, asset_content_id):
"""stub"""
asset_content = None
for asset in self._asset_lookup_session.get_assets():
for content in asset.get_asset_contents():
if content.get_id() == asset_content_id:
asset_content = content
... | def function[_get_asset_content, parameter[self, asset_content_id]]:
constant[stub]
variable[asset_content] assign[=] constant[None]
for taget[name[asset]] in starred[call[name[self]._asset_lookup_session.get_assets, parameter[]]] begin[:]
for taget[name[content]] in starred[call... | keyword[def] identifier[_get_asset_content] ( identifier[self] , identifier[asset_content_id] ):
literal[string]
identifier[asset_content] = keyword[None]
keyword[for] identifier[asset] keyword[in] identifier[self] . identifier[_asset_lookup_session] . identifier[get_assets] ():
... | def _get_asset_content(self, asset_content_id):
"""stub"""
asset_content = None
for asset in self._asset_lookup_session.get_assets():
for content in asset.get_asset_contents():
if content.get_id() == asset_content_id:
asset_content = content
break # depen... |
def _merge_entity(entity, if_match, require_encryption=False, key_encryption_key=None):
'''
Constructs a merge entity request.
'''
_validate_not_none('if_match', if_match)
_validate_entity(entity)
_validate_encryption_unsupported(require_encryption, key_encryption_key)
request = HTTPRequest... | def function[_merge_entity, parameter[entity, if_match, require_encryption, key_encryption_key]]:
constant[
Constructs a merge entity request.
]
call[name[_validate_not_none], parameter[constant[if_match], name[if_match]]]
call[name[_validate_entity], parameter[name[entity]]]
cal... | keyword[def] identifier[_merge_entity] ( identifier[entity] , identifier[if_match] , identifier[require_encryption] = keyword[False] , identifier[key_encryption_key] = keyword[None] ):
literal[string]
identifier[_validate_not_none] ( literal[string] , identifier[if_match] )
identifier[_validate_entity... | def _merge_entity(entity, if_match, require_encryption=False, key_encryption_key=None):
"""
Constructs a merge entity request.
"""
_validate_not_none('if_match', if_match)
_validate_entity(entity)
_validate_encryption_unsupported(require_encryption, key_encryption_key)
request = HTTPRequest(... |
def genCubeVector(x, y, z, x_mult=1, y_mult=1, z_mult=1):
"""Generates a map of vector lengths from the center point to each coordinate
x - width of matrix to generate
y - height of matrix to generate
z - depth of matrix to generate
x_mult - value to scale x-axis by
y_mult - value to sca... | def function[genCubeVector, parameter[x, y, z, x_mult, y_mult, z_mult]]:
constant[Generates a map of vector lengths from the center point to each coordinate
x - width of matrix to generate
y - height of matrix to generate
z - depth of matrix to generate
x_mult - value to scale x-axis by
y_m... | keyword[def] identifier[genCubeVector] ( identifier[x] , identifier[y] , identifier[z] , identifier[x_mult] = literal[int] , identifier[y_mult] = literal[int] , identifier[z_mult] = literal[int] ):
literal[string]
identifier[cX] =( identifier[x] - literal[int] )/ literal[int]
identifier[cY] =( ide... | def genCubeVector(x, y, z, x_mult=1, y_mult=1, z_mult=1):
"""Generates a map of vector lengths from the center point to each coordinate
x - width of matrix to generate
y - height of matrix to generate
z - depth of matrix to generate
x_mult - value to scale x-axis by
y_mult - value to scale y-ax... |
def parse_order(text):
"""
:param text: order=id.desc, xxx.asc
:return: [
[<column>, asc|desc|default],
[<column2>, asc|desc|default],
]
"""
orders = []
for i in map(str.strip, text.split(',')):
items = i.split('.', 2)
... | def function[parse_order, parameter[text]]:
constant[
:param text: order=id.desc, xxx.asc
:return: [
[<column>, asc|desc|default],
[<column2>, asc|desc|default],
]
]
variable[orders] assign[=] list[[]]
for taget[name[i]] in starred[call[nam... | keyword[def] identifier[parse_order] ( identifier[text] ):
literal[string]
identifier[orders] =[]
keyword[for] identifier[i] keyword[in] identifier[map] ( identifier[str] . identifier[strip] , identifier[text] . identifier[split] ( literal[string] )):
identifier[items] = id... | def parse_order(text):
"""
:param text: order=id.desc, xxx.asc
:return: [
[<column>, asc|desc|default],
[<column2>, asc|desc|default],
]
"""
orders = []
for i in map(str.strip, text.split(',')):
items = i.split('.', 2)
if len(items) == ... |
def list(self, *kinds, **kwargs):
"""Returns a list of inputs that are in the :class:`Inputs` collection.
You can also filter by one or more input kinds.
This function iterates over all possible inputs, regardless of any arguments you
specify. Because the :class:`Inputs` collection is t... | def function[list, parameter[self]]:
constant[Returns a list of inputs that are in the :class:`Inputs` collection.
You can also filter by one or more input kinds.
This function iterates over all possible inputs, regardless of any arguments you
specify. Because the :class:`Inputs` collec... | keyword[def] identifier[list] ( identifier[self] ,* identifier[kinds] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[len] ( identifier[kinds] )== literal[int] :
identifier[kinds] = identifier[self] . identifier[kinds]
keyword[if] identifier[len] ( identifi... | def list(self, *kinds, **kwargs):
"""Returns a list of inputs that are in the :class:`Inputs` collection.
You can also filter by one or more input kinds.
This function iterates over all possible inputs, regardless of any arguments you
specify. Because the :class:`Inputs` collection is the u... |
def server_identity_is_verified(self):
""" GPGAuth stage0 """
# Encrypt a uuid token for the server
server_verify_token = self.gpg.encrypt(self._nonce0,
self.server_fingerprint, always_trust=True)
if not server_verify_token.ok:
r... | def function[server_identity_is_verified, parameter[self]]:
constant[ GPGAuth stage0 ]
variable[server_verify_token] assign[=] call[name[self].gpg.encrypt, parameter[name[self]._nonce0, name[self].server_fingerprint]]
if <ast.UnaryOp object at 0x7da18ede4fd0> begin[:]
<ast.Raise object a... | keyword[def] identifier[server_identity_is_verified] ( identifier[self] ):
literal[string]
identifier[server_verify_token] = identifier[self] . identifier[gpg] . identifier[encrypt] ( identifier[self] . identifier[_nonce0] ,
identifier[self] . identifier[server_fingerprint] , iden... | def server_identity_is_verified(self):
""" GPGAuth stage0 """
# Encrypt a uuid token for the server
server_verify_token = self.gpg.encrypt(self._nonce0, self.server_fingerprint, always_trust=True)
if not server_verify_token.ok:
raise GPGAuthStage0Exception('Encryption of the nonce0 (%s) to the s... |
def get_chunks(Array, Chunksize):
"""Generator that yields chunks of size ChunkSize"""
for i in range(0, len(Array), Chunksize):
yield Array[i:i + Chunksize] | def function[get_chunks, parameter[Array, Chunksize]]:
constant[Generator that yields chunks of size ChunkSize]
for taget[name[i]] in starred[call[name[range], parameter[constant[0], call[name[len], parameter[name[Array]]], name[Chunksize]]]] begin[:]
<ast.Yield object at 0x7da20e963b50> | keyword[def] identifier[get_chunks] ( identifier[Array] , identifier[Chunksize] ):
literal[string]
keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] , identifier[len] ( identifier[Array] ), identifier[Chunksize] ):
keyword[yield] identifier[Array] [ identifier[i] : identi... | def get_chunks(Array, Chunksize):
"""Generator that yields chunks of size ChunkSize"""
for i in range(0, len(Array), Chunksize):
yield Array[i:i + Chunksize] # depends on [control=['for'], data=['i']] |
def load_outputs(self):
"""Load output module(s)"""
for output in sorted(logdissect.output.__formats__):
self.output_modules[output] = \
__import__('logdissect.output.' + output, globals(), \
locals(), [logdissect]).OutputModule(args=self.output_args) | def function[load_outputs, parameter[self]]:
constant[Load output module(s)]
for taget[name[output]] in starred[call[name[sorted], parameter[name[logdissect].output.__formats__]]] begin[:]
call[name[self].output_modules][name[output]] assign[=] call[call[name[__import__], parameter[binar... | keyword[def] identifier[load_outputs] ( identifier[self] ):
literal[string]
keyword[for] identifier[output] keyword[in] identifier[sorted] ( identifier[logdissect] . identifier[output] . identifier[__formats__] ):
identifier[self] . identifier[output_modules] [ identifier[output] ]=... | def load_outputs(self):
"""Load output module(s)"""
for output in sorted(logdissect.output.__formats__):
self.output_modules[output] = __import__('logdissect.output.' + output, globals(), locals(), [logdissect]).OutputModule(args=self.output_args) # depends on [control=['for'], data=['output']] |
def create(self, friendly_name, aws_credentials_sid=values.unset,
encryption_key_sid=values.unset, aws_s3_url=values.unset,
aws_storage_enabled=values.unset, encryption_enabled=values.unset):
"""
Create a new RecordingSettingsInstance
:param unicode friendly_name: ... | def function[create, parameter[self, friendly_name, aws_credentials_sid, encryption_key_sid, aws_s3_url, aws_storage_enabled, encryption_enabled]]:
constant[
Create a new RecordingSettingsInstance
:param unicode friendly_name: Friendly name of the configuration to be shown in the console
... | keyword[def] identifier[create] ( identifier[self] , identifier[friendly_name] , identifier[aws_credentials_sid] = identifier[values] . identifier[unset] ,
identifier[encryption_key_sid] = identifier[values] . identifier[unset] , identifier[aws_s3_url] = identifier[values] . identifier[unset] ,
identifier[aws_stora... | def create(self, friendly_name, aws_credentials_sid=values.unset, encryption_key_sid=values.unset, aws_s3_url=values.unset, aws_storage_enabled=values.unset, encryption_enabled=values.unset):
"""
Create a new RecordingSettingsInstance
:param unicode friendly_name: Friendly name of the configuration... |
def renegotiate_keys(self):
"""
Force this session to switch to new keys. Normally this is done
automatically after the session hits a certain number of packets or
bytes sent or received, but this method gives you the option of forcing
new keys whenever you want. Negotiating ne... | def function[renegotiate_keys, parameter[self]]:
constant[
Force this session to switch to new keys. Normally this is done
automatically after the session hits a certain number of packets or
bytes sent or received, but this method gives you the option of forcing
new keys wheneve... | keyword[def] identifier[renegotiate_keys] ( identifier[self] ):
literal[string]
identifier[self] . identifier[completion_event] = identifier[threading] . identifier[Event] ()
identifier[self] . identifier[_send_kex_init] ()
keyword[while] keyword[True] :
identifier[s... | def renegotiate_keys(self):
"""
Force this session to switch to new keys. Normally this is done
automatically after the session hits a certain number of packets or
bytes sent or received, but this method gives you the option of forcing
new keys whenever you want. Negotiating new ke... |
def get_barcode_umis(read, cell_barcode=False):
''' extract the umi +/- cell barcode from the read name where the barcodes
were extracted using umis'''
umi, cell = None, None
try:
read_name_elements = read.qname.split(":")
for element in read_name_elements:
if element.starts... | def function[get_barcode_umis, parameter[read, cell_barcode]]:
constant[ extract the umi +/- cell barcode from the read name where the barcodes
were extracted using umis]
<ast.Tuple object at 0x7da20c794850> assign[=] tuple[[<ast.Constant object at 0x7da20c796350>, <ast.Constant object at 0x7da20c79... | keyword[def] identifier[get_barcode_umis] ( identifier[read] , identifier[cell_barcode] = keyword[False] ):
literal[string]
identifier[umi] , identifier[cell] = keyword[None] , keyword[None]
keyword[try] :
identifier[read_name_elements] = identifier[read] . identifier[qname] . identifier[sp... | def get_barcode_umis(read, cell_barcode=False):
""" extract the umi +/- cell barcode from the read name where the barcodes
were extracted using umis"""
(umi, cell) = (None, None)
try:
read_name_elements = read.qname.split(':')
for element in read_name_elements:
if element.sta... |
def makeMarkovApproxToNormal(x_grid,mu,sigma,K=351,bound=3.5):
'''
Creates an approximation to a normal distribution with mean mu and standard
deviation sigma, returning a stochastic vector called p_vec, corresponding
to values in x_grid. If a RV is distributed x~N(mu,sigma), then the expectation
o... | def function[makeMarkovApproxToNormal, parameter[x_grid, mu, sigma, K, bound]]:
constant[
Creates an approximation to a normal distribution with mean mu and standard
deviation sigma, returning a stochastic vector called p_vec, corresponding
to values in x_grid. If a RV is distributed x~N(mu,sigma),... | keyword[def] identifier[makeMarkovApproxToNormal] ( identifier[x_grid] , identifier[mu] , identifier[sigma] , identifier[K] = literal[int] , identifier[bound] = literal[int] ):
literal[string]
identifier[x_n] = identifier[x_grid] . identifier[size]
identifier[lower_bound] =- identifier[bound]
i... | def makeMarkovApproxToNormal(x_grid, mu, sigma, K=351, bound=3.5):
"""
Creates an approximation to a normal distribution with mean mu and standard
deviation sigma, returning a stochastic vector called p_vec, corresponding
to values in x_grid. If a RV is distributed x~N(mu,sigma), then the expectation
... |
def integrate(self, mass_min, mass_max, log_mode=True, weight=False, steps=1e4):
""" Numerical Riemannn integral of the IMF (stupid simple).
Parameters:
-----------
mass_min: minimum mass bound for integration (solar masses)
mass_max: maximum mass bound for integration (solar ma... | def function[integrate, parameter[self, mass_min, mass_max, log_mode, weight, steps]]:
constant[ Numerical Riemannn integral of the IMF (stupid simple).
Parameters:
-----------
mass_min: minimum mass bound for integration (solar masses)
mass_max: maximum mass bound for integrati... | keyword[def] identifier[integrate] ( identifier[self] , identifier[mass_min] , identifier[mass_max] , identifier[log_mode] = keyword[True] , identifier[weight] = keyword[False] , identifier[steps] = literal[int] ):
literal[string]
keyword[if] identifier[log_mode] :
identifier[d_log_ma... | def integrate(self, mass_min, mass_max, log_mode=True, weight=False, steps=10000.0):
""" Numerical Riemannn integral of the IMF (stupid simple).
Parameters:
-----------
mass_min: minimum mass bound for integration (solar masses)
mass_max: maximum mass bound for integration (solar ma... |
def at_depth(self, level):
"""
Locate the last config item at a specified depth
"""
return Zconfig(lib.zconfig_at_depth(self._as_parameter_, level), False) | def function[at_depth, parameter[self, level]]:
constant[
Locate the last config item at a specified depth
]
return[call[name[Zconfig], parameter[call[name[lib].zconfig_at_depth, parameter[name[self]._as_parameter_, name[level]]], constant[False]]]] | keyword[def] identifier[at_depth] ( identifier[self] , identifier[level] ):
literal[string]
keyword[return] identifier[Zconfig] ( identifier[lib] . identifier[zconfig_at_depth] ( identifier[self] . identifier[_as_parameter_] , identifier[level] ), keyword[False] ) | def at_depth(self, level):
"""
Locate the last config item at a specified depth
"""
return Zconfig(lib.zconfig_at_depth(self._as_parameter_, level), False) |
def pre_run_cell(self, cellno, code):
"""Executes before the user-entered code in `ipython` is run. This
intercepts loops and other problematic code that would produce lots of
database entries and streamlines it to produce only a single entry.
Args:
cellno (int): the cell nu... | def function[pre_run_cell, parameter[self, cellno, code]]:
constant[Executes before the user-entered code in `ipython` is run. This
intercepts loops and other problematic code that would produce lots of
database entries and streamlines it to produce only a single entry.
Args:
... | keyword[def] identifier[pre_run_cell] ( identifier[self] , identifier[cellno] , identifier[code] ):
literal[string]
identifier[self] . identifier[cellid] = identifier[cellno]
keyword[import] identifier[ast]
keyword[if] identifier[findloop] ... | def pre_run_cell(self, cellno, code):
"""Executes before the user-entered code in `ipython` is run. This
intercepts loops and other problematic code that would produce lots of
database entries and streamlines it to produce only a single entry.
Args:
cellno (int): the cell number... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.