code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def write_table(self, d):
"""
Write out a Python dictionary made of up string keys, and values
that are strings, signed integers, Decimal, datetime.datetime, or
sub-dictionaries following the same constraints.
"""
# HACK: encoding of AMQP tables is broken because it requi... | def function[write_table, parameter[self, d]]:
constant[
Write out a Python dictionary made of up string keys, and values
that are strings, signed integers, Decimal, datetime.datetime, or
sub-dictionaries following the same constraints.
]
variable[table_len_pos] assign[=]... | keyword[def] identifier[write_table] ( identifier[self] , identifier[d] ):
literal[string]
identifier[table_len_pos] = identifier[len] ( identifier[self] . identifier[_output_buffer] )
identifier[self] . identifier[write_long] ( literal[int] )
... | def write_table(self, d):
"""
Write out a Python dictionary made of up string keys, and values
that are strings, signed integers, Decimal, datetime.datetime, or
sub-dictionaries following the same constraints.
"""
# HACK: encoding of AMQP tables is broken because it requires the
... |
def set_tlsext_use_srtp(self, profiles):
"""
Enable support for negotiating SRTP keying material.
:param bytes profiles: A colon delimited list of protection profile
names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``.
:return: None
"""
if not is... | def function[set_tlsext_use_srtp, parameter[self, profiles]]:
constant[
Enable support for negotiating SRTP keying material.
:param bytes profiles: A colon delimited list of protection profile
names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``.
:return: None
... | keyword[def] identifier[set_tlsext_use_srtp] ( identifier[self] , identifier[profiles] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[profiles] , identifier[bytes] ):
keyword[raise] identifier[TypeError] ( literal[string] )
identifier[_open... | def set_tlsext_use_srtp(self, profiles):
"""
Enable support for negotiating SRTP keying material.
:param bytes profiles: A colon delimited list of protection profile
names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``.
:return: None
"""
if not isinstance... |
def publish(self, topic, message):
"""Publish a json message to a topic with a type and a sequence number
The actual message will be published as a JSON object:
{
"sequence": <incrementing id>,
"message": message
}
Args:
topic (string): The M... | def function[publish, parameter[self, topic, message]]:
constant[Publish a json message to a topic with a type and a sequence number
The actual message will be published as a JSON object:
{
"sequence": <incrementing id>,
"message": message
}
Args:
... | keyword[def] identifier[publish] ( identifier[self] , identifier[topic] , identifier[message] ):
literal[string]
identifier[seq] = identifier[self] . identifier[sequencer] . identifier[next_id] ( identifier[topic] )
identifier[packet] ={
literal[string] : identifier[seq] ,
... | def publish(self, topic, message):
"""Publish a json message to a topic with a type and a sequence number
The actual message will be published as a JSON object:
{
"sequence": <incrementing id>,
"message": message
}
Args:
topic (string): The MQTT ... |
def _read_message(self):
""" Reads a single size-annotated message from the server """
size = int(self.buf.read_line().decode("utf-8"))
return self.buf.read(size).decode("utf-8") | def function[_read_message, parameter[self]]:
constant[ Reads a single size-annotated message from the server ]
variable[size] assign[=] call[name[int], parameter[call[call[name[self].buf.read_line, parameter[]].decode, parameter[constant[utf-8]]]]]
return[call[call[name[self].buf.read, parameter[na... | keyword[def] identifier[_read_message] ( identifier[self] ):
literal[string]
identifier[size] = identifier[int] ( identifier[self] . identifier[buf] . identifier[read_line] (). identifier[decode] ( literal[string] ))
keyword[return] identifier[self] . identifier[buf] . identifier[read] ( identifier[s... | def _read_message(self):
""" Reads a single size-annotated message from the server """
size = int(self.buf.read_line().decode('utf-8'))
return self.buf.read(size).decode('utf-8') |
def multiline_string_lines(source, include_docstrings=False):
"""Return line numbers that are within multiline strings.
The line numbers are indexed at 1.
Docstrings are ignored.
"""
line_numbers = set()
previous_token_type = ''
try:
for t in generate_tokens(source):
t... | def function[multiline_string_lines, parameter[source, include_docstrings]]:
constant[Return line numbers that are within multiline strings.
The line numbers are indexed at 1.
Docstrings are ignored.
]
variable[line_numbers] assign[=] call[name[set], parameter[]]
variable[previous... | keyword[def] identifier[multiline_string_lines] ( identifier[source] , identifier[include_docstrings] = keyword[False] ):
literal[string]
identifier[line_numbers] = identifier[set] ()
identifier[previous_token_type] = literal[string]
keyword[try] :
keyword[for] identifier[t] keyword[i... | def multiline_string_lines(source, include_docstrings=False):
"""Return line numbers that are within multiline strings.
The line numbers are indexed at 1.
Docstrings are ignored.
"""
line_numbers = set()
previous_token_type = ''
try:
for t in generate_tokens(source):
t... |
def encode_dataset(dataset, vocabulary):
"""Encode from strings to token ids.
Args:
dataset: a tf.data.Dataset with string values.
vocabulary: a mesh_tensorflow.transformer.Vocabulary
Returns:
a tf.data.Dataset with integer-vector values ending in EOS=1
"""
def encode(features):
return {k: vo... | def function[encode_dataset, parameter[dataset, vocabulary]]:
constant[Encode from strings to token ids.
Args:
dataset: a tf.data.Dataset with string values.
vocabulary: a mesh_tensorflow.transformer.Vocabulary
Returns:
a tf.data.Dataset with integer-vector values ending in EOS=1
]
de... | keyword[def] identifier[encode_dataset] ( identifier[dataset] , identifier[vocabulary] ):
literal[string]
keyword[def] identifier[encode] ( identifier[features] ):
keyword[return] { identifier[k] : identifier[vocabulary] . identifier[encode_tf] ( identifier[v] ) keyword[for] identifier[k] , identifier[v... | def encode_dataset(dataset, vocabulary):
"""Encode from strings to token ids.
Args:
dataset: a tf.data.Dataset with string values.
vocabulary: a mesh_tensorflow.transformer.Vocabulary
Returns:
a tf.data.Dataset with integer-vector values ending in EOS=1
"""
def encode(features):
retu... |
def _next_non_ff_byte(self, start):
"""
Return an offset, byte 2-tuple for the next byte in *stream* that is
not '\xFF', starting with the byte at offset *start*. If the byte at
offset *start* is not '\xFF', *start* and the returned *offset* will
be the same.
"""
... | def function[_next_non_ff_byte, parameter[self, start]]:
constant[
Return an offset, byte 2-tuple for the next byte in *stream* that is
not 'ÿ', starting with the byte at offset *start*. If the byte at
offset *start* is not 'ÿ', *start* and the returned *offset* will
be the same.... | keyword[def] identifier[_next_non_ff_byte] ( identifier[self] , identifier[start] ):
literal[string]
identifier[self] . identifier[_stream] . identifier[seek] ( identifier[start] )
identifier[byte_] = identifier[self] . identifier[_read_byte] ()
keyword[while] identifier[byte_] =... | def _next_non_ff_byte(self, start):
"""
Return an offset, byte 2-tuple for the next byte in *stream* that is
not 'ÿ', starting with the byte at offset *start*. If the byte at
offset *start* is not 'ÿ', *start* and the returned *offset* will
be the same.
"""
self._stream.s... |
def mask_circular_annular_from_shape_pixel_scale_and_radii(shape, pixel_scale, inner_radius_arcsec, outer_radius_arcsec,
centre=(0.0, 0.0)):
"""Compute an annular masks from an input inner and outer masks radius and regular shape."""
mask = np.full(sha... | def function[mask_circular_annular_from_shape_pixel_scale_and_radii, parameter[shape, pixel_scale, inner_radius_arcsec, outer_radius_arcsec, centre]]:
constant[Compute an annular masks from an input inner and outer masks radius and regular shape.]
variable[mask] assign[=] call[name[np].full, parameter[n... | keyword[def] identifier[mask_circular_annular_from_shape_pixel_scale_and_radii] ( identifier[shape] , identifier[pixel_scale] , identifier[inner_radius_arcsec] , identifier[outer_radius_arcsec] ,
identifier[centre] =( literal[int] , literal[int] )):
literal[string]
identifier[mask] = identifier[np] . ide... | def mask_circular_annular_from_shape_pixel_scale_and_radii(shape, pixel_scale, inner_radius_arcsec, outer_radius_arcsec, centre=(0.0, 0.0)):
"""Compute an annular masks from an input inner and outer masks radius and regular shape."""
mask = np.full(shape, True)
centres_arcsec = mask_centres_from_shape_pixel... |
def get_blocks(self, chrom, start, end):
"""
Get any blocks in this alignment that overlap the given location.
:return: the alignment blocks that overlap a given genomic interval;
potentially none, in which case the empty list is returned.
"""
if chrom not in self.block_trees:
re... | def function[get_blocks, parameter[self, chrom, start, end]]:
constant[
Get any blocks in this alignment that overlap the given location.
:return: the alignment blocks that overlap a given genomic interval;
potentially none, in which case the empty list is returned.
]
if compar... | keyword[def] identifier[get_blocks] ( identifier[self] , identifier[chrom] , identifier[start] , identifier[end] ):
literal[string]
keyword[if] identifier[chrom] keyword[not] keyword[in] identifier[self] . identifier[block_trees] :
keyword[return] []
keyword[return] identifier[self] . iden... | def get_blocks(self, chrom, start, end):
"""
Get any blocks in this alignment that overlap the given location.
:return: the alignment blocks that overlap a given genomic interval;
potentially none, in which case the empty list is returned.
"""
if chrom not in self.block_trees:
... |
def _build(self, inputs):
"""Connects the SliceByDim module into the graph.
Args:
inputs: `Tensor` to slice. Its rank must be greater than the maximum
dimension specified in `dims` (plus one as python is 0 indexed).
Returns:
The sliced tensor.
Raises:
ValueError: If `input... | def function[_build, parameter[self, inputs]]:
constant[Connects the SliceByDim module into the graph.
Args:
inputs: `Tensor` to slice. Its rank must be greater than the maximum
dimension specified in `dims` (plus one as python is 0 indexed).
Returns:
The sliced tensor.
Rais... | keyword[def] identifier[_build] ( identifier[self] , identifier[inputs] ):
literal[string]
identifier[shape_inputs] = identifier[inputs] . identifier[get_shape] (). identifier[as_list] ()
identifier[rank] = identifier[len] ( identifier[shape_inputs] )
identifier[max_dim] = identifier[np] . ... | def _build(self, inputs):
"""Connects the SliceByDim module into the graph.
Args:
inputs: `Tensor` to slice. Its rank must be greater than the maximum
dimension specified in `dims` (plus one as python is 0 indexed).
Returns:
The sliced tensor.
Raises:
ValueError: If `input... |
def is_same_as(self, other):
"""Asserts that the val is identical to other, via 'is' compare."""
if self.val is not other:
self._err('Expected <%s> to be identical to <%s>, but was not.' % (self.val, other))
return self | def function[is_same_as, parameter[self, other]]:
constant[Asserts that the val is identical to other, via 'is' compare.]
if compare[name[self].val is_not name[other]] begin[:]
call[name[self]._err, parameter[binary_operation[constant[Expected <%s> to be identical to <%s>, but was not.] ... | keyword[def] identifier[is_same_as] ( identifier[self] , identifier[other] ):
literal[string]
keyword[if] identifier[self] . identifier[val] keyword[is] keyword[not] identifier[other] :
identifier[self] . identifier[_err] ( literal[string] %( identifier[self] . identifier[val] , id... | def is_same_as(self, other):
"""Asserts that the val is identical to other, via 'is' compare."""
if self.val is not other:
self._err('Expected <%s> to be identical to <%s>, but was not.' % (self.val, other)) # depends on [control=['if'], data=['other']]
return self |
def tag(self, tag, child='', enclose=0, newline=True, **kwargs):
"""
enclose:
0 => <tag>
1 => <tag/>
2 => <tag></tag>
"""
kw = kwargs.copy()
_class = ''
if '_class' in kw:
_class = kw.pop('_class')
if 'class' in kw:
... | def function[tag, parameter[self, tag, child, enclose, newline]]:
constant[
enclose:
0 => <tag>
1 => <tag/>
2 => <tag></tag>
]
variable[kw] assign[=] call[name[kwargs].copy, parameter[]]
variable[_class] assign[=] constant[]
if compare[... | keyword[def] identifier[tag] ( identifier[self] , identifier[tag] , identifier[child] = literal[string] , identifier[enclose] = literal[int] , identifier[newline] = keyword[True] ,** identifier[kwargs] ):
literal[string]
identifier[kw] = identifier[kwargs] . identifier[copy] ()
identifier[... | def tag(self, tag, child='', enclose=0, newline=True, **kwargs):
"""
enclose:
0 => <tag>
1 => <tag/>
2 => <tag></tag>
"""
kw = kwargs.copy()
_class = ''
if '_class' in kw:
_class = kw.pop('_class') # depends on [control=['if'], data=['kw']]
... |
def receiveds_parsing(receiveds):
"""
This function parses the receiveds headers.
Args:
receiveds (list): list of raw receiveds headers
Returns:
a list of parsed receiveds headers with first hop in first position
"""
parsed = []
receiveds = [re.sub(JUNK_PATTERN, " ", i).st... | def function[receiveds_parsing, parameter[receiveds]]:
constant[
This function parses the receiveds headers.
Args:
receiveds (list): list of raw receiveds headers
Returns:
a list of parsed receiveds headers with first hop in first position
]
variable[parsed] assign[=] l... | keyword[def] identifier[receiveds_parsing] ( identifier[receiveds] ):
literal[string]
identifier[parsed] =[]
identifier[receiveds] =[ identifier[re] . identifier[sub] ( identifier[JUNK_PATTERN] , literal[string] , identifier[i] ). identifier[strip] () keyword[for] identifier[i] keyword[in] identif... | def receiveds_parsing(receiveds):
"""
This function parses the receiveds headers.
Args:
receiveds (list): list of raw receiveds headers
Returns:
a list of parsed receiveds headers with first hop in first position
"""
parsed = []
receiveds = [re.sub(JUNK_PATTERN, ' ', i).str... |
def convert_string_value_to_type_value(string_value, data_type):
"""Helper function to convert a given string to a given data type
:param str string_value: the string to convert
:param type data_type: the target data type
:return: the converted value
"""
from ast import literal_eval
try:
... | def function[convert_string_value_to_type_value, parameter[string_value, data_type]]:
constant[Helper function to convert a given string to a given data type
:param str string_value: the string to convert
:param type data_type: the target data type
:return: the converted value
]
from relati... | keyword[def] identifier[convert_string_value_to_type_value] ( identifier[string_value] , identifier[data_type] ):
literal[string]
keyword[from] identifier[ast] keyword[import] identifier[literal_eval]
keyword[try] :
keyword[if] identifier[data_type] keyword[in] ( identifier[str] , iden... | def convert_string_value_to_type_value(string_value, data_type):
"""Helper function to convert a given string to a given data type
:param str string_value: the string to convert
:param type data_type: the target data type
:return: the converted value
"""
from ast import literal_eval
try:
... |
def load(self, filething):
"""Load tags from a filename.
Raises apev2.error
"""
data = _APEv2Data(filething.fileobj)
if data.tag:
self.clear()
self.__parse_tag(data.tag, data.items)
else:
raise APENoHeaderError("No APE tag found") | def function[load, parameter[self, filething]]:
constant[Load tags from a filename.
Raises apev2.error
]
variable[data] assign[=] call[name[_APEv2Data], parameter[name[filething].fileobj]]
if name[data].tag begin[:]
call[name[self].clear, parameter[]]
... | keyword[def] identifier[load] ( identifier[self] , identifier[filething] ):
literal[string]
identifier[data] = identifier[_APEv2Data] ( identifier[filething] . identifier[fileobj] )
keyword[if] identifier[data] . identifier[tag] :
identifier[self] . identifier[clear] ()
... | def load(self, filething):
"""Load tags from a filename.
Raises apev2.error
"""
data = _APEv2Data(filething.fileobj)
if data.tag:
self.clear()
self.__parse_tag(data.tag, data.items) # depends on [control=['if'], data=[]]
else:
raise APENoHeaderError('No APE tag ... |
def add_play(self, choice, count=1):
"""Increments the play count for a given experiment choice"""
self.redis.hincrby(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "%s:plays" % choice, count)
self._choices = None | def function[add_play, parameter[self, choice, count]]:
constant[Increments the play count for a given experiment choice]
call[name[self].redis.hincrby, parameter[binary_operation[name[EXPERIMENT_REDIS_KEY_TEMPLATE] <ast.Mod object at 0x7da2590d6920> name[self].name], binary_operation[constant[%s:plays]... | keyword[def] identifier[add_play] ( identifier[self] , identifier[choice] , identifier[count] = literal[int] ):
literal[string]
identifier[self] . identifier[redis] . identifier[hincrby] ( identifier[EXPERIMENT_REDIS_KEY_TEMPLATE] % identifier[self] . identifier[name] , literal[string] % identifier... | def add_play(self, choice, count=1):
"""Increments the play count for a given experiment choice"""
self.redis.hincrby(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, '%s:plays' % choice, count)
self._choices = None |
def discover_and_apply(self, directory=None, dry_run=False):
"""
Retrieve the patches and try to apply them against the datamodel
:param directory: Directory to search the patch in (default: patches_dir)
:param dry_run: Don't actually apply the patches
"""
directory = di... | def function[discover_and_apply, parameter[self, directory, dry_run]]:
constant[
Retrieve the patches and try to apply them against the datamodel
:param directory: Directory to search the patch in (default: patches_dir)
:param dry_run: Don't actually apply the patches
]
... | keyword[def] identifier[discover_and_apply] ( identifier[self] , identifier[directory] = keyword[None] , identifier[dry_run] = keyword[False] ):
literal[string]
identifier[directory] = identifier[directory] keyword[or] identifier[self] . identifier[patches_dir]
identifier[patches_dict] ... | def discover_and_apply(self, directory=None, dry_run=False):
"""
Retrieve the patches and try to apply them against the datamodel
:param directory: Directory to search the patch in (default: patches_dir)
:param dry_run: Don't actually apply the patches
"""
directory = directory ... |
def chart_type(self, value):
"""Set the MetricsGraphics chart type.
Allowed charts are: line, histogram, point, and bar
Args:
value (str): chart type.
Raises:
ValueError: Not a valid chart type.
"""
if value not in self._allow... | def function[chart_type, parameter[self, value]]:
constant[Set the MetricsGraphics chart type.
Allowed charts are: line, histogram, point, and bar
Args:
value (str): chart type.
Raises:
ValueError: Not a valid chart type.
]
if... | keyword[def] identifier[chart_type] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[value] keyword[not] keyword[in] identifier[self] . identifier[_allowed_charts] :
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[self... | def chart_type(self, value):
"""Set the MetricsGraphics chart type.
Allowed charts are: line, histogram, point, and bar
Args:
value (str): chart type.
Raises:
ValueError: Not a valid chart type.
"""
if value not in self._allowed_chart... |
def write(models, base=None, graph=None, rdfsonly=False, prefixes=None, logger=logging):
'''
See the command line help
'''
prefixes = prefixes or {}
g = graph or rdflib.Graph()
#g.bind('bf', BFNS)
#g.bind('bfc', BFCNS)
#g.bind('bfd', BFDNS)
g.bind('v', VNS)
for k, v in prefixes.i... | def function[write, parameter[models, base, graph, rdfsonly, prefixes, logger]]:
constant[
See the command line help
]
variable[prefixes] assign[=] <ast.BoolOp object at 0x7da204620850>
variable[g] assign[=] <ast.BoolOp object at 0x7da204623bb0>
call[name[g].bind, parameter[const... | keyword[def] identifier[write] ( identifier[models] , identifier[base] = keyword[None] , identifier[graph] = keyword[None] , identifier[rdfsonly] = keyword[False] , identifier[prefixes] = keyword[None] , identifier[logger] = identifier[logging] ):
literal[string]
identifier[prefixes] = identifier[prefixes]... | def write(models, base=None, graph=None, rdfsonly=False, prefixes=None, logger=logging):
"""
See the command line help
"""
prefixes = prefixes or {}
g = graph or rdflib.Graph()
#g.bind('bf', BFNS)
#g.bind('bfc', BFCNS)
#g.bind('bfd', BFDNS)
g.bind('v', VNS)
for (k, v) in prefixes... |
def row_coordinates(self, X):
"""Returns the row principal coordinates.
The row principal coordinates are obtained by projecting `X` on the right eigenvectors.
"""
utils.validation.check_is_fitted(self, 's_')
# Extract index
index = X.index if isinstance(X, pd.DataFrame... | def function[row_coordinates, parameter[self, X]]:
constant[Returns the row principal coordinates.
The row principal coordinates are obtained by projecting `X` on the right eigenvectors.
]
call[name[utils].validation.check_is_fitted, parameter[name[self], constant[s_]]]
variable... | keyword[def] identifier[row_coordinates] ( identifier[self] , identifier[X] ):
literal[string]
identifier[utils] . identifier[validation] . identifier[check_is_fitted] ( identifier[self] , literal[string] )
identifier[index] = identifier[X] . identifier[index] keyword[if] ident... | def row_coordinates(self, X):
"""Returns the row principal coordinates.
The row principal coordinates are obtained by projecting `X` on the right eigenvectors.
"""
utils.validation.check_is_fitted(self, 's_')
# Extract index
index = X.index if isinstance(X, pd.DataFrame) else None
#... |
def prepare_static_data(self, data):
"""
If user defined static fields, then process them with visiable value
"""
d = self.obj.to_dict()
d.update(data.copy())
for f in self.get_fields():
if f['static'] and f['name'] in d:
v = make_view_... | def function[prepare_static_data, parameter[self, data]]:
constant[
If user defined static fields, then process them with visiable value
]
variable[d] assign[=] call[name[self].obj.to_dict, parameter[]]
call[name[d].update, parameter[call[name[data].copy, parameter[]]]]
f... | keyword[def] identifier[prepare_static_data] ( identifier[self] , identifier[data] ):
literal[string]
identifier[d] = identifier[self] . identifier[obj] . identifier[to_dict] ()
identifier[d] . identifier[update] ( identifier[data] . identifier[copy] ())
keyword[for] identifi... | def prepare_static_data(self, data):
"""
If user defined static fields, then process them with visiable value
"""
d = self.obj.to_dict()
d.update(data.copy())
for f in self.get_fields():
if f['static'] and f['name'] in d:
v = make_view_field(f, self.obj, self.types_co... |
def getEdgePoints(self):
"""
Returns a list with the coordinates of the points at the edge of the rectangle as tuples.
e.g.[(x1,y1),(x2,y2)]
The sorting is counterclockwise starting with the lower left corner.
Coordinates must be numbers or an exception will be thrown.
""... | def function[getEdgePoints, parameter[self]]:
constant[
Returns a list with the coordinates of the points at the edge of the rectangle as tuples.
e.g.[(x1,y1),(x2,y2)]
The sorting is counterclockwise starting with the lower left corner.
Coordinates must be numbers or an exception... | keyword[def] identifier[getEdgePoints] ( identifier[self] ):
literal[string]
identifier[result] =[( identifier[float] ( identifier[self] . identifier[get_x] ()), identifier[float] ( identifier[self] . identifier[get_y] ()))]
identifier[result] . identifier[append] (( identifier[float] ( id... | def getEdgePoints(self):
"""
Returns a list with the coordinates of the points at the edge of the rectangle as tuples.
e.g.[(x1,y1),(x2,y2)]
The sorting is counterclockwise starting with the lower left corner.
Coordinates must be numbers or an exception will be thrown.
"""
... |
def _find_file(self, path, saltenv='base'):
'''
Locate the file path
'''
fnd = {'path': '',
'rel': ''}
if salt.utils.url.is_escaped(path):
# The path arguments are escaped
path = salt.utils.url.unescape(path)
for root in self.opts['... | def function[_find_file, parameter[self, path, saltenv]]:
constant[
Locate the file path
]
variable[fnd] assign[=] dictionary[[<ast.Constant object at 0x7da18f720400>, <ast.Constant object at 0x7da18f723130>], [<ast.Constant object at 0x7da18f723bb0>, <ast.Constant object at 0x7da18f721c... | keyword[def] identifier[_find_file] ( identifier[self] , identifier[path] , identifier[saltenv] = literal[string] ):
literal[string]
identifier[fnd] ={ literal[string] : literal[string] ,
literal[string] : literal[string] }
keyword[if] identifier[salt] . identifier[utils] . iden... | def _find_file(self, path, saltenv='base'):
"""
Locate the file path
"""
fnd = {'path': '', 'rel': ''}
if salt.utils.url.is_escaped(path):
# The path arguments are escaped
path = salt.utils.url.unescape(path) # depends on [control=['if'], data=[]]
for root in self.opts['... |
def store_zonefile_data( self, fetched_zfhash, zonefile_data, min_block_height, peer_hostport, con, path ):
"""
Store the fetched zonefile (as a serialized string) to storage and cache it locally.
Update internal state to mark it present
Return True on success
Return False on err... | def function[store_zonefile_data, parameter[self, fetched_zfhash, zonefile_data, min_block_height, peer_hostport, con, path]]:
constant[
Store the fetched zonefile (as a serialized string) to storage and cache it locally.
Update internal state to mark it present
Return True on success
... | keyword[def] identifier[store_zonefile_data] ( identifier[self] , identifier[fetched_zfhash] , identifier[zonefile_data] , identifier[min_block_height] , identifier[peer_hostport] , identifier[con] , identifier[path] ):
literal[string]
identifier[rc] = identifier[add_atlas_zonefile_data] ( identifi... | def store_zonefile_data(self, fetched_zfhash, zonefile_data, min_block_height, peer_hostport, con, path):
"""
Store the fetched zonefile (as a serialized string) to storage and cache it locally.
Update internal state to mark it present
Return True on success
Return False on error
... |
def allowed(self, **kwargs):
"""
Get all available sender settings which could be used in "from" parameter of POST messages method.
Returns :class:`Source` object.
:Example:
allowed = client.sources.allowed()
:param country: Return sender settings available in specifi... | def function[allowed, parameter[self]]:
constant[
Get all available sender settings which could be used in "from" parameter of POST messages method.
Returns :class:`Source` object.
:Example:
allowed = client.sources.allowed()
:param country: Return sender settings ava... | keyword[def] identifier[allowed] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[resp] , identifier[instance] = identifier[self] . identifier[request] ( literal[string] , identifier[self] . identifier[uri] , identifier[params] = identifier[kwargs] )
keyword[return] ... | def allowed(self, **kwargs):
"""
Get all available sender settings which could be used in "from" parameter of POST messages method.
Returns :class:`Source` object.
:Example:
allowed = client.sources.allowed()
:param country: Return sender settings available in specified c... |
def json(value,
schema = None,
allow_empty = False,
json_serializer = None,
**kwargs):
"""Validate that ``value`` conforms to the supplied JSON Schema.
.. note::
``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the
meta-schema using... | def function[json, parameter[value, schema, allow_empty, json_serializer]]:
constant[Validate that ``value`` conforms to the supplied JSON Schema.
.. note::
``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the
meta-schema using a ``$schema`` property, the schema w... | keyword[def] identifier[json] ( identifier[value] ,
identifier[schema] = keyword[None] ,
identifier[allow_empty] = keyword[False] ,
identifier[json_serializer] = keyword[None] ,
** identifier[kwargs] ):
literal[string]
identifier[original_value] = identifier[value]
identifier[original_schema] = id... | def json(value, schema=None, allow_empty=False, json_serializer=None, **kwargs):
"""Validate that ``value`` conforms to the supplied JSON Schema.
.. note::
``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the
meta-schema using a ``$schema`` property, the schema will b... |
def open_link(self, url):
"""
Open a media link using the definitions from the user's mailcap file.
Most urls are parsed using their file extension, but special cases
exist for websites that are prevalent on reddit such as Imgur and
Gfycat. If there are no valid mailcap definiti... | def function[open_link, parameter[self, url]]:
constant[
Open a media link using the definitions from the user's mailcap file.
Most urls are parsed using their file extension, but special cases
exist for websites that are prevalent on reddit such as Imgur and
Gfycat. If there ar... | keyword[def] identifier[open_link] ( identifier[self] , identifier[url] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[config] [ literal[string] ]:
identifier[self] . identifier[open_browser] ( identifier[url] )
keyword[return]
keyw... | def open_link(self, url):
"""
Open a media link using the definitions from the user's mailcap file.
Most urls are parsed using their file extension, but special cases
exist for websites that are prevalent on reddit such as Imgur and
Gfycat. If there are no valid mailcap definitions,... |
def execute(self, *args, **kwargs):
"""
Executes the action and returns the result.
You dont have to call this function directly as the class is callable (implements __call__)
you just call the @action marked function as normal.
@action
def my_actio... | def function[execute, parameter[self]]:
constant[
Executes the action and returns the result.
You dont have to call this function directly as the class is callable (implements __call__)
you just call the @action marked function as normal.
@action
de... | keyword[def] identifier[execute] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[timeout] = identifier[kwargs] . identifier[pop] ( literal[string] ,- literal[int] )
identifier[execute_async] = identifier[kwargs] . identifier[pop] ( literal[string... | def execute(self, *args, **kwargs):
"""
Executes the action and returns the result.
You dont have to call this function directly as the class is callable (implements __call__)
you just call the @action marked function as normal.
@action
def my_action(p1... |
def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return f... | def function[property_observer, parameter[self, name]]:
constant[Function decorator to register a property observer. See ``MPV.observe_property`` for details.]
def function[wrapper, parameter[fun]]:
call[name[self].observe_property, parameter[name[name], name[fun]]]
name[... | keyword[def] identifier[property_observer] ( identifier[self] , identifier[name] ):
literal[string]
keyword[def] identifier[wrapper] ( identifier[fun] ):
identifier[self] . identifier[observe_property] ( identifier[name] , identifier[fun] )
identifier[fun] . identifier[un... | def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda : self.unobserve_property(name, fun)
return fun
return wrap... |
def validate_unit(input_unit):
"""Validate unit.
To be compatible with existing SYNPHOT data files:
* 'angstroms' and 'inversemicrons' are accepted although
unrecognized by astropy units
* 'transmission', 'extinction', and 'emissivity' are
converted to astropy dimensionless... | def function[validate_unit, parameter[input_unit]]:
constant[Validate unit.
To be compatible with existing SYNPHOT data files:
* 'angstroms' and 'inversemicrons' are accepted although
unrecognized by astropy units
* 'transmission', 'extinction', and 'emissivity' are
con... | keyword[def] identifier[validate_unit] ( identifier[input_unit] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[input_unit] , identifier[str] ):
identifier[input_unit_lowcase] = identifier[input_unit] . identifier[lower] ()
keyword[if] identifier[input_unit_... | def validate_unit(input_unit):
"""Validate unit.
To be compatible with existing SYNPHOT data files:
* 'angstroms' and 'inversemicrons' are accepted although
unrecognized by astropy units
* 'transmission', 'extinction', and 'emissivity' are
converted to astropy dimensionless... |
def _loadfilepath(self, filepath, **kwargs):
"""This loads a geojson file into a geojson python
dictionary using the json module.
Note: to load with a different text encoding use the encoding argument.
"""
with open(filepath, "r") as f:
data = json.load(f, **... | def function[_loadfilepath, parameter[self, filepath]]:
constant[This loads a geojson file into a geojson python
dictionary using the json module.
Note: to load with a different text encoding use the encoding argument.
]
with call[name[open], parameter[name[filepath], co... | keyword[def] identifier[_loadfilepath] ( identifier[self] , identifier[filepath] ,** identifier[kwargs] ):
literal[string]
keyword[with] identifier[open] ( identifier[filepath] , literal[string] ) keyword[as] identifier[f] :
identifier[data] = identifier[json] . identifier[load] ( id... | def _loadfilepath(self, filepath, **kwargs):
"""This loads a geojson file into a geojson python
dictionary using the json module.
Note: to load with a different text encoding use the encoding argument.
"""
with open(filepath, 'r') as f:
data = json.load(f, **kwargs) # d... |
def updateSolutionTerminal(self):
'''
Update the terminal period solution. This method should be run when a
new AgentType is created or when CRRA changes.
Parameters
----------
None
Returns
-------
None
'''
self.solution_terminal... | def function[updateSolutionTerminal, parameter[self]]:
constant[
Update the terminal period solution. This method should be run when a
new AgentType is created or when CRRA changes.
Parameters
----------
None
Returns
-------
None
]
... | keyword[def] identifier[updateSolutionTerminal] ( identifier[self] ):
literal[string]
identifier[self] . identifier[solution_terminal] . identifier[vFunc] = identifier[ValueFunc2D] ( identifier[self] . identifier[cFunc_terminal_] , identifier[self] . identifier[CRRA] )
identifier[self] . i... | def updateSolutionTerminal(self):
"""
Update the terminal period solution. This method should be run when a
new AgentType is created or when CRRA changes.
Parameters
----------
None
Returns
-------
None
"""
self.solution_terminal.vFunc =... |
def read_csv(self, dtype=False, parse_dates=True, *args, **kwargs):
"""Fetch the target and pass through to pandas.read_csv
Don't provide the first argument of read_csv(); it is supplied internally.
"""
import pandas
t = self.resolved_url.get_resource().get_target()
k... | def function[read_csv, parameter[self, dtype, parse_dates]]:
constant[Fetch the target and pass through to pandas.read_csv
Don't provide the first argument of read_csv(); it is supplied internally.
]
import module[pandas]
variable[t] assign[=] call[call[name[self].resolved_url.get_r... | keyword[def] identifier[read_csv] ( identifier[self] , identifier[dtype] = keyword[False] , identifier[parse_dates] = keyword[True] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[import] identifier[pandas]
identifier[t] = identifier[self] . identifier[resolved_ur... | def read_csv(self, dtype=False, parse_dates=True, *args, **kwargs):
"""Fetch the target and pass through to pandas.read_csv
Don't provide the first argument of read_csv(); it is supplied internally.
"""
import pandas
t = self.resolved_url.get_resource().get_target()
kwargs = self._updat... |
def _raise_for_status(response):
""" make sure that only crate.exceptions are raised that are defined in
the DB-API specification """
message = ''
if 400 <= response.status < 500:
message = '%s Client Error: %s' % (response.status, response.reason)
elif 500 <= response.status < 600:
... | def function[_raise_for_status, parameter[response]]:
constant[ make sure that only crate.exceptions are raised that are defined in
the DB-API specification ]
variable[message] assign[=] constant[]
if compare[constant[400] less_or_equal[<=] name[response].status] begin[:]
var... | keyword[def] identifier[_raise_for_status] ( identifier[response] ):
literal[string]
identifier[message] = literal[string]
keyword[if] literal[int] <= identifier[response] . identifier[status] < literal[int] :
identifier[message] = literal[string] %( identifier[response] . identifier[status... | def _raise_for_status(response):
""" make sure that only crate.exceptions are raised that are defined in
the DB-API specification """
message = ''
if 400 <= response.status < 500:
message = '%s Client Error: %s' % (response.status, response.reason) # depends on [control=['if'], data=[]]
eli... |
def set_sort_order(self, sort_order):
"""
Use the SortOrder object to sort the listings descending or ascending.
:param sort_order:
:return:
"""
if not isinstance(sort_order, SortOrder):
raise DaftException("sort_order should be an instance of SortOrder.")
... | def function[set_sort_order, parameter[self, sort_order]]:
constant[
Use the SortOrder object to sort the listings descending or ascending.
:param sort_order:
:return:
]
if <ast.UnaryOp object at 0x7da2044c18a0> begin[:]
<ast.Raise object at 0x7da1b06251e0>
... | keyword[def] identifier[set_sort_order] ( identifier[self] , identifier[sort_order] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[sort_order] , identifier[SortOrder] ):
keyword[raise] identifier[DaftException] ( literal[string] )
identifi... | def set_sort_order(self, sort_order):
"""
Use the SortOrder object to sort the listings descending or ascending.
:param sort_order:
:return:
"""
if not isinstance(sort_order, SortOrder):
raise DaftException('sort_order should be an instance of SortOrder.') # depends on [... |
async def list(self) -> List[str]:
"""
Return list of pool names configured, empty list for none.
:return: list of pool names.
"""
LOGGER.debug('NodePoolManager.list >>>')
rv = [p['pool'] for p in await pool.list_pools()]
LOGGER.debug('NodePoolManager.list <<<... | <ast.AsyncFunctionDef object at 0x7da20c6c4d00> | keyword[async] keyword[def] identifier[list] ( identifier[self] )-> identifier[List] [ identifier[str] ]:
literal[string]
identifier[LOGGER] . identifier[debug] ( literal[string] )
identifier[rv] =[ identifier[p] [ literal[string] ] keyword[for] identifier[p] keyword[in] keyword[awai... | async def list(self) -> List[str]:
"""
Return list of pool names configured, empty list for none.
:return: list of pool names.
"""
LOGGER.debug('NodePoolManager.list >>>')
rv = [p['pool'] for p in await pool.list_pools()]
LOGGER.debug('NodePoolManager.list <<< %s', rv)
retur... |
def get_model(self):
"""
Get a model if the formula was previously satisfied.
"""
if self.minisat and self.status == True:
model = pysolvers.minisat22_model(self.minisat)
return model if model != None else [] | def function[get_model, parameter[self]]:
constant[
Get a model if the formula was previously satisfied.
]
if <ast.BoolOp object at 0x7da1b128add0> begin[:]
variable[model] assign[=] call[name[pysolvers].minisat22_model, parameter[name[self].minisat]]
return[<... | keyword[def] identifier[get_model] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[minisat] keyword[and] identifier[self] . identifier[status] == keyword[True] :
identifier[model] = identifier[pysolvers] . identifier[minisat22_model] ( identifier[sel... | def get_model(self):
"""
Get a model if the formula was previously satisfied.
"""
if self.minisat and self.status == True:
model = pysolvers.minisat22_model(self.minisat)
return model if model != None else [] # depends on [control=['if'], data=[]] |
def center_of_mass(self, scalars_weight=False):
"""
Returns the coordinates for the center of mass of the mesh.
Parameters
----------
scalars_weight : bool, optional
Flag for using the mesh scalars as weights. Defaults to False.
Return
------
... | def function[center_of_mass, parameter[self, scalars_weight]]:
constant[
Returns the coordinates for the center of mass of the mesh.
Parameters
----------
scalars_weight : bool, optional
Flag for using the mesh scalars as weights. Defaults to False.
Return
... | keyword[def] identifier[center_of_mass] ( identifier[self] , identifier[scalars_weight] = keyword[False] ):
literal[string]
identifier[comfilter] = identifier[vtk] . identifier[vtkCenterOfMass] ()
identifier[comfilter] . identifier[SetInputData] ( identifier[self] )
identifier[com... | def center_of_mass(self, scalars_weight=False):
"""
Returns the coordinates for the center of mass of the mesh.
Parameters
----------
scalars_weight : bool, optional
Flag for using the mesh scalars as weights. Defaults to False.
Return
------
cen... |
def sqrt(self):
"""square root operation
Returns
-------
Matrix : Matrix
square root of self
"""
if self.isdiagonal:
return type(self)(x=np.sqrt(self.__x), isdiagonal=True,
row_names=self.row_names,
... | def function[sqrt, parameter[self]]:
constant[square root operation
Returns
-------
Matrix : Matrix
square root of self
]
if name[self].isdiagonal begin[:]
return[call[call[name[type], parameter[name[self]]], parameter[]]] | keyword[def] identifier[sqrt] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[isdiagonal] :
keyword[return] identifier[type] ( identifier[self] )( identifier[x] = identifier[np] . identifier[sqrt] ( identifier[self] . identifier[__x] ), identifier[isdi... | def sqrt(self):
"""square root operation
Returns
-------
Matrix : Matrix
square root of self
"""
if self.isdiagonal:
return type(self)(x=np.sqrt(self.__x), isdiagonal=True, row_names=self.row_names, col_names=self.col_names, autoalign=self.autoalign) # depe... |
def get(self):
""" get method """
try:
cluster = self.get_argument_cluster()
role = self.get_argument_role()
environ = self.get_argument_environ()
topology_name = self.get_argument_topology()
topology = self.tracker.getTopologyByClusterRoleEnvironAndName(
cluster, role, ... | def function[get, parameter[self]]:
constant[ get method ]
<ast.Try object at 0x7da18ede7160> | keyword[def] identifier[get] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[cluster] = identifier[self] . identifier[get_argument_cluster] ()
identifier[role] = identifier[self] . identifier[get_argument_role] ()
identifier[environ] = identifier[self] . identifier[get... | def get(self):
""" get method """
try:
cluster = self.get_argument_cluster()
role = self.get_argument_role()
environ = self.get_argument_environ()
topology_name = self.get_argument_topology()
topology = self.tracker.getTopologyByClusterRoleEnvironAndName(cluster, role, en... |
def async_save_result(self):
"""
Retrieves the result of this subject's asynchronous save.
- Returns `True` if the subject was saved successfully.
- Raises `concurrent.futures.CancelledError` if the save was cancelled.
- If the save failed, raises the relevant exception.
... | def function[async_save_result, parameter[self]]:
constant[
Retrieves the result of this subject's asynchronous save.
- Returns `True` if the subject was saved successfully.
- Raises `concurrent.futures.CancelledError` if the save was cancelled.
- If the save failed, raises the ... | keyword[def] identifier[async_save_result] ( identifier[self] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ) keyword[and] identifier[self] . identifier[_async_future] . identifier[done] ():
identifier[self] . identifier[_async_future] . iden... | def async_save_result(self):
"""
Retrieves the result of this subject's asynchronous save.
- Returns `True` if the subject was saved successfully.
- Raises `concurrent.futures.CancelledError` if the save was cancelled.
- If the save failed, raises the relevant exception.
- R... |
def delete(self, file_id):
"""Given an file_id, delete this stored file's files collection document
and associated chunks from a GridFS bucket.
For example::
my_db = MongoClient().test
fs = GridFSBucket(my_db)
# Get _id of file to delete
file_id = fs.upl... | def function[delete, parameter[self, file_id]]:
constant[Given an file_id, delete this stored file's files collection document
and associated chunks from a GridFS bucket.
For example::
my_db = MongoClient().test
fs = GridFSBucket(my_db)
# Get _id of file to delete... | keyword[def] identifier[delete] ( identifier[self] , identifier[file_id] ):
literal[string]
identifier[res] = identifier[self] . identifier[_files] . identifier[delete_one] ({ literal[string] : identifier[file_id] })
identifier[self] . identifier[_chunks] . identifier[delete_many] ({ liter... | def delete(self, file_id):
"""Given an file_id, delete this stored file's files collection document
and associated chunks from a GridFS bucket.
For example::
my_db = MongoClient().test
fs = GridFSBucket(my_db)
# Get _id of file to delete
file_id = fs.upload_... |
def try_open (*args, **kwargs):
"""Simply a wrapper for io.open(), unless an IOError with errno=2 (ENOENT) is
raised, in which case None is retured.
"""
try:
return io.open (*args, **kwargs)
except IOError as e:
if e.errno == 2:
return None
raise | def function[try_open, parameter[]]:
constant[Simply a wrapper for io.open(), unless an IOError with errno=2 (ENOENT) is
raised, in which case None is retured.
]
<ast.Try object at 0x7da1b26b7370> | keyword[def] identifier[try_open] (* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
keyword[return] identifier[io] . identifier[open] (* identifier[args] ,** identifier[kwargs] )
keyword[except] identifier[IOError] keyword[as] identifier[e] :
keyword[if... | def try_open(*args, **kwargs):
"""Simply a wrapper for io.open(), unless an IOError with errno=2 (ENOENT) is
raised, in which case None is retured.
"""
try:
return io.open(*args, **kwargs) # depends on [control=['try'], data=[]]
except IOError as e:
if e.errno == 2:
ret... |
def make_interactive_tree(matrix=None,labels=None):
'''make interactive tree will return complete html for an interactive tree
:param title: a title for the plot, if not defined, will be left out.
'''
from scipy.cluster.hierarchy import (
dendrogram,
linkage,
to_tree
)
... | def function[make_interactive_tree, parameter[matrix, labels]]:
constant[make interactive tree will return complete html for an interactive tree
:param title: a title for the plot, if not defined, will be left out.
]
from relative_module[scipy.cluster.hierarchy] import module[dendrogram], module[lin... | keyword[def] identifier[make_interactive_tree] ( identifier[matrix] = keyword[None] , identifier[labels] = keyword[None] ):
literal[string]
keyword[from] identifier[scipy] . identifier[cluster] . identifier[hierarchy] keyword[import] (
identifier[dendrogram] ,
identifier[linkage] ,
identif... | def make_interactive_tree(matrix=None, labels=None):
"""make interactive tree will return complete html for an interactive tree
:param title: a title for the plot, if not defined, will be left out.
"""
from scipy.cluster.hierarchy import dendrogram, linkage, to_tree
d3 = None
from scipy.cluster.... |
def battery_percent(self):
"""Get batteries capacity percent."""
if not batinfo_tag or not self.bat.stat:
return []
# Init the bsum (sum of percent)
# and Loop over batteries (yes a computer could have more than 1 battery)
bsum = 0
for b in self.bat.stat:
... | def function[battery_percent, parameter[self]]:
constant[Get batteries capacity percent.]
if <ast.BoolOp object at 0x7da207f03be0> begin[:]
return[list[[]]]
variable[bsum] assign[=] constant[0]
for taget[name[b]] in starred[name[self].bat.stat] begin[:]
<ast.Try object at... | keyword[def] identifier[battery_percent] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[batinfo_tag] keyword[or] keyword[not] identifier[self] . identifier[bat] . identifier[stat] :
keyword[return] []
identifier[bsum] ... | def battery_percent(self):
"""Get batteries capacity percent."""
if not batinfo_tag or not self.bat.stat:
return [] # depends on [control=['if'], data=[]]
# Init the bsum (sum of percent)
# and Loop over batteries (yes a computer could have more than 1 battery)
bsum = 0
for b in self.ba... |
def _load_file(self, filename):
"""Load a vtkMultiBlockDataSet from a file (extension ``.vtm`` or
``.vtmb``)
"""
filename = os.path.abspath(os.path.expanduser(filename))
# test if file exists
if not os.path.isfile(filename):
raise Exception('File %s does not e... | def function[_load_file, parameter[self, filename]]:
constant[Load a vtkMultiBlockDataSet from a file (extension ``.vtm`` or
``.vtmb``)
]
variable[filename] assign[=] call[name[os].path.abspath, parameter[call[name[os].path.expanduser, parameter[name[filename]]]]]
if <ast.UnaryOp... | keyword[def] identifier[_load_file] ( identifier[self] , identifier[filename] ):
literal[string]
identifier[filename] = identifier[os] . identifier[path] . identifier[abspath] ( identifier[os] . identifier[path] . identifier[expanduser] ( identifier[filename] ))
keyword[if] keywo... | def _load_file(self, filename):
"""Load a vtkMultiBlockDataSet from a file (extension ``.vtm`` or
``.vtmb``)
"""
filename = os.path.abspath(os.path.expanduser(filename))
# test if file exists
if not os.path.isfile(filename):
raise Exception('File %s does not exist' % filename) #... |
def profile_validation(self, status):
"""Return run total value."""
self.selected_profile.data.setdefault('validation_pass_count', 0)
self.selected_profile.data.setdefault('validation_fail_count', 0)
if status:
self.selected_profile.data['validation_pass_count'] += 1
... | def function[profile_validation, parameter[self, status]]:
constant[Return run total value.]
call[name[self].selected_profile.data.setdefault, parameter[constant[validation_pass_count], constant[0]]]
call[name[self].selected_profile.data.setdefault, parameter[constant[validation_fail_count], con... | keyword[def] identifier[profile_validation] ( identifier[self] , identifier[status] ):
literal[string]
identifier[self] . identifier[selected_profile] . identifier[data] . identifier[setdefault] ( literal[string] , literal[int] )
identifier[self] . identifier[selected_profile] . identifier... | def profile_validation(self, status):
"""Return run total value."""
self.selected_profile.data.setdefault('validation_pass_count', 0)
self.selected_profile.data.setdefault('validation_fail_count', 0)
if status:
self.selected_profile.data['validation_pass_count'] += 1 # depends on [control=['if'... |
def set_longest_orf(self, feature_id, organism=None, sequence=None):
"""
Automatically pick the longest ORF in a feature
:type feature_id: str
:param feature_id: Feature UUID
:type organism: str
:param organism: Organism Common Name
:type sequence: str
... | def function[set_longest_orf, parameter[self, feature_id, organism, sequence]]:
constant[
Automatically pick the longest ORF in a feature
:type feature_id: str
:param feature_id: Feature UUID
:type organism: str
:param organism: Organism Common Name
:type seque... | keyword[def] identifier[set_longest_orf] ( identifier[self] , identifier[feature_id] , identifier[organism] = keyword[None] , identifier[sequence] = keyword[None] ):
literal[string]
identifier[data] ={
literal[string] :[
{
literal[string] : identifier[feature_id] ,
... | def set_longest_orf(self, feature_id, organism=None, sequence=None):
"""
Automatically pick the longest ORF in a feature
:type feature_id: str
:param feature_id: Feature UUID
:type organism: str
:param organism: Organism Common Name
:type sequence: str
:par... |
def calc_translations_parallel(images):
"""Calculate image translations in parallel.
Parameters
----------
images : ImageCollection
Images as instance of ImageCollection.
Returns
-------
2d array, (ty, tx)
ty and tx is translation to previous image in respectively
x... | def function[calc_translations_parallel, parameter[images]]:
constant[Calculate image translations in parallel.
Parameters
----------
images : ImageCollection
Images as instance of ImageCollection.
Returns
-------
2d array, (ty, tx)
ty and tx is translation to previous ... | keyword[def] identifier[calc_translations_parallel] ( identifier[images] ):
literal[string]
identifier[w] = identifier[Parallel] ( identifier[n_jobs] = identifier[_CPUS] )
identifier[res] = identifier[w] ( identifier[delayed] ( identifier[images] . identifier[translation] )( identifier[img] ) keyword[... | def calc_translations_parallel(images):
"""Calculate image translations in parallel.
Parameters
----------
images : ImageCollection
Images as instance of ImageCollection.
Returns
-------
2d array, (ty, tx)
ty and tx is translation to previous image in respectively
x... |
def delete(self, instance, disconnect=True):
'''
Delete an *instance* from the instance pool and optionally *disconnect*
it from any links it might be connected to. If the *instance* is not
part of the metaclass, a *MetaException* is thrown.
'''
if instance in self.storag... | def function[delete, parameter[self, instance, disconnect]]:
constant[
Delete an *instance* from the instance pool and optionally *disconnect*
it from any links it might be connected to. If the *instance* is not
part of the metaclass, a *MetaException* is thrown.
]
if com... | keyword[def] identifier[delete] ( identifier[self] , identifier[instance] , identifier[disconnect] = keyword[True] ):
literal[string]
keyword[if] identifier[instance] keyword[in] identifier[self] . identifier[storage] :
identifier[self] . identifier[storage] . identifier[remove] ( i... | def delete(self, instance, disconnect=True):
"""
Delete an *instance* from the instance pool and optionally *disconnect*
it from any links it might be connected to. If the *instance* is not
part of the metaclass, a *MetaException* is thrown.
"""
if instance in self.storage:
... |
def hide_dataset(dataset_id, exceptions, read, write, share,**kwargs):
"""
Hide a particular piece of data so it can only be seen by its owner.
Only an owner can hide (and unhide) data.
Data with no owner cannot be hidden.
The exceptions paramater lists the usernames of those with p... | def function[hide_dataset, parameter[dataset_id, exceptions, read, write, share]]:
constant[
Hide a particular piece of data so it can only be seen by its owner.
Only an owner can hide (and unhide) data.
Data with no owner cannot be hidden.
The exceptions paramater lists the use... | keyword[def] identifier[hide_dataset] ( identifier[dataset_id] , identifier[exceptions] , identifier[read] , identifier[write] , identifier[share] ,** identifier[kwargs] ):
literal[string]
identifier[user_id] = identifier[kwargs] . identifier[get] ( literal[string] )
identifier[dataset_i] = identifie... | def hide_dataset(dataset_id, exceptions, read, write, share, **kwargs):
"""
Hide a particular piece of data so it can only be seen by its owner.
Only an owner can hide (and unhide) data.
Data with no owner cannot be hidden.
The exceptions paramater lists the usernames of those with ... |
def status(name, maximum=None, minimum=None, absolute=False, free=False):
'''
Return the current disk usage stats for the named mount point
name
Disk mount or directory for which to check used space
maximum
The maximum disk utilization
minimum
The minimum disk utilization
... | def function[status, parameter[name, maximum, minimum, absolute, free]]:
constant[
Return the current disk usage stats for the named mount point
name
Disk mount or directory for which to check used space
maximum
The maximum disk utilization
minimum
The minimum disk uti... | keyword[def] identifier[status] ( identifier[name] , identifier[maximum] = keyword[None] , identifier[minimum] = keyword[None] , identifier[absolute] = keyword[False] , identifier[free] = keyword[False] ):
literal[string]
identifier[ret] ={ literal[string] : identifier[name] ,
literal[string] : k... | def status(name, maximum=None, minimum=None, absolute=False, free=False):
"""
Return the current disk usage stats for the named mount point
name
Disk mount or directory for which to check used space
maximum
The maximum disk utilization
minimum
The minimum disk utilization
... |
def insert_psd_option_group_multi_ifo(parser):
"""
Adds the options used to call the pycbc.psd.from_cli function to an
optparser as an OptionGroup. This should be used if you
want to use these options in your code.
Parameters
-----------
parser : object
OptionParser instance.
""... | def function[insert_psd_option_group_multi_ifo, parameter[parser]]:
constant[
Adds the options used to call the pycbc.psd.from_cli function to an
optparser as an OptionGroup. This should be used if you
want to use these options in your code.
Parameters
-----------
parser : object
... | keyword[def] identifier[insert_psd_option_group_multi_ifo] ( identifier[parser] ):
literal[string]
identifier[psd_options] = identifier[parser] . identifier[add_argument_group] (
literal[string] ,
literal[string]
literal[string] )
identifier[psd_options] . identifier[add_argument] ( li... | def insert_psd_option_group_multi_ifo(parser):
"""
Adds the options used to call the pycbc.psd.from_cli function to an
optparser as an OptionGroup. This should be used if you
want to use these options in your code.
Parameters
-----------
parser : object
OptionParser instance.
""... |
def from_node(index, value):
"""
>>> h = TimelineHistory.from_node(1, 2)
>>> h.lines
[]
"""
try:
lines = json.loads(value)
except (TypeError, ValueError):
lines = None
if not isinstance(lines, list):
lines = []
r... | def function[from_node, parameter[index, value]]:
constant[
>>> h = TimelineHistory.from_node(1, 2)
>>> h.lines
[]
]
<ast.Try object at 0x7da1b216f2e0>
if <ast.UnaryOp object at 0x7da1b216f070> begin[:]
variable[lines] assign[=] list[[]]
return[cal... | keyword[def] identifier[from_node] ( identifier[index] , identifier[value] ):
literal[string]
keyword[try] :
identifier[lines] = identifier[json] . identifier[loads] ( identifier[value] )
keyword[except] ( identifier[TypeError] , identifier[ValueError] ):
identifi... | def from_node(index, value):
"""
>>> h = TimelineHistory.from_node(1, 2)
>>> h.lines
[]
"""
try:
lines = json.loads(value) # depends on [control=['try'], data=[]]
except (TypeError, ValueError):
lines = None # depends on [control=['except'], data=[]]
if ... |
def extend(self, protocol: Union[Iterable[Dict], 'Pipeline']) -> 'Pipeline':
"""Add another pipeline to the end of the current pipeline.
:param protocol: An iterable of dictionaries (or another Pipeline)
:return: This pipeline for fluid query building
Example:
>>> p1 = Pipelin... | def function[extend, parameter[self, protocol]]:
constant[Add another pipeline to the end of the current pipeline.
:param protocol: An iterable of dictionaries (or another Pipeline)
:return: This pipeline for fluid query building
Example:
>>> p1 = Pipeline.from_functions(['enr... | keyword[def] identifier[extend] ( identifier[self] , identifier[protocol] : identifier[Union] [ identifier[Iterable] [ identifier[Dict] ], literal[string] ])-> literal[string] :
literal[string]
keyword[for] identifier[data] keyword[in] identifier[protocol] :
identifier[name] , ident... | def extend(self, protocol: Union[Iterable[Dict], 'Pipeline']) -> 'Pipeline':
"""Add another pipeline to the end of the current pipeline.
:param protocol: An iterable of dictionaries (or another Pipeline)
:return: This pipeline for fluid query building
Example:
>>> p1 = Pipeline.fr... |
def get_sns_topic_arn(topic_name, account, region):
"""Get SNS topic ARN.
Args:
topic_name (str): Name of the topic to lookup.
account (str): Environment, e.g. dev
region (str): Region name, e.g. us-east-1
Returns:
str: ARN for requested topic name
"""
if topic_nam... | def function[get_sns_topic_arn, parameter[topic_name, account, region]]:
constant[Get SNS topic ARN.
Args:
topic_name (str): Name of the topic to lookup.
account (str): Environment, e.g. dev
region (str): Region name, e.g. us-east-1
Returns:
str: ARN for requested topic... | keyword[def] identifier[get_sns_topic_arn] ( identifier[topic_name] , identifier[account] , identifier[region] ):
literal[string]
keyword[if] identifier[topic_name] . identifier[count] ( literal[string] )== literal[int] keyword[and] identifier[topic_name] . identifier[startswith] ( literal[string] ):
... | def get_sns_topic_arn(topic_name, account, region):
"""Get SNS topic ARN.
Args:
topic_name (str): Name of the topic to lookup.
account (str): Environment, e.g. dev
region (str): Region name, e.g. us-east-1
Returns:
str: ARN for requested topic name
"""
if topic_nam... |
def set_back(self, x: int, y: int, r: int, g: int, b: int) -> None:
"""Set the background color of one cell.
Args:
x (int): X position to change.
y (int): Y position to change.
r (int): Red background color, from 0 to 255.
g (int): Green background color,... | def function[set_back, parameter[self, x, y, r, g, b]]:
constant[Set the background color of one cell.
Args:
x (int): X position to change.
y (int): Y position to change.
r (int): Red background color, from 0 to 255.
g (int): Green background color, from ... | keyword[def] identifier[set_back] ( identifier[self] , identifier[x] : identifier[int] , identifier[y] : identifier[int] , identifier[r] : identifier[int] , identifier[g] : identifier[int] , identifier[b] : identifier[int] )-> keyword[None] :
literal[string]
identifier[i] = identifier[self] . ident... | def set_back(self, x: int, y: int, r: int, g: int, b: int) -> None:
"""Set the background color of one cell.
Args:
x (int): X position to change.
y (int): Y position to change.
r (int): Red background color, from 0 to 255.
g (int): Green background color, fro... |
async def umount(self):
"""Unmount this partition."""
self._data = await self._handler.unmount(
system_id=self.block_device.node.system_id,
device_id=self.block_device.id, id=self.id) | <ast.AsyncFunctionDef object at 0x7da1b26ae650> | keyword[async] keyword[def] identifier[umount] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_data] = keyword[await] identifier[self] . identifier[_handler] . identifier[unmount] (
identifier[system_id] = identifier[self] . identifier[block_device] . identifier[node... | async def umount(self):
"""Unmount this partition."""
self._data = await self._handler.unmount(system_id=self.block_device.node.system_id, device_id=self.block_device.id, id=self.id) |
def training(self, is_training=True):
'''
Set this layer in the training mode or in predition mode if is_training=False
'''
if is_training:
callJavaFunc(self.value.training)
else:
callJavaFunc(self.value.evaluate)
return self | def function[training, parameter[self, is_training]]:
constant[
Set this layer in the training mode or in predition mode if is_training=False
]
if name[is_training] begin[:]
call[name[callJavaFunc], parameter[name[self].value.training]]
return[name[self]] | keyword[def] identifier[training] ( identifier[self] , identifier[is_training] = keyword[True] ):
literal[string]
keyword[if] identifier[is_training] :
identifier[callJavaFunc] ( identifier[self] . identifier[value] . identifier[training] )
keyword[else] :
identi... | def training(self, is_training=True):
"""
Set this layer in the training mode or in predition mode if is_training=False
"""
if is_training:
callJavaFunc(self.value.training) # depends on [control=['if'], data=[]]
else:
callJavaFunc(self.value.evaluate)
return self |
def load_feather(protein_feather, length_filter_pid=None, copynum_scale=False, copynum_df=None):
"""Load a feather of amino acid counts for a protein.
Args:
protein_feather (str): path to feather file
copynum_scale (bool): if counts should be multiplied by protein copy number
copynum_df... | def function[load_feather, parameter[protein_feather, length_filter_pid, copynum_scale, copynum_df]]:
constant[Load a feather of amino acid counts for a protein.
Args:
protein_feather (str): path to feather file
copynum_scale (bool): if counts should be multiplied by protein copy number
... | keyword[def] identifier[load_feather] ( identifier[protein_feather] , identifier[length_filter_pid] = keyword[None] , identifier[copynum_scale] = keyword[False] , identifier[copynum_df] = keyword[None] ):
literal[string]
identifier[protein_df] = identifier[pd] . identifier[read_feather] ( identifier[protei... | def load_feather(protein_feather, length_filter_pid=None, copynum_scale=False, copynum_df=None):
"""Load a feather of amino acid counts for a protein.
Args:
protein_feather (str): path to feather file
copynum_scale (bool): if counts should be multiplied by protein copy number
copynum_df... |
def get_all_suppliers(self, params=None):
"""
Get all suppliers
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list
"""
i... | def function[get_all_suppliers, parameter[self, params]]:
constant[
Get all suppliers
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list... | keyword[def] identifier[get_all_suppliers] ( identifier[self] , identifier[params] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[params] :
identifier[params] ={}
keyword[return] identifier[self] . identifier[_iterate_through_pages] (
identi... | def get_all_suppliers(self, params=None):
"""
Get all suppliers
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list
"""
if not pa... |
def _format_trace(trace):
"""
Convert the (stripped) stack-trace to a nice readable format. The stack
trace `trace` is a list of frame records as returned by
**inspect.stack** but without the frame objects.
Returns a string.
"""
lines = []
for fname, lineno, func, src, _ in trace:
... | def function[_format_trace, parameter[trace]]:
constant[
Convert the (stripped) stack-trace to a nice readable format. The stack
trace `trace` is a list of frame records as returned by
**inspect.stack** but without the frame objects.
Returns a string.
]
variable[lines] assign[=] list... | keyword[def] identifier[_format_trace] ( identifier[trace] ):
literal[string]
identifier[lines] =[]
keyword[for] identifier[fname] , identifier[lineno] , identifier[func] , identifier[src] , identifier[_] keyword[in] identifier[trace] :
keyword[if] identifier[src] :
keyword[f... | def _format_trace(trace):
"""
Convert the (stripped) stack-trace to a nice readable format. The stack
trace `trace` is a list of frame records as returned by
**inspect.stack** but without the frame objects.
Returns a string.
"""
lines = []
for (fname, lineno, func, src, _) in trace:
... |
def sys_status_send(self, onboard_control_sensors_present, onboard_control_sensors_enabled, onboard_control_sensors_health, load, voltage_battery, current_battery, battery_remaining, drop_rate_comm, errors_comm, errors_count1, errors_count2, errors_count3, errors_count4, force_mavlink1=False):
'''
... | def function[sys_status_send, parameter[self, onboard_control_sensors_present, onboard_control_sensors_enabled, onboard_control_sensors_health, load, voltage_battery, current_battery, battery_remaining, drop_rate_comm, errors_comm, errors_count1, errors_count2, errors_count3, errors_count4, force_mavlink1]]:
co... | keyword[def] identifier[sys_status_send] ( identifier[self] , identifier[onboard_control_sensors_present] , identifier[onboard_control_sensors_enabled] , identifier[onboard_control_sensors_health] , identifier[load] , identifier[voltage_battery] , identifier[current_battery] , identifier[battery_remaining] , identifi... | def sys_status_send(self, onboard_control_sensors_present, onboard_control_sensors_enabled, onboard_control_sensors_health, load, voltage_battery, current_battery, battery_remaining, drop_rate_comm, errors_comm, errors_count1, errors_count2, errors_count3, errors_count4, force_mavlink1=False):
"""
T... |
def _generic_placeobject_parser(self, obj, version):
"""A generic parser for several PlaceObjectX."""
bc = BitConsumer(self._src)
obj.PlaceFlagHasClipActions = bc.u_get(1)
obj.PlaceFlagHasClipDepth = bc.u_get(1)
obj.PlaceFlagHasName = bc.u_get(1)
obj.PlaceFlagHasRatio = b... | def function[_generic_placeobject_parser, parameter[self, obj, version]]:
constant[A generic parser for several PlaceObjectX.]
variable[bc] assign[=] call[name[BitConsumer], parameter[name[self]._src]]
name[obj].PlaceFlagHasClipActions assign[=] call[name[bc].u_get, parameter[constant[1]]]
... | keyword[def] identifier[_generic_placeobject_parser] ( identifier[self] , identifier[obj] , identifier[version] ):
literal[string]
identifier[bc] = identifier[BitConsumer] ( identifier[self] . identifier[_src] )
identifier[obj] . identifier[PlaceFlagHasClipActions] = identifier[bc] . ident... | def _generic_placeobject_parser(self, obj, version):
"""A generic parser for several PlaceObjectX."""
bc = BitConsumer(self._src)
obj.PlaceFlagHasClipActions = bc.u_get(1)
obj.PlaceFlagHasClipDepth = bc.u_get(1)
obj.PlaceFlagHasName = bc.u_get(1)
obj.PlaceFlagHasRatio = bc.u_get(1)
obj.Place... |
def to_html(self, show_mean=None, sortable=None, colorize=True, *args,
**kwargs):
"""Extend Pandas built in `to_html` method for rendering a DataFrame
and use it to render a ScoreMatrix."""
if show_mean is None:
show_mean = self.show_mean
if sortable is None:
... | def function[to_html, parameter[self, show_mean, sortable, colorize]]:
constant[Extend Pandas built in `to_html` method for rendering a DataFrame
and use it to render a ScoreMatrix.]
if compare[name[show_mean] is constant[None]] begin[:]
variable[show_mean] assign[=] name[self].s... | keyword[def] identifier[to_html] ( identifier[self] , identifier[show_mean] = keyword[None] , identifier[sortable] = keyword[None] , identifier[colorize] = keyword[True] ,* identifier[args] ,
** identifier[kwargs] ):
literal[string]
keyword[if] identifier[show_mean] keyword[is] keyword[None] :
... | def to_html(self, show_mean=None, sortable=None, colorize=True, *args, **kwargs):
"""Extend Pandas built in `to_html` method for rendering a DataFrame
and use it to render a ScoreMatrix."""
if show_mean is None:
show_mean = self.show_mean # depends on [control=['if'], data=['show_mean']]
if... |
def write_squonk_datasetmetadata(outputBase, thinOutput, valueClassMappings, datasetMetaProps, fieldMetaProps):
"""This is a temp hack to write the minimal metadata that Squonk needs.
Will needs to be replaced with something that allows something more complete to be written.
:param outputBase: Base name fo... | def function[write_squonk_datasetmetadata, parameter[outputBase, thinOutput, valueClassMappings, datasetMetaProps, fieldMetaProps]]:
constant[This is a temp hack to write the minimal metadata that Squonk needs.
Will needs to be replaced with something that allows something more complete to be written.
... | keyword[def] identifier[write_squonk_datasetmetadata] ( identifier[outputBase] , identifier[thinOutput] , identifier[valueClassMappings] , identifier[datasetMetaProps] , identifier[fieldMetaProps] ):
literal[string]
identifier[meta] ={}
identifier[props] ={}
keyword[if] identifier[datasetMe... | def write_squonk_datasetmetadata(outputBase, thinOutput, valueClassMappings, datasetMetaProps, fieldMetaProps):
"""This is a temp hack to write the minimal metadata that Squonk needs.
Will needs to be replaced with something that allows something more complete to be written.
:param outputBase: Base name fo... |
def calculate_time_to_reset(self):
"""Calculate the seconds to reset the token requests, by obtaining the different
between the current date and the next date when the token is fully regenerated.
"""
time_to_reset = self.rate_limit_reset_ts - (datetime_utcnow().replace(microsecond=0).ti... | def function[calculate_time_to_reset, parameter[self]]:
constant[Calculate the seconds to reset the token requests, by obtaining the different
between the current date and the next date when the token is fully regenerated.
]
variable[time_to_reset] assign[=] binary_operation[name[self].r... | keyword[def] identifier[calculate_time_to_reset] ( identifier[self] ):
literal[string]
identifier[time_to_reset] = identifier[self] . identifier[rate_limit_reset_ts] -( identifier[datetime_utcnow] (). identifier[replace] ( identifier[microsecond] = literal[int] ). identifier[timestamp] ()+ literal... | def calculate_time_to_reset(self):
"""Calculate the seconds to reset the token requests, by obtaining the different
between the current date and the next date when the token is fully regenerated.
"""
time_to_reset = self.rate_limit_reset_ts - (datetime_utcnow().replace(microsecond=0).timestamp()... |
def allocate(self, manager=None):
"""
This function is called once we have completed the initialization
of the :class:`Work`. It sets the manager of each task (if not already done)
and defines the working directories of the tasks.
Args:
manager: :class:`TaskManager` ... | def function[allocate, parameter[self, manager]]:
constant[
This function is called once we have completed the initialization
of the :class:`Work`. It sets the manager of each task (if not already done)
and defines the working directories of the tasks.
Args:
manager:... | keyword[def] identifier[allocate] ( identifier[self] , identifier[manager] = keyword[None] ):
literal[string]
keyword[for] identifier[i] , identifier[task] keyword[in] identifier[enumerate] ( identifier[self] ):
keyword[if] keyword[not] identifier[hasattr] ( identifier[task] , li... | def allocate(self, manager=None):
"""
This function is called once we have completed the initialization
of the :class:`Work`. It sets the manager of each task (if not already done)
and defines the working directories of the tasks.
Args:
manager: :class:`TaskManager` obje... |
def convert_to_oqhazardlib(
self, tom, simple_mesh_spacing=1.0,
complex_mesh_spacing=2.0, area_discretisation=10.0,
use_defaults=False):
"""
Converts the source model to an iterator of sources of :class:
openquake.hazardlib.source.base.BaseSeismicSource
... | def function[convert_to_oqhazardlib, parameter[self, tom, simple_mesh_spacing, complex_mesh_spacing, area_discretisation, use_defaults]]:
constant[
Converts the source model to an iterator of sources of :class:
openquake.hazardlib.source.base.BaseSeismicSource
]
variable[oq_sourc... | keyword[def] identifier[convert_to_oqhazardlib] (
identifier[self] , identifier[tom] , identifier[simple_mesh_spacing] = literal[int] ,
identifier[complex_mesh_spacing] = literal[int] , identifier[area_discretisation] = literal[int] ,
identifier[use_defaults] = keyword[False] ):
literal[string]
... | def convert_to_oqhazardlib(self, tom, simple_mesh_spacing=1.0, complex_mesh_spacing=2.0, area_discretisation=10.0, use_defaults=False):
"""
Converts the source model to an iterator of sources of :class:
openquake.hazardlib.source.base.BaseSeismicSource
"""
oq_source_model = []
for so... |
def _lreg_bokeh(self, **kwargs):
"""
Returns a Bokeh linear regression line
"""
try:
ds2 = self._duplicate_()
ds2.timestamps(ds2.x)
ds2.lreg("Timestamps", ds2.y)
ds2.drop(ds2.y)
ds2.df = ds2.df.rename(columns={'Regression': ds2.... | def function[_lreg_bokeh, parameter[self]]:
constant[
Returns a Bokeh linear regression line
]
<ast.Try object at 0x7da18bc72290> | keyword[def] identifier[_lreg_bokeh] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
identifier[ds2] = identifier[self] . identifier[_duplicate_] ()
identifier[ds2] . identifier[timestamps] ( identifier[ds2] . identifier[x] )
identi... | def _lreg_bokeh(self, **kwargs):
"""
Returns a Bokeh linear regression line
"""
try:
ds2 = self._duplicate_()
ds2.timestamps(ds2.x)
ds2.lreg('Timestamps', ds2.y)
ds2.drop(ds2.y)
ds2.df = ds2.df.rename(columns={'Regression': ds2.y})
if 'date_format'... |
def render_customizations(self):
"""
Customize template for site user specified customizations
"""
disable_plugins = self.pt.customize_conf.get('disable_plugins', [])
if not disable_plugins:
logger.debug('No site-user specified plugins to disable')
else:
... | def function[render_customizations, parameter[self]]:
constant[
Customize template for site user specified customizations
]
variable[disable_plugins] assign[=] call[name[self].pt.customize_conf.get, parameter[constant[disable_plugins], list[[]]]]
if <ast.UnaryOp object at 0x7da1b... | keyword[def] identifier[render_customizations] ( identifier[self] ):
literal[string]
identifier[disable_plugins] = identifier[self] . identifier[pt] . identifier[customize_conf] . identifier[get] ( literal[string] ,[])
keyword[if] keyword[not] identifier[disable_plugins] :
i... | def render_customizations(self):
"""
Customize template for site user specified customizations
"""
disable_plugins = self.pt.customize_conf.get('disable_plugins', [])
if not disable_plugins:
logger.debug('No site-user specified plugins to disable') # depends on [control=['if'], data... |
def upsample_geolocation(self, dsid, info):
"""Upsample the geolocation (lon,lat) from the tiepoint grid"""
from geotiepoints import SatelliteInterpolator
# Read the fields needed:
col_indices = self.nc['nx_reduced'].values
row_indices = self.nc['ny_reduced'].values
lat_r... | def function[upsample_geolocation, parameter[self, dsid, info]]:
constant[Upsample the geolocation (lon,lat) from the tiepoint grid]
from relative_module[geotiepoints] import module[SatelliteInterpolator]
variable[col_indices] assign[=] call[name[self].nc][constant[nx_reduced]].values
variab... | keyword[def] identifier[upsample_geolocation] ( identifier[self] , identifier[dsid] , identifier[info] ):
literal[string]
keyword[from] identifier[geotiepoints] keyword[import] identifier[SatelliteInterpolator]
identifier[col_indices] = identifier[self] . identifier[nc] [ lite... | def upsample_geolocation(self, dsid, info):
"""Upsample the geolocation (lon,lat) from the tiepoint grid"""
from geotiepoints import SatelliteInterpolator
# Read the fields needed:
col_indices = self.nc['nx_reduced'].values
row_indices = self.nc['ny_reduced'].values
lat_reduced = self.scale_data... |
def _avgConnectedSpanForColumn1D(self, columnIndex):
"""
The range of connected synapses for column. This is used to
calculate the inhibition radius. This variation of the function only
supports a 1 dimensional column topology.
Parameters:
----------------------------
:param columnIndex: ... | def function[_avgConnectedSpanForColumn1D, parameter[self, columnIndex]]:
constant[
The range of connected synapses for column. This is used to
calculate the inhibition radius. This variation of the function only
supports a 1 dimensional column topology.
Parameters:
------------------------... | keyword[def] identifier[_avgConnectedSpanForColumn1D] ( identifier[self] , identifier[columnIndex] ):
literal[string]
keyword[assert] ( identifier[self] . identifier[_inputDimensions] . identifier[size] == literal[int] )
identifier[connected] = identifier[self] . identifier[_connectedSynapses] [ ident... | def _avgConnectedSpanForColumn1D(self, columnIndex):
"""
The range of connected synapses for column. This is used to
calculate the inhibition radius. This variation of the function only
supports a 1 dimensional column topology.
Parameters:
----------------------------
:param columnIndex: ... |
def loadtxt_str(path:PathOrStr)->np.ndarray:
"Return `ndarray` of `str` of lines of text from `path`."
with open(path, 'r') as f: lines = f.readlines()
return np.array([l.strip() for l in lines]) | def function[loadtxt_str, parameter[path]]:
constant[Return `ndarray` of `str` of lines of text from `path`.]
with call[name[open], parameter[name[path], constant[r]]] begin[:]
variable[lines] assign[=] call[name[f].readlines, parameter[]]
return[call[name[np].array, parameter[<ast.L... | keyword[def] identifier[loadtxt_str] ( identifier[path] : identifier[PathOrStr] )-> identifier[np] . identifier[ndarray] :
literal[string]
keyword[with] identifier[open] ( identifier[path] , literal[string] ) keyword[as] identifier[f] : identifier[lines] = identifier[f] . identifier[readlines] ()
ke... | def loadtxt_str(path: PathOrStr) -> np.ndarray:
"""Return `ndarray` of `str` of lines of text from `path`."""
with open(path, 'r') as f:
lines = f.readlines() # depends on [control=['with'], data=['f']]
return np.array([l.strip() for l in lines]) |
def incoordination_score(self, data_frame):
"""
This method calculates the variance of the time interval in msec between taps
:param data_frame: the data frame
:type data_frame: pandas.DataFrame
:return is: incoordination score
:rtype is: float
... | def function[incoordination_score, parameter[self, data_frame]]:
constant[
This method calculates the variance of the time interval in msec between taps
:param data_frame: the data frame
:type data_frame: pandas.DataFrame
:return is: incoordination score
... | keyword[def] identifier[incoordination_score] ( identifier[self] , identifier[data_frame] ):
literal[string]
identifier[diff] = identifier[data_frame] . identifier[td] [ literal[int] :- literal[int] ]. identifier[values] - identifier[data_frame] . identifier[td] [ literal[int] :- literal[int] ]. id... | def incoordination_score(self, data_frame):
"""
This method calculates the variance of the time interval in msec between taps
:param data_frame: the data frame
:type data_frame: pandas.DataFrame
:return is: incoordination score
:rtype is: float
"... |
def add_and_get(self, delta):
"""
Adds the given value to the current value and returns the updated value.
:raises NoDataMemberInClusterError: if the cluster does not contain any data members.
:raises UnsupportedOperationError: if the cluster version is less than 3.10.
:raises C... | def function[add_and_get, parameter[self, delta]]:
constant[
Adds the given value to the current value and returns the updated value.
:raises NoDataMemberInClusterError: if the cluster does not contain any data members.
:raises UnsupportedOperationError: if the cluster version is less t... | keyword[def] identifier[add_and_get] ( identifier[self] , identifier[delta] ):
literal[string]
keyword[return] identifier[self] . identifier[_invoke_internal] ( identifier[pn_counter_add_codec] , identifier[delta] = identifier[delta] , identifier[get_before_update] = keyword[False] ) | def add_and_get(self, delta):
"""
Adds the given value to the current value and returns the updated value.
:raises NoDataMemberInClusterError: if the cluster does not contain any data members.
:raises UnsupportedOperationError: if the cluster version is less than 3.10.
:raises Consi... |
def create_argparser():
"""Instantiate an `argparse.ArgumentParser`.
Adds all basic cli options including default values.
"""
parser = argparse.ArgumentParser()
arg_defaults = {
"daemon": False,
"loop": False,
"listpresets": False,
"config": None,
"debug": Fa... | def function[create_argparser, parameter[]]:
constant[Instantiate an `argparse.ArgumentParser`.
Adds all basic cli options including default values.
]
variable[parser] assign[=] call[name[argparse].ArgumentParser, parameter[]]
variable[arg_defaults] assign[=] dictionary[[<ast.Constant o... | keyword[def] identifier[create_argparser] ():
literal[string]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] ()
identifier[arg_defaults] ={
literal[string] : keyword[False] ,
literal[string] : keyword[False] ,
literal[string] : keyword[False] ,
literal[strin... | def create_argparser():
"""Instantiate an `argparse.ArgumentParser`.
Adds all basic cli options including default values.
"""
parser = argparse.ArgumentParser()
arg_defaults = {'daemon': False, 'loop': False, 'listpresets': False, 'config': None, 'debug': False, 'sleeptime': 300, 'version': False, ... |
def bkg_noise(readout_noise, exposure_time, sky_brightness, pixel_scael, num_exposures=1):
"""
computes the expected Gaussian background noise of a pixel in units of counts/second
:param readout_noise: noise added per readout
:param exposure_time: exposure time per exposure (in seconds)
:param sky_... | def function[bkg_noise, parameter[readout_noise, exposure_time, sky_brightness, pixel_scael, num_exposures]]:
constant[
computes the expected Gaussian background noise of a pixel in units of counts/second
:param readout_noise: noise added per readout
:param exposure_time: exposure time per exposure... | keyword[def] identifier[bkg_noise] ( identifier[readout_noise] , identifier[exposure_time] , identifier[sky_brightness] , identifier[pixel_scael] , identifier[num_exposures] = literal[int] ):
literal[string]
identifier[exposure_time_tot] = identifier[num_exposures] * identifier[exposure_time]
identif... | def bkg_noise(readout_noise, exposure_time, sky_brightness, pixel_scael, num_exposures=1):
"""
computes the expected Gaussian background noise of a pixel in units of counts/second
:param readout_noise: noise added per readout
:param exposure_time: exposure time per exposure (in seconds)
:param sky_... |
def phoncontent(self, cls='current', correctionhandling=CorrectionHandling.CURRENT):
"""See :meth:`AbstractElement.phoncontent`"""
if cls == 'original': correctionhandling = CorrectionHandling.ORIGINAL #backward compatibility
if correctionhandling in (CorrectionHandling.CURRENT, CorrectionHandli... | def function[phoncontent, parameter[self, cls, correctionhandling]]:
constant[See :meth:`AbstractElement.phoncontent`]
if compare[name[cls] equal[==] constant[original]] begin[:]
variable[correctionhandling] assign[=] name[CorrectionHandling].ORIGINAL
if compare[name[correctionha... | keyword[def] identifier[phoncontent] ( identifier[self] , identifier[cls] = literal[string] , identifier[correctionhandling] = identifier[CorrectionHandling] . identifier[CURRENT] ):
literal[string]
keyword[if] identifier[cls] == literal[string] : identifier[correctionhandling] = identifier[Correc... | def phoncontent(self, cls='current', correctionhandling=CorrectionHandling.CURRENT):
"""See :meth:`AbstractElement.phoncontent`"""
if cls == 'original':
correctionhandling = CorrectionHandling.ORIGINAL #backward compatibility # depends on [control=['if'], data=[]]
if correctionhandling in (Correct... |
def prepare_authorization_response(self, request, token, headers, body, status):
"""Place token according to response mode.
Base classes can define a default response mode for their authorization
response by overriding the static `default_response_mode` member.
:param request: OAuthlib... | def function[prepare_authorization_response, parameter[self, request, token, headers, body, status]]:
constant[Place token according to response mode.
Base classes can define a default response mode for their authorization
response by overriding the static `default_response_mode` member.
... | keyword[def] identifier[prepare_authorization_response] ( identifier[self] , identifier[request] , identifier[token] , identifier[headers] , identifier[body] , identifier[status] ):
literal[string]
identifier[request] . identifier[response_mode] = identifier[request] . identifier[response_mode] ke... | def prepare_authorization_response(self, request, token, headers, body, status):
"""Place token according to response mode.
Base classes can define a default response mode for their authorization
response by overriding the static `default_response_mode` member.
:param request: OAuthlib req... |
def request(self, method, data=None, nid=None, nid_key='nid',
api_type="logic", return_response=False):
"""Get data from arbitrary Piazza API endpoint `method` in network `nid`
:type method: str
:param method: An internal Piazza API method name like `content.get`
or... | def function[request, parameter[self, method, data, nid, nid_key, api_type, return_response]]:
constant[Get data from arbitrary Piazza API endpoint `method` in network `nid`
:type method: str
:param method: An internal Piazza API method name like `content.get`
or `network.get_users... | keyword[def] identifier[request] ( identifier[self] , identifier[method] , identifier[data] = keyword[None] , identifier[nid] = keyword[None] , identifier[nid_key] = literal[string] ,
identifier[api_type] = literal[string] , identifier[return_response] = keyword[False] ):
literal[string]
identifie... | def request(self, method, data=None, nid=None, nid_key='nid', api_type='logic', return_response=False):
"""Get data from arbitrary Piazza API endpoint `method` in network `nid`
:type method: str
:param method: An internal Piazza API method name like `content.get`
or `network.get_users`... |
def dummyctrl(self,r,ctrl):
"""creates a DummyVertex at rank r inserted in the ctrl dict
of the associated edge and layer.
Arguments:
r (int): rank value
ctrl (dict): the edge's control vertices
Returns:
DummyVertex : the cr... | def function[dummyctrl, parameter[self, r, ctrl]]:
constant[creates a DummyVertex at rank r inserted in the ctrl dict
of the associated edge and layer.
Arguments:
r (int): rank value
ctrl (dict): the edge's control vertices
Returns:
... | keyword[def] identifier[dummyctrl] ( identifier[self] , identifier[r] , identifier[ctrl] ):
literal[string]
identifier[dv] = identifier[DummyVertex] ( identifier[r] )
identifier[dv] . identifier[view] . identifier[w] , identifier[dv] . identifier[view] . identifier[h] = identifier[self] . ... | def dummyctrl(self, r, ctrl):
"""creates a DummyVertex at rank r inserted in the ctrl dict
of the associated edge and layer.
Arguments:
r (int): rank value
ctrl (dict): the edge's control vertices
Returns:
DummyVertex : the crea... |
def create_rcontext(self, size, frame):
'''
Creates a recording surface for the bot to draw on
:param size: The width and height of bot
'''
self.frame = frame
width, height = size
meta_surface = cairo.RecordingSurface(cairo.CONTENT_COLOR_ALPHA, (0, 0, width, heig... | def function[create_rcontext, parameter[self, size, frame]]:
constant[
Creates a recording surface for the bot to draw on
:param size: The width and height of bot
]
name[self].frame assign[=] name[frame]
<ast.Tuple object at 0x7da1b00f4a30> assign[=] name[size]
v... | keyword[def] identifier[create_rcontext] ( identifier[self] , identifier[size] , identifier[frame] ):
literal[string]
identifier[self] . identifier[frame] = identifier[frame]
identifier[width] , identifier[height] = identifier[size]
identifier[meta_surface] = identifier[cairo] .... | def create_rcontext(self, size, frame):
"""
Creates a recording surface for the bot to draw on
:param size: The width and height of bot
"""
self.frame = frame
(width, height) = size
meta_surface = cairo.RecordingSurface(cairo.CONTENT_COLOR_ALPHA, (0, 0, width, height))
ctx =... |
def unlock(self):
"""Unlock the device."""
success = self.set_status(CONST.STATUS_LOCKOPEN_INT)
if success:
self._json_state['status'] = CONST.STATUS_LOCKOPEN
return success | def function[unlock, parameter[self]]:
constant[Unlock the device.]
variable[success] assign[=] call[name[self].set_status, parameter[name[CONST].STATUS_LOCKOPEN_INT]]
if name[success] begin[:]
call[name[self]._json_state][constant[status]] assign[=] name[CONST].STATUS_LOCKOPEN
... | keyword[def] identifier[unlock] ( identifier[self] ):
literal[string]
identifier[success] = identifier[self] . identifier[set_status] ( identifier[CONST] . identifier[STATUS_LOCKOPEN_INT] )
keyword[if] identifier[success] :
identifier[self] . identifier[_json_state] [ litera... | def unlock(self):
"""Unlock the device."""
success = self.set_status(CONST.STATUS_LOCKOPEN_INT)
if success:
self._json_state['status'] = CONST.STATUS_LOCKOPEN # depends on [control=['if'], data=[]]
return success |
def show(close=None):
"""Show all figures as SVG/PNG payloads sent to the IPython clients.
Parameters
----------
close : bool, optional
If true, a ``plt.close('all')`` call is automatically issued after
sending all the figures. If this is set, the figures will entirely
removed from th... | def function[show, parameter[close]]:
constant[Show all figures as SVG/PNG payloads sent to the IPython clients.
Parameters
----------
close : bool, optional
If true, a ``plt.close('all')`` call is automatically issued after
sending all the figures. If this is set, the figures will enti... | keyword[def] identifier[show] ( identifier[close] = keyword[None] ):
literal[string]
keyword[if] identifier[close] keyword[is] keyword[None] :
identifier[close] = identifier[InlineBackend] . identifier[instance] (). identifier[close_figures]
keyword[try] :
keyword[for] identifie... | def show(close=None):
"""Show all figures as SVG/PNG payloads sent to the IPython clients.
Parameters
----------
close : bool, optional
If true, a ``plt.close('all')`` call is automatically issued after
sending all the figures. If this is set, the figures will entirely
removed from th... |
def replace_activities(self):
"""Replace ative flags with Agent states when possible."""
logger.debug('Running PySB Preassembler replace activities')
# TODO: handle activity hierarchies
new_stmts = []
def has_agent_activity(stmt):
"""Return True if any agents in the ... | def function[replace_activities, parameter[self]]:
constant[Replace ative flags with Agent states when possible.]
call[name[logger].debug, parameter[constant[Running PySB Preassembler replace activities]]]
variable[new_stmts] assign[=] list[[]]
def function[has_agent_activity, parameter[... | keyword[def] identifier[replace_activities] ( identifier[self] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] )
identifier[new_stmts] =[]
keyword[def] identifier[has_agent_activity] ( identifier[stmt] ):
literal[string]
... | def replace_activities(self):
"""Replace ative flags with Agent states when possible."""
logger.debug('Running PySB Preassembler replace activities')
# TODO: handle activity hierarchies
new_stmts = []
def has_agent_activity(stmt):
"""Return True if any agents in the Statement have activity.... |
def load_plug_in(self, name):
"""Loads a DBGF plug-in.
in name of type str
The plug-in name or DLL. Special name 'all' loads all installed plug-ins.
return plug_in_name of type str
The name of the loaded plug-in.
"""
if not isinstance(name, basestring):... | def function[load_plug_in, parameter[self, name]]:
constant[Loads a DBGF plug-in.
in name of type str
The plug-in name or DLL. Special name 'all' loads all installed plug-ins.
return plug_in_name of type str
The name of the loaded plug-in.
]
if <ast.Una... | keyword[def] identifier[load_plug_in] ( identifier[self] , identifier[name] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[name] , identifier[basestring] ):
keyword[raise] identifier[TypeError] ( literal[string] )
identifier[plug_in_name] = ... | def load_plug_in(self, name):
"""Loads a DBGF plug-in.
in name of type str
The plug-in name or DLL. Special name 'all' loads all installed plug-ins.
return plug_in_name of type str
The name of the loaded plug-in.
"""
if not isinstance(name, basestring):
... |
def insertChild(self, childItem, position=None):
""" Inserts a child item to the current item.
The childItem must not yet have a parent (it will be set by this function).
IMPORTANT: this does not let the model know that items have been added.
Use BaseTreeModel.insertItem ins... | def function[insertChild, parameter[self, childItem, position]]:
constant[ Inserts a child item to the current item.
The childItem must not yet have a parent (it will be set by this function).
IMPORTANT: this does not let the model know that items have been added.
Use BaseTr... | keyword[def] identifier[insertChild] ( identifier[self] , identifier[childItem] , identifier[position] = keyword[None] ):
literal[string]
keyword[if] identifier[position] keyword[is] keyword[None] :
identifier[position] = identifier[self] . identifier[nChildren] ()
keyword... | def insertChild(self, childItem, position=None):
""" Inserts a child item to the current item.
The childItem must not yet have a parent (it will be set by this function).
IMPORTANT: this does not let the model know that items have been added.
Use BaseTreeModel.insertItem instead... |
def send_magic_packet(*macs, **kwargs):
"""
Wake up computers having any of the given mac addresses.
Wake on lan must be enabled on the host device.
Args:
macs (str): One or more macaddresses of machines to wake.
Keyword Args:
ip_address (str): the ip address of the host to send t... | def function[send_magic_packet, parameter[]]:
constant[
Wake up computers having any of the given mac addresses.
Wake on lan must be enabled on the host device.
Args:
macs (str): One or more macaddresses of machines to wake.
Keyword Args:
ip_address (str): the ip address of th... | keyword[def] identifier[send_magic_packet] (* identifier[macs] ,** identifier[kwargs] ):
literal[string]
identifier[packets] =[]
identifier[ip] = identifier[kwargs] . identifier[pop] ( literal[string] , identifier[BROADCAST_IP] )
identifier[port] = identifier[kwargs] . identifier[pop] ( literal[s... | def send_magic_packet(*macs, **kwargs):
"""
Wake up computers having any of the given mac addresses.
Wake on lan must be enabled on the host device.
Args:
macs (str): One or more macaddresses of machines to wake.
Keyword Args:
ip_address (str): the ip address of the host to send t... |
def _getConfigData(self, all_dependencies, component, builddir, build_info_header_path):
''' returns (path_to_config_header, cmake_set_definitions) '''
# ordered_json, , read/write ordered json, internal
from yotta.lib import ordered_json
add_defs_header = ''
set_definitions = ''... | def function[_getConfigData, parameter[self, all_dependencies, component, builddir, build_info_header_path]]:
constant[ returns (path_to_config_header, cmake_set_definitions) ]
from relative_module[yotta.lib] import module[ordered_json]
variable[add_defs_header] assign[=] constant[]
variable... | keyword[def] identifier[_getConfigData] ( identifier[self] , identifier[all_dependencies] , identifier[component] , identifier[builddir] , identifier[build_info_header_path] ):
literal[string]
keyword[from] identifier[yotta] . identifier[lib] keyword[import] identifier[ordered_json]
... | def _getConfigData(self, all_dependencies, component, builddir, build_info_header_path):
""" returns (path_to_config_header, cmake_set_definitions) """
# ordered_json, , read/write ordered json, internal
from yotta.lib import ordered_json
add_defs_header = ''
set_definitions = ''
# !!! backwards... |
def _chunks(self, l, n):
""" Yield n successive chunks from a list l.
"""
l.sort()
newn = int(1.0 * len(l) / n + 0.5)
for i in range(0, n-1):
yield l[i*newn:i*newn+newn]
yield l[n*newn-newn:] | def function[_chunks, parameter[self, l, n]]:
constant[ Yield n successive chunks from a list l.
]
call[name[l].sort, parameter[]]
variable[newn] assign[=] call[name[int], parameter[binary_operation[binary_operation[binary_operation[constant[1.0] * call[name[len], parameter[name[l]]]] / ... | keyword[def] identifier[_chunks] ( identifier[self] , identifier[l] , identifier[n] ):
literal[string]
identifier[l] . identifier[sort] ()
identifier[newn] = identifier[int] ( literal[int] * identifier[len] ( identifier[l] )/ identifier[n] + literal[int] )
keyword[for] identifier... | def _chunks(self, l, n):
""" Yield n successive chunks from a list l.
"""
l.sort()
newn = int(1.0 * len(l) / n + 0.5)
for i in range(0, n - 1):
yield l[i * newn:i * newn + newn] # depends on [control=['for'], data=['i']]
yield l[n * newn - newn:] |
def type_assert_dict(
d,
kcls=None,
vcls=None,
allow_none=False,
cast_from=None,
cast_to=None,
dynamic=None,
objcls=None,
ctor=None,
):
""" Checks that every key/value in @d is an instance of @kcls: @vcls
Will also unmarshal JSON objects to Python objects if
the ... | def function[type_assert_dict, parameter[d, kcls, vcls, allow_none, cast_from, cast_to, dynamic, objcls, ctor]]:
constant[ Checks that every key/value in @d is an instance of @kcls: @vcls
Will also unmarshal JSON objects to Python objects if
the value is an instance of dict and @vcls is a class... | keyword[def] identifier[type_assert_dict] (
identifier[d] ,
identifier[kcls] = keyword[None] ,
identifier[vcls] = keyword[None] ,
identifier[allow_none] = keyword[False] ,
identifier[cast_from] = keyword[None] ,
identifier[cast_to] = keyword[None] ,
identifier[dynamic] = keyword[None] ,
identifier[objcls] = k... | def type_assert_dict(d, kcls=None, vcls=None, allow_none=False, cast_from=None, cast_to=None, dynamic=None, objcls=None, ctor=None):
""" Checks that every key/value in @d is an instance of @kcls: @vcls
Will also unmarshal JSON objects to Python objects if
the value is an instance of dict and @vcls ... |
def DebugLog(self):
"Devolver y limpiar la bitácora de depuración"
if self.Log:
msg = self.Log.getvalue()
# limpiar log
self.Log.close()
self.Log = None
else:
msg = u''
return msg | def function[DebugLog, parameter[self]]:
constant[Devolver y limpiar la bitácora de depuración]
if name[self].Log begin[:]
variable[msg] assign[=] call[name[self].Log.getvalue, parameter[]]
call[name[self].Log.close, parameter[]]
name[self].Log assign[=] c... | keyword[def] identifier[DebugLog] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[Log] :
identifier[msg] = identifier[self] . identifier[Log] . identifier[getvalue] ()
identifier[self] . identifier[Log] . identifier[close] ()
... | def DebugLog(self):
"""Devolver y limpiar la bitácora de depuración"""
if self.Log:
msg = self.Log.getvalue()
# limpiar log
self.Log.close()
self.Log = None # depends on [control=['if'], data=[]]
else:
msg = u''
return msg |
def address(self, is_compressed=None):
"""
Return the public address representation of this key, if available.
"""
return self._network.address.for_p2pkh(self.hash160(is_compressed=is_compressed)) | def function[address, parameter[self, is_compressed]]:
constant[
Return the public address representation of this key, if available.
]
return[call[name[self]._network.address.for_p2pkh, parameter[call[name[self].hash160, parameter[]]]]] | keyword[def] identifier[address] ( identifier[self] , identifier[is_compressed] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[_network] . identifier[address] . identifier[for_p2pkh] ( identifier[self] . identifier[hash160] ( identifier[is_compressed] = identifier... | def address(self, is_compressed=None):
"""
Return the public address representation of this key, if available.
"""
return self._network.address.for_p2pkh(self.hash160(is_compressed=is_compressed)) |
def set(self, hue):
"""Set cursor position on the color corresponding to the hue value."""
x = hue / 360. * self.winfo_width()
self.coords('cursor', x, 0, x, self.winfo_height())
self._variable.set(hue) | def function[set, parameter[self, hue]]:
constant[Set cursor position on the color corresponding to the hue value.]
variable[x] assign[=] binary_operation[binary_operation[name[hue] / constant[360.0]] * call[name[self].winfo_width, parameter[]]]
call[name[self].coords, parameter[constant[cursor]... | keyword[def] identifier[set] ( identifier[self] , identifier[hue] ):
literal[string]
identifier[x] = identifier[hue] / literal[int] * identifier[self] . identifier[winfo_width] ()
identifier[self] . identifier[coords] ( literal[string] , identifier[x] , literal[int] , identifier[x] , ident... | def set(self, hue):
"""Set cursor position on the color corresponding to the hue value."""
x = hue / 360.0 * self.winfo_width()
self.coords('cursor', x, 0, x, self.winfo_height())
self._variable.set(hue) |
def filters(self):
"""Return filters from query string.
:return list: filter information
"""
results = []
filters = self.qs.get('filter')
if filters is not None:
try:
results.extend(json.loads(filters))
except (ValueError, TypeErro... | def function[filters, parameter[self]]:
constant[Return filters from query string.
:return list: filter information
]
variable[results] assign[=] list[[]]
variable[filters] assign[=] call[name[self].qs.get, parameter[constant[filter]]]
if compare[name[filters] is_not con... | keyword[def] identifier[filters] ( identifier[self] ):
literal[string]
identifier[results] =[]
identifier[filters] = identifier[self] . identifier[qs] . identifier[get] ( literal[string] )
keyword[if] identifier[filters] keyword[is] keyword[not] keyword[None] :
ke... | def filters(self):
"""Return filters from query string.
:return list: filter information
"""
results = []
filters = self.qs.get('filter')
if filters is not None:
try:
results.extend(json.loads(filters)) # depends on [control=['try'], data=[]]
except (ValueEr... |
def is_unique(keys, *, scope=None, comparison_operators=None, present_optional=False,
message=None):
"""Returns a Validation that makes sure the given value is unique for a table and optionally a
scope.
"""
def check(pname, validator):
"""Checks that a value is unique in its column... | def function[is_unique, parameter[keys]]:
constant[Returns a Validation that makes sure the given value is unique for a table and optionally a
scope.
]
def function[check, parameter[pname, validator]]:
constant[Checks that a value is unique in its column, with an optional scope.]... | keyword[def] identifier[is_unique] ( identifier[keys] ,*, identifier[scope] = keyword[None] , identifier[comparison_operators] = keyword[None] , identifier[present_optional] = keyword[False] ,
identifier[message] = keyword[None] ):
literal[string]
keyword[def] identifier[check] ( identifier[pname] , iden... | def is_unique(keys, *, scope=None, comparison_operators=None, present_optional=False, message=None):
"""Returns a Validation that makes sure the given value is unique for a table and optionally a
scope.
"""
def check(pname, validator):
"""Checks that a value is unique in its column, with an opt... |
def commits(self, branch, since=0, to=int(time.time()) + 86400):
"""For given branch return a list of commits.
Each commit contains basic information about itself.
Raises GithubException if rate limit is exceeded
:param branch: git branch
:type branch: str
:param since: minimal timestamp for commit's com... | def function[commits, parameter[self, branch, since, to]]:
constant[For given branch return a list of commits.
Each commit contains basic information about itself.
Raises GithubException if rate limit is exceeded
:param branch: git branch
:type branch: str
:param since: minimal timestamp for commit... | keyword[def] identifier[commits] ( identifier[self] , identifier[branch] , identifier[since] = literal[int] , identifier[to] = identifier[int] ( identifier[time] . identifier[time] ())+ literal[int] ):
literal[string]
keyword[if] identifier[self] . identifier[github] . identifier[get_rate_limit] (). identifie... | def commits(self, branch, since=0, to=int(time.time()) + 86400):
"""For given branch return a list of commits.
Each commit contains basic information about itself.
Raises GithubException if rate limit is exceeded
:param branch: git branch
:type branch: str
:param since: minimal timestamp for commit's c... |
def coverage(self):
"""
Get the fraction of this title sequence that is matched by its reads.
@return: The C{float} fraction of the title sequence matched by its
reads.
"""
intervals = ReadIntervals(self.subjectLength)
for hsp in self.hsps():
inte... | def function[coverage, parameter[self]]:
constant[
Get the fraction of this title sequence that is matched by its reads.
@return: The C{float} fraction of the title sequence matched by its
reads.
]
variable[intervals] assign[=] call[name[ReadIntervals], parameter[nam... | keyword[def] identifier[coverage] ( identifier[self] ):
literal[string]
identifier[intervals] = identifier[ReadIntervals] ( identifier[self] . identifier[subjectLength] )
keyword[for] identifier[hsp] keyword[in] identifier[self] . identifier[hsps] ():
identifier[intervals] ... | def coverage(self):
"""
Get the fraction of this title sequence that is matched by its reads.
@return: The C{float} fraction of the title sequence matched by its
reads.
"""
intervals = ReadIntervals(self.subjectLength)
for hsp in self.hsps():
intervals.add(hsp.su... |
def factory(data):
"""Tahoma Event factory."""
if data['name'] is "DeviceStateChangedEvent":
return DeviceStateChangedEvent(data)
elif data['name'] is "ExecutionStateChangedEvent":
return ExecutionStateChangedEvent(data)
elif data['name'] is "CommandExecutionState... | def function[factory, parameter[data]]:
constant[Tahoma Event factory.]
if compare[call[name[data]][constant[name]] is constant[DeviceStateChangedEvent]] begin[:]
return[call[name[DeviceStateChangedEvent], parameter[name[data]]]] | keyword[def] identifier[factory] ( identifier[data] ):
literal[string]
keyword[if] identifier[data] [ literal[string] ] keyword[is] literal[string] :
keyword[return] identifier[DeviceStateChangedEvent] ( identifier[data] )
keyword[elif] identifier[data] [ literal[string] ]... | def factory(data):
"""Tahoma Event factory."""
if data['name'] is 'DeviceStateChangedEvent':
return DeviceStateChangedEvent(data) # depends on [control=['if'], data=[]]
elif data['name'] is 'ExecutionStateChangedEvent':
return ExecutionStateChangedEvent(data) # depends on [control=['if'], ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.