code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def output(self, _filename):
"""
_filename is not used
Args:
_filename(string)
"""
txt = ""
for c in self.contracts:
(name, _inheritance, _var, func_summaries, _modif_summaries) = c.get_summary()
txt += blue("\n+ Contract %... | def function[output, parameter[self, _filename]]:
constant[
_filename is not used
Args:
_filename(string)
]
variable[txt] assign[=] constant[]
for taget[name[c]] in starred[name[self].contracts] begin[:]
<ast.Tuple object at 0x7da20... | keyword[def] identifier[output] ( identifier[self] , identifier[_filename] ):
literal[string]
identifier[txt] = literal[string]
keyword[for] identifier[c] keyword[in] identifier[self] . identifier[contracts] :
( identifier[name] , identifier[_inheritance] , identifier[_var... | def output(self, _filename):
"""
_filename is not used
Args:
_filename(string)
"""
txt = ''
for c in self.contracts:
(name, _inheritance, _var, func_summaries, _modif_summaries) = c.get_summary()
txt += blue('\n+ Contract %s\n' % name)
... |
def json_dump(obj, # type: Any
fp, # type: IO[str]
**kwargs # type: Any
): # type: (...) -> None
""" Force use of unicode. """
if six.PY2:
kwargs['encoding'] = 'utf-8'
json.dump(convert_to_dict(obj), fp, **kwargs) | def function[json_dump, parameter[obj, fp]]:
constant[ Force use of unicode. ]
if name[six].PY2 begin[:]
call[name[kwargs]][constant[encoding]] assign[=] constant[utf-8]
call[name[json].dump, parameter[call[name[convert_to_dict], parameter[name[obj]]], name[fp]]] | keyword[def] identifier[json_dump] ( identifier[obj] ,
identifier[fp] ,
** identifier[kwargs]
):
literal[string]
keyword[if] identifier[six] . identifier[PY2] :
identifier[kwargs] [ literal[string] ]= literal[string]
identifier[json] . identifier[dump] ( identifier[convert_to_dict] ( iden... | def json_dump(obj, fp, **kwargs): # type: Any
# type: IO[str]
# type: Any
# type: (...) -> None
' Force use of unicode. '
if six.PY2:
kwargs['encoding'] = 'utf-8' # depends on [control=['if'], data=[]]
json.dump(convert_to_dict(obj), fp, **kwargs) |
def yesno(question, default=None):
"""Asks a yes/no question
Args:
question: string **without** the question mark and without the options.
Example: 'Create links'
default: default option. Accepted values are 'Y', 'YES', 'N', 'NO' or lowercase versions of
these val... | def function[yesno, parameter[question, default]]:
constant[Asks a yes/no question
Args:
question: string **without** the question mark and without the options.
Example: 'Create links'
default: default option. Accepted values are 'Y', 'YES', 'N', 'NO' or lowercase versions of
... | keyword[def] identifier[yesno] ( identifier[question] , identifier[default] = keyword[None] ):
literal[string]
keyword[if] identifier[default] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[isinstance] ( identifier[default] , identifier[bool] ):
keyword[pas... | def yesno(question, default=None):
"""Asks a yes/no question
Args:
question: string **without** the question mark and without the options.
Example: 'Create links'
default: default option. Accepted values are 'Y', 'YES', 'N', 'NO' or lowercase versions of
these valus (thi... |
def lookup_obj_attribute(self, obj, field):
"""
Looks for a field's value from the passed in obj. Note that this will strip
leading attributes to deal with subelements if possible
"""
curr_field = field.encode('ascii', 'ignore').decode("utf-8")
rest = None
if fi... | def function[lookup_obj_attribute, parameter[self, obj, field]]:
constant[
Looks for a field's value from the passed in obj. Note that this will strip
leading attributes to deal with subelements if possible
]
variable[curr_field] assign[=] call[call[name[field].encode, parameter... | keyword[def] identifier[lookup_obj_attribute] ( identifier[self] , identifier[obj] , identifier[field] ):
literal[string]
identifier[curr_field] = identifier[field] . identifier[encode] ( literal[string] , literal[string] ). identifier[decode] ( literal[string] )
identifier[rest] = keyword... | def lookup_obj_attribute(self, obj, field):
"""
Looks for a field's value from the passed in obj. Note that this will strip
leading attributes to deal with subelements if possible
"""
curr_field = field.encode('ascii', 'ignore').decode('utf-8')
rest = None
if field.find('.') >= ... |
def get_incomplete_penetrance_genes(hpo_lines):
"""Get a set with all genes that have incomplete penetrance according to HPO
Args:
hpo_lines(iterable(str))
Returns:
incomplete_penetrance_genes(set): A set with the hgnc symbols of all
genes... | def function[get_incomplete_penetrance_genes, parameter[hpo_lines]]:
constant[Get a set with all genes that have incomplete penetrance according to HPO
Args:
hpo_lines(iterable(str))
Returns:
incomplete_penetrance_genes(set): A set with the hgnc symbols of all
... | keyword[def] identifier[get_incomplete_penetrance_genes] ( identifier[hpo_lines] ):
literal[string]
identifier[genes] = identifier[parse_hpo_genes] ( identifier[hpo_lines] )
identifier[incomplete_penetrance_genes] = identifier[set] ()
keyword[for] identifier[hgnc_symbol] keyword[in] identifier... | def get_incomplete_penetrance_genes(hpo_lines):
"""Get a set with all genes that have incomplete penetrance according to HPO
Args:
hpo_lines(iterable(str))
Returns:
incomplete_penetrance_genes(set): A set with the hgnc symbols of all
genes... |
def repvals(self, method):
"""Compute representative statistical values for this Uval. `method`
may be either 'pct' or 'gauss'.
Returns (best, plus_one_sigma, minus_one_sigma), where `best` is the
"best" value in some sense, and the others correspond to values at
the ~84 and 16 ... | def function[repvals, parameter[self, method]]:
constant[Compute representative statistical values for this Uval. `method`
may be either 'pct' or 'gauss'.
Returns (best, plus_one_sigma, minus_one_sigma), where `best` is the
"best" value in some sense, and the others correspond to values... | keyword[def] identifier[repvals] ( identifier[self] , identifier[method] ):
literal[string]
keyword[if] identifier[method] == literal[string] :
keyword[return] identifier[pk_scoreatpercentile] ( identifier[self] . identifier[d] ,[ literal[int] , literal[int] , literal[int] ])
... | def repvals(self, method):
"""Compute representative statistical values for this Uval. `method`
may be either 'pct' or 'gauss'.
Returns (best, plus_one_sigma, minus_one_sigma), where `best` is the
"best" value in some sense, and the others correspond to values at
the ~84 and 16 perc... |
def get_legend_text(obj):
"""Check if line is in legend.
"""
leg = obj.axes.get_legend()
if leg is None:
return None
keys = [l.get_label() for l in leg.legendHandles if l is not None]
values = [l.get_text() for l in leg.texts]
label = obj.get_label()
d = dict(zip(keys, values))... | def function[get_legend_text, parameter[obj]]:
constant[Check if line is in legend.
]
variable[leg] assign[=] call[name[obj].axes.get_legend, parameter[]]
if compare[name[leg] is constant[None]] begin[:]
return[constant[None]]
variable[keys] assign[=] <ast.ListComp object at ... | keyword[def] identifier[get_legend_text] ( identifier[obj] ):
literal[string]
identifier[leg] = identifier[obj] . identifier[axes] . identifier[get_legend] ()
keyword[if] identifier[leg] keyword[is] keyword[None] :
keyword[return] keyword[None]
identifier[keys] =[ identifier[l] . i... | def get_legend_text(obj):
"""Check if line is in legend.
"""
leg = obj.axes.get_legend()
if leg is None:
return None # depends on [control=['if'], data=[]]
keys = [l.get_label() for l in leg.legendHandles if l is not None]
values = [l.get_text() for l in leg.texts]
label = obj.get_l... |
def parse_bytes(self, i):
"""Parse byte."""
value = int(self.get_byte(i), 16)
single = self.get_single_stack()
if self.span_stack:
text = self.convert_case(chr(value), self.span_stack[-1])
value = ord(self.convert_case(text, single)) if single is not None else or... | def function[parse_bytes, parameter[self, i]]:
constant[Parse byte.]
variable[value] assign[=] call[name[int], parameter[call[name[self].get_byte, parameter[name[i]]], constant[16]]]
variable[single] assign[=] call[name[self].get_single_stack, parameter[]]
if name[self].span_stack begin[... | keyword[def] identifier[parse_bytes] ( identifier[self] , identifier[i] ):
literal[string]
identifier[value] = identifier[int] ( identifier[self] . identifier[get_byte] ( identifier[i] ), literal[int] )
identifier[single] = identifier[self] . identifier[get_single_stack] ()
keywo... | def parse_bytes(self, i):
"""Parse byte."""
value = int(self.get_byte(i), 16)
single = self.get_single_stack()
if self.span_stack:
text = self.convert_case(chr(value), self.span_stack[-1])
value = ord(self.convert_case(text, single)) if single is not None else ord(text) # depends on [co... |
def _parse_feature_value(self, value):
""" Checks if value fits the feature type. If not it tries to fix it or raise an error
:raises: ValueError
"""
if isinstance(value, _FileLoader):
return value
if not hasattr(self, 'ndim'): # Because of serialization/dese... | def function[_parse_feature_value, parameter[self, value]]:
constant[ Checks if value fits the feature type. If not it tries to fix it or raise an error
:raises: ValueError
]
if call[name[isinstance], parameter[name[value], name[_FileLoader]]] begin[:]
return[name[value]]
... | keyword[def] identifier[_parse_feature_value] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[value] , identifier[_FileLoader] ):
keyword[return] identifier[value]
keyword[if] keyword[not] identifier[hasattr] (... | def _parse_feature_value(self, value):
""" Checks if value fits the feature type. If not it tries to fix it or raise an error
:raises: ValueError
"""
if isinstance(value, _FileLoader):
return value # depends on [control=['if'], data=[]]
if not hasattr(self, 'ndim'): # Because of s... |
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name``... | def function[remove, parameter[name, pkgs]]:
constant[
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignor... | keyword[def] identifier[remove] ( identifier[name] = keyword[None] , identifier[pkgs] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
identifier[pkg_params] = identifier[__salt__] [ literal[string] ]( identifier[name] , identifier[pkgs] )[ literal[int] ]
keyword[excep... | def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'\n Remove packages using ``opkg remove``.\n\n name\n The name of the package to be deleted.\n\n\n Multiple Package Options:\n\n pkgs\n A list of packages to delete. Must be passed as a python list. The\n ... |
def _do_leave(self, leave, in_port, msg):
"""the process when the querier received a LEAVE message."""
datapath = msg.datapath
parser = datapath.ofproto_parser
self._mcast.setdefault(leave.address, {})
if in_port in self._mcast[leave.address]:
self._del_flow_entry(
... | def function[_do_leave, parameter[self, leave, in_port, msg]]:
constant[the process when the querier received a LEAVE message.]
variable[datapath] assign[=] name[msg].datapath
variable[parser] assign[=] name[datapath].ofproto_parser
call[name[self]._mcast.setdefault, parameter[name[leave... | keyword[def] identifier[_do_leave] ( identifier[self] , identifier[leave] , identifier[in_port] , identifier[msg] ):
literal[string]
identifier[datapath] = identifier[msg] . identifier[datapath]
identifier[parser] = identifier[datapath] . identifier[ofproto_parser]
identifier[s... | def _do_leave(self, leave, in_port, msg):
"""the process when the querier received a LEAVE message."""
datapath = msg.datapath
parser = datapath.ofproto_parser
self._mcast.setdefault(leave.address, {})
if in_port in self._mcast[leave.address]:
self._del_flow_entry(datapath, in_port, leave.ad... |
def lower_context_field_existence(ir_blocks, query_metadata_table):
"""Lower ContextFieldExistence expressions into lower-level expressions."""
def regular_visitor_fn(expression):
"""Expression visitor function that rewrites ContextFieldExistence expressions."""
if not isinstance(expression, Con... | def function[lower_context_field_existence, parameter[ir_blocks, query_metadata_table]]:
constant[Lower ContextFieldExistence expressions into lower-level expressions.]
def function[regular_visitor_fn, parameter[expression]]:
constant[Expression visitor function that rewrites ContextFiel... | keyword[def] identifier[lower_context_field_existence] ( identifier[ir_blocks] , identifier[query_metadata_table] ):
literal[string]
keyword[def] identifier[regular_visitor_fn] ( identifier[expression] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[exp... | def lower_context_field_existence(ir_blocks, query_metadata_table):
"""Lower ContextFieldExistence expressions into lower-level expressions."""
def regular_visitor_fn(expression):
"""Expression visitor function that rewrites ContextFieldExistence expressions."""
if not isinstance(expression, Co... |
def spawn(mode, func, *args, **kwargs):
"""Spawns a thread-like object which runs the given function concurrently.
Available modes:
- `threading`
- `greenlet`
- `eventlet`
"""
if mode is None:
# 'threading' is the default mode.
mode = 'threading'
elif mode not in spawn... | def function[spawn, parameter[mode, func]]:
constant[Spawns a thread-like object which runs the given function concurrently.
Available modes:
- `threading`
- `greenlet`
- `eventlet`
]
if compare[name[mode] is constant[None]] begin[:]
variable[mode] assign[=] consta... | keyword[def] identifier[spawn] ( identifier[mode] , identifier[func] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[mode] keyword[is] keyword[None] :
identifier[mode] = literal[string]
keyword[elif] identifier[mode] keyword[not] keyword[in] i... | def spawn(mode, func, *args, **kwargs):
"""Spawns a thread-like object which runs the given function concurrently.
Available modes:
- `threading`
- `greenlet`
- `eventlet`
"""
if mode is None:
# 'threading' is the default mode.
mode = 'threading' # depends on [control=['i... |
def _check_response_for_errors(self, response):
"""Checks the response for errors and raises one if any exists."""
try:
doc = minidom.parseString(_string(response).replace("opensearch:", ""))
except Exception as e:
raise MalformedResponseError(self.network, e)
e... | def function[_check_response_for_errors, parameter[self, response]]:
constant[Checks the response for errors and raises one if any exists.]
<ast.Try object at 0x7da1b0b656c0>
variable[e] assign[=] call[call[name[doc].getElementsByTagName, parameter[constant[lfm]]]][constant[0]]
if compare[ca... | keyword[def] identifier[_check_response_for_errors] ( identifier[self] , identifier[response] ):
literal[string]
keyword[try] :
identifier[doc] = identifier[minidom] . identifier[parseString] ( identifier[_string] ( identifier[response] ). identifier[replace] ( literal[string] , liter... | def _check_response_for_errors(self, response):
"""Checks the response for errors and raises one if any exists."""
try:
doc = minidom.parseString(_string(response).replace('opensearch:', '')) # depends on [control=['try'], data=[]]
except Exception as e:
raise MalformedResponseError(self.ne... |
def concordance_index_ipcw(survival_train, survival_test, estimate, tau=None, tied_tol=1e-8):
"""Concordance index for right-censored data based on inverse probability of censoring weights.
This is an alternative to the estimator in :func:`concordance_index_censored`
that does not depend on the distributio... | def function[concordance_index_ipcw, parameter[survival_train, survival_test, estimate, tau, tied_tol]]:
constant[Concordance index for right-censored data based on inverse probability of censoring weights.
This is an alternative to the estimator in :func:`concordance_index_censored`
that does not depe... | keyword[def] identifier[concordance_index_ipcw] ( identifier[survival_train] , identifier[survival_test] , identifier[estimate] , identifier[tau] = keyword[None] , identifier[tied_tol] = literal[int] ):
literal[string]
identifier[test_event] , identifier[test_time] = identifier[check_y_survival] ( identifi... | def concordance_index_ipcw(survival_train, survival_test, estimate, tau=None, tied_tol=1e-08):
"""Concordance index for right-censored data based on inverse probability of censoring weights.
This is an alternative to the estimator in :func:`concordance_index_censored`
that does not depend on the distributi... |
def _write_config(self, cfg, slot):
""" Write configuration to YubiKey. """
old_pgm_seq = self._status.pgm_seq
frame = cfg.to_frame(slot=slot)
self._debug("Writing %s frame :\n%s\n" % \
(yubikey_config.command2str(frame.command), cfg))
self._write(frame)
... | def function[_write_config, parameter[self, cfg, slot]]:
constant[ Write configuration to YubiKey. ]
variable[old_pgm_seq] assign[=] name[self]._status.pgm_seq
variable[frame] assign[=] call[name[cfg].to_frame, parameter[]]
call[name[self]._debug, parameter[binary_operation[constant[Writ... | keyword[def] identifier[_write_config] ( identifier[self] , identifier[cfg] , identifier[slot] ):
literal[string]
identifier[old_pgm_seq] = identifier[self] . identifier[_status] . identifier[pgm_seq]
identifier[frame] = identifier[cfg] . identifier[to_frame] ( identifier[slot] = identifi... | def _write_config(self, cfg, slot):
""" Write configuration to YubiKey. """
old_pgm_seq = self._status.pgm_seq
frame = cfg.to_frame(slot=slot)
self._debug('Writing %s frame :\n%s\n' % (yubikey_config.command2str(frame.command), cfg))
self._write(frame)
self._waitfor_clear(yubikey_defs.SLOT_WRITE... |
def _default(self, obj: object):
""" Return a serializable version of obj. Overrides JsonObj _default method
:param obj: Object to be serialized
:return: Serialized version of obj
"""
return None if obj is JSGNull else obj.val if type(obj) is AnyType else \
JSGObject.... | def function[_default, parameter[self, obj]]:
constant[ Return a serializable version of obj. Overrides JsonObj _default method
:param obj: Object to be serialized
:return: Serialized version of obj
]
return[<ast.IfExp object at 0x7da20c9915d0>] | keyword[def] identifier[_default] ( identifier[self] , identifier[obj] : identifier[object] ):
literal[string]
keyword[return] keyword[None] keyword[if] identifier[obj] keyword[is] identifier[JSGNull] keyword[else] identifier[obj] . identifier[val] keyword[if] identifier[type] ( identifier... | def _default(self, obj: object):
""" Return a serializable version of obj. Overrides JsonObj _default method
:param obj: Object to be serialized
:return: Serialized version of obj
"""
return None if obj is JSGNull else obj.val if type(obj) is AnyType else JSGObject._strip_nones(obj.__dic... |
def create_volume(zone_name, size=None, snapshot_id=None, volume_type=None,
iops=None, encrypted=False, kms_key_id=None, wait_for_creation=False,
region=None, key=None, keyid=None, profile=None):
'''
Create an EBS volume to an availability zone.
..
zone_name
... | def function[create_volume, parameter[zone_name, size, snapshot_id, volume_type, iops, encrypted, kms_key_id, wait_for_creation, region, key, keyid, profile]]:
constant[
Create an EBS volume to an availability zone.
..
zone_name
(string) – The Availability zone name of the EBS volume to be... | keyword[def] identifier[create_volume] ( identifier[zone_name] , identifier[size] = keyword[None] , identifier[snapshot_id] = keyword[None] , identifier[volume_type] = keyword[None] ,
identifier[iops] = keyword[None] , identifier[encrypted] = keyword[False] , identifier[kms_key_id] = keyword[None] , identifier[wait_... | def create_volume(zone_name, size=None, snapshot_id=None, volume_type=None, iops=None, encrypted=False, kms_key_id=None, wait_for_creation=False, region=None, key=None, keyid=None, profile=None):
"""
Create an EBS volume to an availability zone.
..
zone_name
(string) – The Availability zone na... |
def imag(self):
"""Imaginary part of ``self``.
Returns
-------
imag : `NumpyTensor`
Imaginary part this element as an element of a
`NumpyTensorSpace` with real data type.
Examples
--------
Get the imaginary part:
>>> space = odl.... | def function[imag, parameter[self]]:
constant[Imaginary part of ``self``.
Returns
-------
imag : `NumpyTensor`
Imaginary part this element as an element of a
`NumpyTensorSpace` with real data type.
Examples
--------
Get the imaginary part... | keyword[def] identifier[imag] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[space] . identifier[is_real] :
keyword[return] identifier[self] . identifier[space] . identifier[zero] ()
keyword[elif] identifier[self] . identifier[space] . ident... | def imag(self):
"""Imaginary part of ``self``.
Returns
-------
imag : `NumpyTensor`
Imaginary part this element as an element of a
`NumpyTensorSpace` with real data type.
Examples
--------
Get the imaginary part:
>>> space = odl.cn(3... |
def list_command_pydb(self, arg):
"""List command to use if we have a newer pydb installed"""
filename, first, last = OldPdb.parse_list_cmd(self, arg)
if filename is not None:
self.print_list_lines(filename, first, last) | def function[list_command_pydb, parameter[self, arg]]:
constant[List command to use if we have a newer pydb installed]
<ast.Tuple object at 0x7da204346bc0> assign[=] call[name[OldPdb].parse_list_cmd, parameter[name[self], name[arg]]]
if compare[name[filename] is_not constant[None]] begin[:]
... | keyword[def] identifier[list_command_pydb] ( identifier[self] , identifier[arg] ):
literal[string]
identifier[filename] , identifier[first] , identifier[last] = identifier[OldPdb] . identifier[parse_list_cmd] ( identifier[self] , identifier[arg] )
keyword[if] identifier[filename] keyword... | def list_command_pydb(self, arg):
"""List command to use if we have a newer pydb installed"""
(filename, first, last) = OldPdb.parse_list_cmd(self, arg)
if filename is not None:
self.print_list_lines(filename, first, last) # depends on [control=['if'], data=['filename']] |
def _validate_time_range(trange, status, msg):
'''
Check time range
'''
# If trange is empty, just return the current status & msg
if not trange:
return status, msg
if not isinstance(trange, dict):
status = False
msg = ('The time_range parameter for '
'wtm... | def function[_validate_time_range, parameter[trange, status, msg]]:
constant[
Check time range
]
if <ast.UnaryOp object at 0x7da1b217d960> begin[:]
return[tuple[[<ast.Name object at 0x7da1b217dc00>, <ast.Name object at 0x7da1b217c490>]]]
if <ast.UnaryOp object at 0x7da1b217cc40> ... | keyword[def] identifier[_validate_time_range] ( identifier[trange] , identifier[status] , identifier[msg] ):
literal[string]
keyword[if] keyword[not] identifier[trange] :
keyword[return] identifier[status] , identifier[msg]
keyword[if] keyword[not] identifier[isinstance] ( identif... | def _validate_time_range(trange, status, msg):
"""
Check time range
"""
# If trange is empty, just return the current status & msg
if not trange:
return (status, msg) # depends on [control=['if'], data=[]]
if not isinstance(trange, dict):
status = False
msg = 'The time_r... |
def lookup_blob(hash_value):
"""
Combines all given arguments to create clean title-tags values.
All arguments are divided by a " " seperator and HTML tags
are to be removed.
"""
try:
blob = BlobStorage.objects.get(sha256=hash_value)
except:
return "Blob not found"
return... | def function[lookup_blob, parameter[hash_value]]:
constant[
Combines all given arguments to create clean title-tags values.
All arguments are divided by a " " seperator and HTML tags
are to be removed.
]
<ast.Try object at 0x7da1b16d71c0>
return[name[blob].content] | keyword[def] identifier[lookup_blob] ( identifier[hash_value] ):
literal[string]
keyword[try] :
identifier[blob] = identifier[BlobStorage] . identifier[objects] . identifier[get] ( identifier[sha256] = identifier[hash_value] )
keyword[except] :
keyword[return] literal[string]
... | def lookup_blob(hash_value):
"""
Combines all given arguments to create clean title-tags values.
All arguments are divided by a " " seperator and HTML tags
are to be removed.
"""
try:
blob = BlobStorage.objects.get(sha256=hash_value) # depends on [control=['try'], data=[]]
except:
... |
def data_uri(thumbnail):
"""
This filter will return the base64 encoded data URI for a given thumbnail object.
Example usage::
{% thumbnail sample_image 25x25 crop as thumb %}
<img src="{{ thumb|data_uri }}">
will for instance be rendered as:
<img src="data:image/png;base64,i... | def function[data_uri, parameter[thumbnail]]:
constant[
This filter will return the base64 encoded data URI for a given thumbnail object.
Example usage::
{% thumbnail sample_image 25x25 crop as thumb %}
<img src="{{ thumb|data_uri }}">
will for instance be rendered as:
<i... | keyword[def] identifier[data_uri] ( identifier[thumbnail] ):
literal[string]
keyword[try] :
identifier[thumbnail] . identifier[open] ( literal[string] )
identifier[data] = identifier[thumbnail] . identifier[read] ()
keyword[finally] :
identifier[thumbnail] . identifier[close... | def data_uri(thumbnail):
"""
This filter will return the base64 encoded data URI for a given thumbnail object.
Example usage::
{% thumbnail sample_image 25x25 crop as thumb %}
<img src="{{ thumb|data_uri }}">
will for instance be rendered as:
<img src="data:image/png;base64,i... |
def get_offset_range(self, row_offset, column_offset):
"""
Gets an object which represents a range that's offset from the specified range.
The dimension of the returned range will match this range.
If the resulting range is forced outside the bounds of the worksheet grid,
an ... | def function[get_offset_range, parameter[self, row_offset, column_offset]]:
constant[
Gets an object which represents a range that's offset from the specified range.
The dimension of the returned range will match this range.
If the resulting range is forced outside the bounds of the wo... | keyword[def] identifier[get_offset_range] ( identifier[self] , identifier[row_offset] , identifier[column_offset] ):
literal[string]
keyword[return] identifier[self] . identifier[_get_range] ( literal[string] , identifier[rowOffset] = identifier[row_offset] , identifier[columnOffset] = identifier[... | def get_offset_range(self, row_offset, column_offset):
"""
Gets an object which represents a range that's offset from the specified range.
The dimension of the returned range will match this range.
If the resulting range is forced outside the bounds of the worksheet grid,
an exce... |
def inverse(self):
"""Return the (left) inverse.
If the domain is a real space, this is not a true inverse,
only a (left) inverse.
Examples
--------
>>> r3 = odl.rn(3)
>>> op = ComplexEmbedding(r3, scalar=1)
>>> op.inverse(op([1, 2, 4]))
rn(3).el... | def function[inverse, parameter[self]]:
constant[Return the (left) inverse.
If the domain is a real space, this is not a true inverse,
only a (left) inverse.
Examples
--------
>>> r3 = odl.rn(3)
>>> op = ComplexEmbedding(r3, scalar=1)
>>> op.inverse(op([... | keyword[def] identifier[inverse] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[domain] . identifier[is_real] :
keyword[if] identifier[self] . identifier[scalar] . identifier[real] == identifier[self] . identifier[scalar] :
... | def inverse(self):
"""Return the (left) inverse.
If the domain is a real space, this is not a true inverse,
only a (left) inverse.
Examples
--------
>>> r3 = odl.rn(3)
>>> op = ComplexEmbedding(r3, scalar=1)
>>> op.inverse(op([1, 2, 4]))
rn(3).elemen... |
def mass2_from_tau0_tau3(tau0, tau3, f_lower):
r"""Returns the secondary mass from the given :math:`\tau_0, \tau_3`."""
mtotal = mtotal_from_tau0_tau3(tau0, tau3, f_lower)
eta = eta_from_tau0_tau3(tau0, tau3, f_lower)
return mass2_from_mtotal_eta(mtotal, eta) | def function[mass2_from_tau0_tau3, parameter[tau0, tau3, f_lower]]:
constant[Returns the secondary mass from the given :math:`\tau_0, \tau_3`.]
variable[mtotal] assign[=] call[name[mtotal_from_tau0_tau3], parameter[name[tau0], name[tau3], name[f_lower]]]
variable[eta] assign[=] call[name[eta_fro... | keyword[def] identifier[mass2_from_tau0_tau3] ( identifier[tau0] , identifier[tau3] , identifier[f_lower] ):
literal[string]
identifier[mtotal] = identifier[mtotal_from_tau0_tau3] ( identifier[tau0] , identifier[tau3] , identifier[f_lower] )
identifier[eta] = identifier[eta_from_tau0_tau3] ( identifie... | def mass2_from_tau0_tau3(tau0, tau3, f_lower):
"""Returns the secondary mass from the given :math:`\\tau_0, \\tau_3`."""
mtotal = mtotal_from_tau0_tau3(tau0, tau3, f_lower)
eta = eta_from_tau0_tau3(tau0, tau3, f_lower)
return mass2_from_mtotal_eta(mtotal, eta) |
def backend_query(self, **kwargs):
'''Build and return the :class:`stdnet.utils.async.BackendQuery`.
This is a lazy method in the sense that it is evaluated once only and its
result stored for future retrieval.'''
q = self.construct()
return q if isinstance(q, EmptyQuery) else q.backend_que... | def function[backend_query, parameter[self]]:
constant[Build and return the :class:`stdnet.utils.async.BackendQuery`.
This is a lazy method in the sense that it is evaluated once only and its
result stored for future retrieval.]
variable[q] assign[=] call[name[self].construct, parameter[]]
return[<a... | keyword[def] identifier[backend_query] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[q] = identifier[self] . identifier[construct] ()
keyword[return] identifier[q] keyword[if] identifier[isinstance] ( identifier[q] , identifier[EmptyQuery] ) keyword[else] i... | def backend_query(self, **kwargs):
"""Build and return the :class:`stdnet.utils.async.BackendQuery`.
This is a lazy method in the sense that it is evaluated once only and its
result stored for future retrieval."""
q = self.construct()
return q if isinstance(q, EmptyQuery) else q.backend_query(**kwargs) |
def _handle_stop_dag(self, request):
""" The handler for the stop_dag request.
The stop_dag request adds a dag to the list of dags that should be stopped.
The dag will then stop queueing new tasks and will eventually stop running.
Args:
request (Request): Reference to a req... | def function[_handle_stop_dag, parameter[self, request]]:
constant[ The handler for the stop_dag request.
The stop_dag request adds a dag to the list of dags that should be stopped.
The dag will then stop queueing new tasks and will eventually stop running.
Args:
request (R... | keyword[def] identifier[_handle_stop_dag] ( identifier[self] , identifier[request] ):
literal[string]
keyword[if] ( identifier[request] . identifier[payload] [ literal[string] ] keyword[is] keyword[not] keyword[None] ) keyword[and] ( identifier[request] . identifier[payload] [ literal[string] ] k... | def _handle_stop_dag(self, request):
""" The handler for the stop_dag request.
The stop_dag request adds a dag to the list of dags that should be stopped.
The dag will then stop queueing new tasks and will eventually stop running.
Args:
request (Request): Reference to a request... |
def to_array(self):
"""
Serializes this InlineKeyboardButton to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineKeyboardButton, self).to_array()
array['text'] = u(self.text) # py2: type unicode, py3: type str... | def function[to_array, parameter[self]]:
constant[
Serializes this InlineKeyboardButton to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
]
variable[array] assign[=] call[call[name[super], parameter[name[InlineKeyboardButton], name[self]]].... | keyword[def] identifier[to_array] ( identifier[self] ):
literal[string]
identifier[array] = identifier[super] ( identifier[InlineKeyboardButton] , identifier[self] ). identifier[to_array] ()
identifier[array] [ literal[string] ]= identifier[u] ( identifier[self] . identifier[text] )
... | def to_array(self):
"""
Serializes this InlineKeyboardButton to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineKeyboardButton, self).to_array()
array['text'] = u(self.text) # py2: type unicode, py3: type str
if self... |
def post_struct(UserStruct):
"""
Post Model
"""
db = UserStruct.User.db
class SlugNameMixin(object):
name = db.Column(db.String(250))
slug = db.Column(db.String(250), index=True, unique=True)
@classmethod
def get_by_slug(cls, slug):
"""
Ret... | def function[post_struct, parameter[UserStruct]]:
constant[
Post Model
]
variable[db] assign[=] name[UserStruct].User.db
class class[SlugNameMixin, parameter[]] begin[:]
variable[name] assign[=] call[name[db].Column, parameter[call[name[db].String, parameter[constant[250... | keyword[def] identifier[post_struct] ( identifier[UserStruct] ):
literal[string]
identifier[db] = identifier[UserStruct] . identifier[User] . identifier[db]
keyword[class] identifier[SlugNameMixin] ( identifier[object] ):
identifier[name] = identifier[db] . identifier[Column] ( identifier... | def post_struct(UserStruct):
"""
Post Model
"""
db = UserStruct.User.db
class SlugNameMixin(object):
name = db.Column(db.String(250))
slug = db.Column(db.String(250), index=True, unique=True)
@classmethod
def get_by_slug(cls, slug):
"""
Retu... |
def flatten_all(list_of_list):
"""Flatten arbitrary depth of nesting. Good for unknown nesting structure
iterable object.
Usage::
>>> flatten_all([[0, 1], [2, 3, [4, 5], [6, 7, 8]], [9,]])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
"""
for i in list_of_list:
if hasattr(i, "__iter__"):
... | def function[flatten_all, parameter[list_of_list]]:
constant[Flatten arbitrary depth of nesting. Good for unknown nesting structure
iterable object.
Usage::
>>> flatten_all([[0, 1], [2, 3, [4, 5], [6, 7, 8]], [9,]])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
]
for taget[name[i]] in sta... | keyword[def] identifier[flatten_all] ( identifier[list_of_list] ):
literal[string]
keyword[for] identifier[i] keyword[in] identifier[list_of_list] :
keyword[if] identifier[hasattr] ( identifier[i] , literal[string] ):
keyword[for] identifier[j] keyword[in] identifier[flatten_al... | def flatten_all(list_of_list):
"""Flatten arbitrary depth of nesting. Good for unknown nesting structure
iterable object.
Usage::
>>> flatten_all([[0, 1], [2, 3, [4, 5], [6, 7, 8]], [9,]])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
"""
for i in list_of_list:
if hasattr(i, '__iter__'):
... |
def convert_fully_connected(node, **kwargs):
"""Map MXNet's FullyConnected operator attributes to onnx's Gemm operator
and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
initializer = kwargs["initializer"]
no_bias = get_boolean_attribute_value(attrs, "no_bias"... | def function[convert_fully_connected, parameter[node]]:
constant[Map MXNet's FullyConnected operator attributes to onnx's Gemm operator
and return the created node.
]
<ast.Tuple object at 0x7da1b1ef1cc0> assign[=] call[name[get_inputs], parameter[name[node], name[kwargs]]]
variable[initi... | keyword[def] identifier[convert_fully_connected] ( identifier[node] ,** identifier[kwargs] ):
literal[string]
identifier[name] , identifier[input_nodes] , identifier[attrs] = identifier[get_inputs] ( identifier[node] , identifier[kwargs] )
identifier[initializer] = identifier[kwargs] [ literal[string... | def convert_fully_connected(node, **kwargs):
"""Map MXNet's FullyConnected operator attributes to onnx's Gemm operator
and return the created node.
"""
(name, input_nodes, attrs) = get_inputs(node, kwargs)
initializer = kwargs['initializer']
no_bias = get_boolean_attribute_value(attrs, 'no_bias'... |
def add_firewalld_port(port, permanent=True):
""" adds a firewall rule """
yum_install(packages=['firewalld'])
log_green('adding a new fw rule: %s' % port)
with settings(hide('warnings', 'running', 'stdout', 'stderr'),
warn_only=True, capture=True):
p = ''
if permanen... | def function[add_firewalld_port, parameter[port, permanent]]:
constant[ adds a firewall rule ]
call[name[yum_install], parameter[]]
call[name[log_green], parameter[binary_operation[constant[adding a new fw rule: %s] <ast.Mod object at 0x7da2590d6920> name[port]]]]
with call[name[settings... | keyword[def] identifier[add_firewalld_port] ( identifier[port] , identifier[permanent] = keyword[True] ):
literal[string]
identifier[yum_install] ( identifier[packages] =[ literal[string] ])
identifier[log_green] ( literal[string] % identifier[port] )
keyword[with] identifier[settings] ( ident... | def add_firewalld_port(port, permanent=True):
""" adds a firewall rule """
yum_install(packages=['firewalld'])
log_green('adding a new fw rule: %s' % port)
with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True, capture=True):
p = ''
if permanent:
p = '... |
def sample(self, features):
"""Run the model and extract samples.
Args:
features: an map of string to `Tensor`.
Returns:
samples: an integer `Tensor`.
logits: a list of `Tensor`s, one per datashard.
losses: a dictionary: {loss-name (string): floating point `Scalar`}.
"""
... | def function[sample, parameter[self, features]]:
constant[Run the model and extract samples.
Args:
features: an map of string to `Tensor`.
Returns:
samples: an integer `Tensor`.
logits: a list of `Tensor`s, one per datashard.
losses: a dictionary: {loss-name (string): floati... | keyword[def] identifier[sample] ( identifier[self] , identifier[features] ):
literal[string]
identifier[logits] , identifier[losses] = identifier[self] ( identifier[features] )
keyword[if] identifier[self] . identifier[_target_modality_is_real] :
keyword[return] identifier[logits] , identifie... | def sample(self, features):
"""Run the model and extract samples.
Args:
features: an map of string to `Tensor`.
Returns:
samples: an integer `Tensor`.
logits: a list of `Tensor`s, one per datashard.
losses: a dictionary: {loss-name (string): floating point `Scalar`}.
"""
... |
def _build(self, *args):
"""Connects the Sequential module into the graph.
Args:
*args: A tuple of inputs, to be unpacked as the arguments to the first
layer.
Returns:
The output value of the last layer.
"""
net = args
if not self._layers:
# If the sequential is pa... | def function[_build, parameter[self]]:
constant[Connects the Sequential module into the graph.
Args:
*args: A tuple of inputs, to be unpacked as the arguments to the first
layer.
Returns:
The output value of the last layer.
]
variable[net] assign[=] name[args]
... | keyword[def] identifier[_build] ( identifier[self] ,* identifier[args] ):
literal[string]
identifier[net] = identifier[args]
keyword[if] keyword[not] identifier[self] . identifier[_layers] :
keyword[if] identifier[len] ( identifier[args] )== literal[int] :
keyw... | def _build(self, *args):
"""Connects the Sequential module into the graph.
Args:
*args: A tuple of inputs, to be unpacked as the arguments to the first
layer.
Returns:
The output value of the last layer.
"""
net = args
if not self._layers:
# If the sequential is p... |
def get_element_by_class_name_or_raise(self, class_name):
"""Return the SchemaElement for the specified class name, asserting that it exists."""
if class_name not in self._elements:
raise InvalidClassError(u'Class does not exist: {}'.format(class_name))
return self._elements[class_n... | def function[get_element_by_class_name_or_raise, parameter[self, class_name]]:
constant[Return the SchemaElement for the specified class name, asserting that it exists.]
if compare[name[class_name] <ast.NotIn object at 0x7da2590d7190> name[self]._elements] begin[:]
<ast.Raise object at 0x7da2045... | keyword[def] identifier[get_element_by_class_name_or_raise] ( identifier[self] , identifier[class_name] ):
literal[string]
keyword[if] identifier[class_name] keyword[not] keyword[in] identifier[self] . identifier[_elements] :
keyword[raise] identifier[InvalidClassError] ( literal[... | def get_element_by_class_name_or_raise(self, class_name):
"""Return the SchemaElement for the specified class name, asserting that it exists."""
if class_name not in self._elements:
raise InvalidClassError(u'Class does not exist: {}'.format(class_name)) # depends on [control=['if'], data=['class_name']... |
def record_migration(plugin, filename, script, **kwargs):
'''Only record a migration without applying it'''
db = get_db()
db.eval(RECORD_WRAPPER, plugin, filename, script)
return True | def function[record_migration, parameter[plugin, filename, script]]:
constant[Only record a migration without applying it]
variable[db] assign[=] call[name[get_db], parameter[]]
call[name[db].eval, parameter[name[RECORD_WRAPPER], name[plugin], name[filename], name[script]]]
return[constant[T... | keyword[def] identifier[record_migration] ( identifier[plugin] , identifier[filename] , identifier[script] ,** identifier[kwargs] ):
literal[string]
identifier[db] = identifier[get_db] ()
identifier[db] . identifier[eval] ( identifier[RECORD_WRAPPER] , identifier[plugin] , identifier[filename] , ident... | def record_migration(plugin, filename, script, **kwargs):
"""Only record a migration without applying it"""
db = get_db()
db.eval(RECORD_WRAPPER, plugin, filename, script)
return True |
def set_paths_caching_params(self, timeout=None, cache_name=None):
"""Use the uWSGI caching subsystem to store mappings from URI to filesystem paths.
* http://uwsgi.readthedocs.io/en/latest/StaticFiles.html#caching-paths-mappings-resolutions
:param int timeout: Amount of seconds to put resolve... | def function[set_paths_caching_params, parameter[self, timeout, cache_name]]:
constant[Use the uWSGI caching subsystem to store mappings from URI to filesystem paths.
* http://uwsgi.readthedocs.io/en/latest/StaticFiles.html#caching-paths-mappings-resolutions
:param int timeout: Amount of secon... | keyword[def] identifier[set_paths_caching_params] ( identifier[self] , identifier[timeout] = keyword[None] , identifier[cache_name] = keyword[None] ):
literal[string]
identifier[self] . identifier[_set] ( literal[string] , identifier[timeout] )
identifier[self] . identifier[_set] ( literal... | def set_paths_caching_params(self, timeout=None, cache_name=None):
"""Use the uWSGI caching subsystem to store mappings from URI to filesystem paths.
* http://uwsgi.readthedocs.io/en/latest/StaticFiles.html#caching-paths-mappings-resolutions
:param int timeout: Amount of seconds to put resolved pa... |
def activate_firmware_and_wait(self, rollback_override=None,
timeout=2, interval=1):
""" Activate the new uploaded firmware and wait for
long running command. """
try:
self.activate_firmware(rollback_override)
except CompletionCodeError ... | def function[activate_firmware_and_wait, parameter[self, rollback_override, timeout, interval]]:
constant[ Activate the new uploaded firmware and wait for
long running command. ]
<ast.Try object at 0x7da1b077a800> | keyword[def] identifier[activate_firmware_and_wait] ( identifier[self] , identifier[rollback_override] = keyword[None] ,
identifier[timeout] = literal[int] , identifier[interval] = literal[int] ):
literal[string]
keyword[try] :
identifier[self] . identifier[activate_firmware] ( identi... | def activate_firmware_and_wait(self, rollback_override=None, timeout=2, interval=1):
""" Activate the new uploaded firmware and wait for
long running command. """
try:
self.activate_firmware(rollback_override) # depends on [control=['try'], data=[]]
except CompletionCodeError as e:
... |
def search(self, query, *, max_results=100, **kwargs):
"""Search Google Music and library for content.
Parameters:
query (str): Search text.
max_results (int, Optional): Maximum number of results per type per
location to retrieve. I.e up to 100 Google and 100 library
for a total of 200 for the defaul... | def function[search, parameter[self, query]]:
constant[Search Google Music and library for content.
Parameters:
query (str): Search text.
max_results (int, Optional): Maximum number of results per type per
location to retrieve. I.e up to 100 Google and 100 library
for a total of 200 for the def... | keyword[def] identifier[search] ( identifier[self] , identifier[query] ,*, identifier[max_results] = literal[int] ,** identifier[kwargs] ):
literal[string]
identifier[results] = identifier[defaultdict] ( identifier[list] )
keyword[for] identifier[type_] , identifier[results_] keyword[in] identifier[sel... | def search(self, query, *, max_results=100, **kwargs):
"""Search Google Music and library for content.
Parameters:
query (str): Search text.
max_results (int, Optional): Maximum number of results per type per
location to retrieve. I.e up to 100 Google and 100 library
for a total of 200 for the defa... |
def get_urls_and_locations(self, urls):
"""Get URLs and their redirection addresses.
:param urls: a list of URL addresses
:returns: an instance of CachedIterable containing given URLs
and valid location header values of their responses
"""
location_generator = self.get_n... | def function[get_urls_and_locations, parameter[self, urls]]:
constant[Get URLs and their redirection addresses.
:param urls: a list of URL addresses
:returns: an instance of CachedIterable containing given URLs
and valid location header values of their responses
]
variab... | keyword[def] identifier[get_urls_and_locations] ( identifier[self] , identifier[urls] ):
literal[string]
identifier[location_generator] = identifier[self] . identifier[get_new_locations] ( identifier[urls] )
identifier[initial_cache] = identifier[list] ( identifier[set] ( identifier[urls] ... | def get_urls_and_locations(self, urls):
"""Get URLs and their redirection addresses.
:param urls: a list of URL addresses
:returns: an instance of CachedIterable containing given URLs
and valid location header values of their responses
"""
location_generator = self.get_new_locat... |
def plotting_context(context=None, font_scale=1, rc=None):
"""Return a parameter dict to scale elements of the figure.
This affects things like the size of the labels, lines, and other
elements of the plot, but not the overall style. The base context
is "notebook", and the other contexts are "paper", "t... | def function[plotting_context, parameter[context, font_scale, rc]]:
constant[Return a parameter dict to scale elements of the figure.
This affects things like the size of the labels, lines, and other
elements of the plot, but not the overall style. The base context
is "notebook", and the other conte... | keyword[def] identifier[plotting_context] ( identifier[context] = keyword[None] , identifier[font_scale] = literal[int] , identifier[rc] = keyword[None] ):
literal[string]
keyword[if] identifier[context] keyword[is] keyword[None] :
identifier[context_dict] ={ identifier[k] : identifier[mpl] . i... | def plotting_context(context=None, font_scale=1, rc=None):
"""Return a parameter dict to scale elements of the figure.
This affects things like the size of the labels, lines, and other
elements of the plot, but not the overall style. The base context
is "notebook", and the other contexts are "paper", "t... |
def _check_all_deps(self, pkg_name=None, pkg_file=None, formula_def=None):
'''
Starting with one package, check all packages for dependencies
'''
if pkg_file and not os.path.exists(pkg_file):
raise SPMInvocationError('Package file {0} not found'.format(pkg_file))
sel... | def function[_check_all_deps, parameter[self, pkg_name, pkg_file, formula_def]]:
constant[
Starting with one package, check all packages for dependencies
]
if <ast.BoolOp object at 0x7da20c6a8370> begin[:]
<ast.Raise object at 0x7da20c6a8eb0>
name[self].repo_metadata assi... | keyword[def] identifier[_check_all_deps] ( identifier[self] , identifier[pkg_name] = keyword[None] , identifier[pkg_file] = keyword[None] , identifier[formula_def] = keyword[None] ):
literal[string]
keyword[if] identifier[pkg_file] keyword[and] keyword[not] identifier[os] . identifier[path] . i... | def _check_all_deps(self, pkg_name=None, pkg_file=None, formula_def=None):
"""
Starting with one package, check all packages for dependencies
"""
if pkg_file and (not os.path.exists(pkg_file)):
raise SPMInvocationError('Package file {0} not found'.format(pkg_file)) # depends on [control... |
def update_module_item(self, id, course_id, module_id, module_item_completion_requirement_min_score=None, module_item_completion_requirement_type=None, module_item_external_url=None, module_item_indent=None, module_item_module_id=None, module_item_new_tab=None, module_item_position=None, module_item_published=None, mod... | def function[update_module_item, parameter[self, id, course_id, module_id, module_item_completion_requirement_min_score, module_item_completion_requirement_type, module_item_external_url, module_item_indent, module_item_module_id, module_item_new_tab, module_item_position, module_item_published, module_item_title]]:
... | keyword[def] identifier[update_module_item] ( identifier[self] , identifier[id] , identifier[course_id] , identifier[module_id] , identifier[module_item_completion_requirement_min_score] = keyword[None] , identifier[module_item_completion_requirement_type] = keyword[None] , identifier[module_item_external_url] = keyw... | def update_module_item(self, id, course_id, module_id, module_item_completion_requirement_min_score=None, module_item_completion_requirement_type=None, module_item_external_url=None, module_item_indent=None, module_item_module_id=None, module_item_new_tab=None, module_item_position=None, module_item_published=None, mod... |
def fw_rule_delete(self, data, fw_name=None):
"""Top level rule delete function. """
LOG.debug("FW Rule delete %s", data)
self._fw_rule_delete(fw_name, data) | def function[fw_rule_delete, parameter[self, data, fw_name]]:
constant[Top level rule delete function. ]
call[name[LOG].debug, parameter[constant[FW Rule delete %s], name[data]]]
call[name[self]._fw_rule_delete, parameter[name[fw_name], name[data]]] | keyword[def] identifier[fw_rule_delete] ( identifier[self] , identifier[data] , identifier[fw_name] = keyword[None] ):
literal[string]
identifier[LOG] . identifier[debug] ( literal[string] , identifier[data] )
identifier[self] . identifier[_fw_rule_delete] ( identifier[fw_name] , identifie... | def fw_rule_delete(self, data, fw_name=None):
"""Top level rule delete function. """
LOG.debug('FW Rule delete %s', data)
self._fw_rule_delete(fw_name, data) |
def apply_relationships(self, data, obj):
"""Apply relationship provided by data to obj
:param dict data: data provided by the client
:param DeclarativeMeta obj: the sqlalchemy object to plug relationships to
:return boolean: True if relationship have changed else False
"""
... | def function[apply_relationships, parameter[self, data, obj]]:
constant[Apply relationship provided by data to obj
:param dict data: data provided by the client
:param DeclarativeMeta obj: the sqlalchemy object to plug relationships to
:return boolean: True if relationship have changed ... | keyword[def] identifier[apply_relationships] ( identifier[self] , identifier[data] , identifier[obj] ):
literal[string]
identifier[relationships_to_apply] =[]
identifier[relationship_fields] = identifier[get_relationships] ( identifier[self] . identifier[resource] . identifier[schema] , id... | def apply_relationships(self, data, obj):
"""Apply relationship provided by data to obj
:param dict data: data provided by the client
:param DeclarativeMeta obj: the sqlalchemy object to plug relationships to
:return boolean: True if relationship have changed else False
"""
rela... |
def long_press(self, locator, duration=1000):
""" Long press the element with optional duration """
driver = self._current_application()
element = self._element_find(locator, True, True)
action = TouchAction(driver)
action.press(element).wait(duration).release().perform() | def function[long_press, parameter[self, locator, duration]]:
constant[ Long press the element with optional duration ]
variable[driver] assign[=] call[name[self]._current_application, parameter[]]
variable[element] assign[=] call[name[self]._element_find, parameter[name[locator], constant[True]... | keyword[def] identifier[long_press] ( identifier[self] , identifier[locator] , identifier[duration] = literal[int] ):
literal[string]
identifier[driver] = identifier[self] . identifier[_current_application] ()
identifier[element] = identifier[self] . identifier[_element_find] ( identifi... | def long_press(self, locator, duration=1000):
""" Long press the element with optional duration """
driver = self._current_application()
element = self._element_find(locator, True, True)
action = TouchAction(driver)
action.press(element).wait(duration).release().perform() |
def find_library_linux(cls):
"""Loads the SEGGER DLL from the root directory.
On Linux, the SEGGER tools are installed under the ``/opt/SEGGER``
directory with versioned directories having the suffix ``_VERSION``.
Args:
cls (Library): the ``Library`` class
Returns:
... | def function[find_library_linux, parameter[cls]]:
constant[Loads the SEGGER DLL from the root directory.
On Linux, the SEGGER tools are installed under the ``/opt/SEGGER``
directory with versioned directories having the suffix ``_VERSION``.
Args:
cls (Library): the ``Library`... | keyword[def] identifier[find_library_linux] ( identifier[cls] ):
literal[string]
identifier[dll] = identifier[Library] . identifier[JLINK_SDK_NAME]
identifier[root] = identifier[os] . identifier[path] . identifier[join] ( literal[string] , literal[string] , literal[string] )
key... | def find_library_linux(cls):
"""Loads the SEGGER DLL from the root directory.
On Linux, the SEGGER tools are installed under the ``/opt/SEGGER``
directory with versioned directories having the suffix ``_VERSION``.
Args:
cls (Library): the ``Library`` class
Returns:
... |
def set_locked_variable(self, key, access_key, value):
"""Set an already locked global variable
:param key: the key of the global variable to be set
:param access_key: the access key to the already locked global variable
:param value: the new value of the global variable
"""
... | def function[set_locked_variable, parameter[self, key, access_key, value]]:
constant[Set an already locked global variable
:param key: the key of the global variable to be set
:param access_key: the access key to the already locked global variable
:param value: the new value of the glob... | keyword[def] identifier[set_locked_variable] ( identifier[self] , identifier[key] , identifier[access_key] , identifier[value] ):
literal[string]
keyword[return] identifier[self] . identifier[set_variable] ( identifier[key] , identifier[value] , identifier[per_reference] = keyword[False] , identif... | def set_locked_variable(self, key, access_key, value):
"""Set an already locked global variable
:param key: the key of the global variable to be set
:param access_key: the access key to the already locked global variable
:param value: the new value of the global variable
"""
ret... |
def zoom_in(self, increment=1):
"""
Zooms in the editor (makes the font bigger).
:param increment: zoom level increment. Default is 1.
"""
self.zoom_level += increment
TextHelper(self).mark_whole_doc_dirty()
self._reset_stylesheet() | def function[zoom_in, parameter[self, increment]]:
constant[
Zooms in the editor (makes the font bigger).
:param increment: zoom level increment. Default is 1.
]
<ast.AugAssign object at 0x7da18f720a90>
call[call[name[TextHelper], parameter[name[self]]].mark_whole_doc_dirty,... | keyword[def] identifier[zoom_in] ( identifier[self] , identifier[increment] = literal[int] ):
literal[string]
identifier[self] . identifier[zoom_level] += identifier[increment]
identifier[TextHelper] ( identifier[self] ). identifier[mark_whole_doc_dirty] ()
identifier[self] . ide... | def zoom_in(self, increment=1):
"""
Zooms in the editor (makes the font bigger).
:param increment: zoom level increment. Default is 1.
"""
self.zoom_level += increment
TextHelper(self).mark_whole_doc_dirty()
self._reset_stylesheet() |
def _reduction_output_shape(x, output_shape, reduced_dim):
"""Helper function to reduce_sum, etc."""
if output_shape is None:
if reduced_dim is None:
return Shape([])
else:
if reduced_dim not in x.shape.dims:
raise ValueError(
"reduced_dim=%s not in x.shape.dims=%s" % (reduce... | def function[_reduction_output_shape, parameter[x, output_shape, reduced_dim]]:
constant[Helper function to reduce_sum, etc.]
if compare[name[output_shape] is constant[None]] begin[:]
if compare[name[reduced_dim] is constant[None]] begin[:]
return[call[name[Shape], parameter[... | keyword[def] identifier[_reduction_output_shape] ( identifier[x] , identifier[output_shape] , identifier[reduced_dim] ):
literal[string]
keyword[if] identifier[output_shape] keyword[is] keyword[None] :
keyword[if] identifier[reduced_dim] keyword[is] keyword[None] :
keyword[return] identifier... | def _reduction_output_shape(x, output_shape, reduced_dim):
"""Helper function to reduce_sum, etc."""
if output_shape is None:
if reduced_dim is None:
return Shape([]) # depends on [control=['if'], data=[]]
else:
if reduced_dim not in x.shape.dims:
raise V... |
def wordify(self):
"""
Constructs string of all documents.
:return: document representation of the dataset, one line per document
:rtype: str
"""
string_documents = []
for klass, document in zip(self.resulting_classes, self.resulting_documents):
... | def function[wordify, parameter[self]]:
constant[
Constructs string of all documents.
:return: document representation of the dataset, one line per document
:rtype: str
]
variable[string_documents] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0... | keyword[def] identifier[wordify] ( identifier[self] ):
literal[string]
identifier[string_documents] =[]
keyword[for] identifier[klass] , identifier[document] keyword[in] identifier[zip] ( identifier[self] . identifier[resulting_classes] , identifier[self] . identifier[resulting_document... | def wordify(self):
"""
Constructs string of all documents.
:return: document representation of the dataset, one line per document
:rtype: str
"""
string_documents = []
for (klass, document) in zip(self.resulting_classes, self.resulting_documents):
string_docu... |
def get_package_format_names(predicate=None):
"""Get names for available package formats."""
return [
k
for k, v in six.iteritems(get_package_formats())
if not predicate or predicate(k, v)
] | def function[get_package_format_names, parameter[predicate]]:
constant[Get names for available package formats.]
return[<ast.ListComp object at 0x7da1b19c10f0>] | keyword[def] identifier[get_package_format_names] ( identifier[predicate] = keyword[None] ):
literal[string]
keyword[return] [
identifier[k]
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[six] . identifier[iteritems] ( identifier[get_package_formats] ())
keyword[if] k... | def get_package_format_names(predicate=None):
"""Get names for available package formats."""
return [k for (k, v) in six.iteritems(get_package_formats()) if not predicate or predicate(k, v)] |
def is_gvcf_file(in_file):
"""Check if an input file is raw gVCF
"""
to_check = 100
n = 0
with utils.open_gzipsafe(in_file) as in_handle:
for line in in_handle:
if not line.startswith("##"):
if n > to_check:
break
n += 1
... | def function[is_gvcf_file, parameter[in_file]]:
constant[Check if an input file is raw gVCF
]
variable[to_check] assign[=] constant[100]
variable[n] assign[=] constant[0]
with call[name[utils].open_gzipsafe, parameter[name[in_file]]] begin[:]
for taget[name[line]] in ... | keyword[def] identifier[is_gvcf_file] ( identifier[in_file] ):
literal[string]
identifier[to_check] = literal[int]
identifier[n] = literal[int]
keyword[with] identifier[utils] . identifier[open_gzipsafe] ( identifier[in_file] ) keyword[as] identifier[in_handle] :
keyword[for] identi... | def is_gvcf_file(in_file):
"""Check if an input file is raw gVCF
"""
to_check = 100
n = 0
with utils.open_gzipsafe(in_file) as in_handle:
for line in in_handle:
if not line.startswith('##'):
if n > to_check:
break # depends on [control=['if'],... |
def add_based_on_time(files_with_tags, on_location):
'''
Sometimes the first photo in a series does not have gps coordinates because the phone
doesnt have a gps-fix yet. To add these photos as well we take the list of photos wich where
taken in the right location. Then add any photos taken whitin 10... | def function[add_based_on_time, parameter[files_with_tags, on_location]]:
constant[
Sometimes the first photo in a series does not have gps coordinates because the phone
doesnt have a gps-fix yet. To add these photos as well we take the list of photos wich where
taken in the right location. Then add... | keyword[def] identifier[add_based_on_time] ( identifier[files_with_tags] , identifier[on_location] ):
literal[string]
identifier[to_add] = identifier[dict] ()
keyword[for] identifier[veiling_f] , identifier[veiling_tags] keyword[in] identifier[on_location] . identifier[items] ():
keywo... | def add_based_on_time(files_with_tags, on_location):
"""
Sometimes the first photo in a series does not have gps coordinates because the phone
doesnt have a gps-fix yet. To add these photos as well we take the list of photos wich where
taken in the right location. Then add any photos taken whitin 10 min... |
def format_fat(self, quick):
"""Formats the medium as FAT. Generally only useful for floppy images as
no partition table will be created.
in quick of type bool
Quick format it when set.
"""
if not isinstance(quick, bool):
raise TypeError("quick can only... | def function[format_fat, parameter[self, quick]]:
constant[Formats the medium as FAT. Generally only useful for floppy images as
no partition table will be created.
in quick of type bool
Quick format it when set.
]
if <ast.UnaryOp object at 0x7da204346f80> begin[:]... | keyword[def] identifier[format_fat] ( identifier[self] , identifier[quick] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[quick] , identifier[bool] ):
keyword[raise] identifier[TypeError] ( literal[string] )
identifier[self] . identifier[_ca... | def format_fat(self, quick):
"""Formats the medium as FAT. Generally only useful for floppy images as
no partition table will be created.
in quick of type bool
Quick format it when set.
"""
if not isinstance(quick, bool):
raise TypeError('quick can only be an insta... |
def changes(new_cmp_dict, old_cmp_dict, id_column, columns):
"""Return a list dict of the changes of the
rows that exist in both dictionaries
User must provide an ID column for old_cmp_dict
"""
update_ldict = []
same_keys = set(new_cmp_dict).intersection(set(old_cmp_dict))
for same_ke... | def function[changes, parameter[new_cmp_dict, old_cmp_dict, id_column, columns]]:
constant[Return a list dict of the changes of the
rows that exist in both dictionaries
User must provide an ID column for old_cmp_dict
]
variable[update_ldict] assign[=] list[[]]
variable[same_key... | keyword[def] identifier[changes] ( identifier[new_cmp_dict] , identifier[old_cmp_dict] , identifier[id_column] , identifier[columns] ):
literal[string]
identifier[update_ldict] =[]
identifier[same_keys] = identifier[set] ( identifier[new_cmp_dict] ). identifier[intersection] ( identifier[set] ( ident... | def changes(new_cmp_dict, old_cmp_dict, id_column, columns):
"""Return a list dict of the changes of the
rows that exist in both dictionaries
User must provide an ID column for old_cmp_dict
"""
update_ldict = []
same_keys = set(new_cmp_dict).intersection(set(old_cmp_dict))
for same_key... |
async def list(self, *, filters: Mapping = None) -> List[Mapping]:
"""
Return a list of services
Args:
filters: a dict with a list of filters
Available filters:
id=<service id>
label=<service label>
mode=["replicated"|"global"]
... | <ast.AsyncFunctionDef object at 0x7da1b088b9a0> | keyword[async] keyword[def] identifier[list] ( identifier[self] ,*, identifier[filters] : identifier[Mapping] = keyword[None] )-> identifier[List] [ identifier[Mapping] ]:
literal[string]
identifier[params] ={ literal[string] : identifier[clean_filters] ( identifier[filters] )}
identifi... | async def list(self, *, filters: Mapping=None) -> List[Mapping]:
"""
Return a list of services
Args:
filters: a dict with a list of filters
Available filters:
id=<service id>
label=<service label>
mode=["replicated"|"global"]
name... |
def mentions_links(uri, s):
""" Turns mentions-like strings into HTML links,
@uri: /uri/ root for the hashtag-like
@s: the #str string you're looking for |@|mentions in
-> #str HTML link |<a href="/uri/mention">mention</a>|
"""
for username, after in mentions_re.findall(s):
... | def function[mentions_links, parameter[uri, s]]:
constant[ Turns mentions-like strings into HTML links,
@uri: /uri/ root for the hashtag-like
@s: the #str string you're looking for |@|mentions in
-> #str HTML link |<a href="/uri/mention">mention</a>|
]
for taget[tuple[[<ast.... | keyword[def] identifier[mentions_links] ( identifier[uri] , identifier[s] ):
literal[string]
keyword[for] identifier[username] , identifier[after] keyword[in] identifier[mentions_re] . identifier[findall] ( identifier[s] ):
identifier[_uri] = literal[string] +( identifier[uri] keyword[or] lit... | def mentions_links(uri, s):
""" Turns mentions-like strings into HTML links,
@uri: /uri/ root for the hashtag-like
@s: the #str string you're looking for |@|mentions in
-> #str HTML link |<a href="/uri/mention">mention</a>|
"""
for (username, after) in mentions_re.findall(s):
... |
def bbox_vert_aligned_center(box1, box2):
"""
Returns true if the center of both boxes is within 5 pts
"""
if not (box1 and box2):
return False
return abs(((box1.right + box1.left) / 2.0) - ((box2.right + box2.left) / 2.0)) <= 5 | def function[bbox_vert_aligned_center, parameter[box1, box2]]:
constant[
Returns true if the center of both boxes is within 5 pts
]
if <ast.UnaryOp object at 0x7da18ede5e10> begin[:]
return[constant[False]]
return[compare[call[name[abs], parameter[binary_operation[binary_operation[bi... | keyword[def] identifier[bbox_vert_aligned_center] ( identifier[box1] , identifier[box2] ):
literal[string]
keyword[if] keyword[not] ( identifier[box1] keyword[and] identifier[box2] ):
keyword[return] keyword[False]
keyword[return] identifier[abs] ((( identifier[box1] . identifier[right]... | def bbox_vert_aligned_center(box1, box2):
"""
Returns true if the center of both boxes is within 5 pts
"""
if not (box1 and box2):
return False # depends on [control=['if'], data=[]]
return abs((box1.right + box1.left) / 2.0 - (box2.right + box2.left) / 2.0) <= 5 |
def set_range_y(self,val):
""" Set visible range of y data.
Note: Padding must be 0 or it will create an infinite loop
"""
d = self.declaration
if d.auto_range[1]:
return
self.widget.setYRange(*val,padding=0) | def function[set_range_y, parameter[self, val]]:
constant[ Set visible range of y data.
Note: Padding must be 0 or it will create an infinite loop
]
variable[d] assign[=] name[self].declaration
if call[name[d].auto_range][constant[1]] begin[:]
return[No... | keyword[def] identifier[set_range_y] ( identifier[self] , identifier[val] ):
literal[string]
identifier[d] = identifier[self] . identifier[declaration]
keyword[if] identifier[d] . identifier[auto_range] [ literal[int] ]:
keyword[return]
identifier[self] . identifie... | def set_range_y(self, val):
""" Set visible range of y data.
Note: Padding must be 0 or it will create an infinite loop
"""
d = self.declaration
if d.auto_range[1]:
return # depends on [control=['if'], data=[]]
self.widget.setYRange(*val, padding=0) |
def update(self, job):
"""Update last_run, next_run, and last_run_result for an existing job.
:param dict job: The job dictionary
:returns: True
"""
self.cur.execute('''UPDATE jobs
SET last_run=?,next_run=?,last_run_result=? WHERE hash=?''', (
job["last-ru... | def function[update, parameter[self, job]]:
constant[Update last_run, next_run, and last_run_result for an existing job.
:param dict job: The job dictionary
:returns: True
]
call[name[self].cur.execute, parameter[constant[UPDATE jobs
SET last_run=?,next_run=?,last_run... | keyword[def] identifier[update] ( identifier[self] , identifier[job] ):
literal[string]
identifier[self] . identifier[cur] . identifier[execute] ( literal[string] ,(
identifier[job] [ literal[string] ], identifier[job] [ literal[string] ], identifier[job] [ literal[string] ], identifier[jo... | def update(self, job):
"""Update last_run, next_run, and last_run_result for an existing job.
:param dict job: The job dictionary
:returns: True
"""
self.cur.execute('UPDATE jobs\n SET last_run=?,next_run=?,last_run_result=? WHERE hash=?', (job['last-run'], job['next-run'], jo... |
def start(self):
"""
Start the reader, acquires the global lock before appending the descriptor on the stream.
Releases the lock afterwards.
:return: Nothing
"""
NonBlockingStreamReader._stream_mtx.acquire()
NonBlockingStreamReader._streams.append(self._descriptor... | def function[start, parameter[self]]:
constant[
Start the reader, acquires the global lock before appending the descriptor on the stream.
Releases the lock afterwards.
:return: Nothing
]
call[name[NonBlockingStreamReader]._stream_mtx.acquire, parameter[]]
call[nam... | keyword[def] identifier[start] ( identifier[self] ):
literal[string]
identifier[NonBlockingStreamReader] . identifier[_stream_mtx] . identifier[acquire] ()
identifier[NonBlockingStreamReader] . identifier[_streams] . identifier[append] ( identifier[self] . identifier[_descriptor] )
... | def start(self):
"""
Start the reader, acquires the global lock before appending the descriptor on the stream.
Releases the lock afterwards.
:return: Nothing
"""
NonBlockingStreamReader._stream_mtx.acquire()
NonBlockingStreamReader._streams.append(self._descriptor)
NonBlo... |
def p_DefaultValue_string(p):
"""DefaultValue : STRING"""
p[0] = model.Value(type=model.Value.STRING, value=p[1]) | def function[p_DefaultValue_string, parameter[p]]:
constant[DefaultValue : STRING]
call[name[p]][constant[0]] assign[=] call[name[model].Value, parameter[]] | keyword[def] identifier[p_DefaultValue_string] ( identifier[p] ):
literal[string]
identifier[p] [ literal[int] ]= identifier[model] . identifier[Value] ( identifier[type] = identifier[model] . identifier[Value] . identifier[STRING] , identifier[value] = identifier[p] [ literal[int] ]) | def p_DefaultValue_string(p):
"""DefaultValue : STRING"""
p[0] = model.Value(type=model.Value.STRING, value=p[1]) |
def run_server(cls, args=None, **kwargs):
"""Run the class as a device server.
It is based on the tango.server.run method.
The difference is that the device class
and server name are automatically given.
Args:
args (iterable): args as given in the tango.server.run m... | def function[run_server, parameter[cls, args]]:
constant[Run the class as a device server.
It is based on the tango.server.run method.
The difference is that the device class
and server name are automatically given.
Args:
args (iterable): args as given in the tango.... | keyword[def] identifier[run_server] ( identifier[cls] , identifier[args] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[args] keyword[is] keyword[None] :
identifier[args] = identifier[sys] . identifier[argv] [ literal[int] :]
identifier[arg... | def run_server(cls, args=None, **kwargs):
"""Run the class as a device server.
It is based on the tango.server.run method.
The difference is that the device class
and server name are automatically given.
Args:
args (iterable): args as given in the tango.server.run metho... |
def register_channel_post_handler(self, callback, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
"""
Register handler for channel post
:param callback:
:param commands: list of commands
... | def function[register_channel_post_handler, parameter[self, callback]]:
constant[
Register handler for channel post
:param callback:
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param ... | keyword[def] identifier[register_channel_post_handler] ( identifier[self] , identifier[callback] ,* identifier[custom_filters] , identifier[commands] = keyword[None] , identifier[regexp] = keyword[None] , identifier[content_types] = keyword[None] ,
identifier[state] = keyword[None] , identifier[run_task] = keyword[N... | def register_channel_post_handler(self, callback, *custom_filters, commands=None, regexp=None, content_types=None, state=None, run_task=None, **kwargs):
"""
Register handler for channel post
:param callback:
:param commands: list of commands
:param regexp: REGEXP
:param cont... |
def _construct(self, targets, control_flow_slice=False):
"""
Construct a dependency graph based on given parameters.
:param targets: A list of tuples like (CFGNode, statement ID)
:param control_flow_slice: Is the backward slicing only depends on CFG or not.
"""
... | def function[_construct, parameter[self, targets, control_flow_slice]]:
constant[
Construct a dependency graph based on given parameters.
:param targets: A list of tuples like (CFGNode, statement ID)
:param control_flow_slice: Is the backward slicing only depends on CFG or ... | keyword[def] identifier[_construct] ( identifier[self] , identifier[targets] , identifier[control_flow_slice] = keyword[False] ):
literal[string]
keyword[if] identifier[control_flow_slice] :
identifier[simruns] =[ identifier[r] keyword[for] identifier[r] , identifier[_] keyword[in... | def _construct(self, targets, control_flow_slice=False):
"""
Construct a dependency graph based on given parameters.
:param targets: A list of tuples like (CFGNode, statement ID)
:param control_flow_slice: Is the backward slicing only depends on CFG or not.
"""
if c... |
def _aggregate_ndoverlay(self, element, agg_fn):
"""
Optimized aggregation for NdOverlay objects by aggregating each
Element in an NdOverlay individually avoiding having to concatenate
items in the NdOverlay. Works by summing sum and count aggregates and
applying appropriate mask... | def function[_aggregate_ndoverlay, parameter[self, element, agg_fn]]:
constant[
Optimized aggregation for NdOverlay objects by aggregating each
Element in an NdOverlay individually avoiding having to concatenate
items in the NdOverlay. Works by summing sum and count aggregates and
... | keyword[def] identifier[_aggregate_ndoverlay] ( identifier[self] , identifier[element] , identifier[agg_fn] ):
literal[string]
identifier[x] , identifier[y] = identifier[element] . identifier[last] . identifier[dimensions] ()[ literal[int] : literal[int] ]
identifier[info] = ident... | def _aggregate_ndoverlay(self, element, agg_fn):
"""
Optimized aggregation for NdOverlay objects by aggregating each
Element in an NdOverlay individually avoiding having to concatenate
items in the NdOverlay. Works by summing sum and count aggregates and
applying appropriate masking ... |
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude D... | def function[_handle_exclude, parameter[self, state, sls, saltenv, errors]]:
constant[
Take the exclude dec out of the state and apply it to the highstate
global dec
]
if compare[constant[exclude] in name[state]] begin[:]
variable[exc] assign[=] call[name[state].p... | keyword[def] identifier[_handle_exclude] ( identifier[self] , identifier[state] , identifier[sls] , identifier[saltenv] , identifier[errors] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[state] :
identifier[exc] = identifier[state] . identifier[pop] ( literal... | def _handle_exclude(self, state, sls, saltenv, errors):
"""
Take the exclude dec out of the state and apply it to the highstate
global dec
"""
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = 'Exclude Declaration in SLS {0}... |
def deepupdate(original, update):
"""Recursively update a dict.
Subdict's won't be overwritten but also updated.
"""
for key, value in original.items():
if key not in update:
update[key] = value
elif isinstance(value, dict):
deepupdate(value, update[key])
ret... | def function[deepupdate, parameter[original, update]]:
constant[Recursively update a dict.
Subdict's won't be overwritten but also updated.
]
for taget[tuple[[<ast.Name object at 0x7da1b1701450>, <ast.Name object at 0x7da1b1700f10>]]] in starred[call[name[original].items, parameter[]]] begin[:]... | keyword[def] identifier[deepupdate] ( identifier[original] , identifier[update] ):
literal[string]
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[original] . identifier[items] ():
keyword[if] identifier[key] keyword[not] keyword[in] identifier[update] :
... | def deepupdate(original, update):
"""Recursively update a dict.
Subdict's won't be overwritten but also updated.
"""
for (key, value) in original.items():
if key not in update:
update[key] = value # depends on [control=['if'], data=['key', 'update']]
elif isinstance(value, ... |
def AreaUnderCurve(x, y):
"""Compute Area Under the Curve (AUC) using the trapezoidal rule
Parameters
----------
x : array, shape = [n]
x coordinates
y : array, shape = [n]
y coordinates
Returns
-------
auc : float
Examples
--------
>>> import numpy as np
... | def function[AreaUnderCurve, parameter[x, y]]:
constant[Compute Area Under the Curve (AUC) using the trapezoidal rule
Parameters
----------
x : array, shape = [n]
x coordinates
y : array, shape = [n]
y coordinates
Returns
-------
auc : float
Examples
-----... | keyword[def] identifier[AreaUnderCurve] ( identifier[x] , identifier[y] ):
literal[string]
keyword[if] identifier[x] . identifier[shape] [ literal[int] ]!= identifier[y] . identifier[shape] [ literal[int] ]:
keyword[raise] identifier[ValueError] ( literal[string]
literal[string]
... | def AreaUnderCurve(x, y):
"""Compute Area Under the Curve (AUC) using the trapezoidal rule
Parameters
----------
x : array, shape = [n]
x coordinates
y : array, shape = [n]
y coordinates
Returns
-------
auc : float
Examples
--------
>>> import numpy as np
... |
def _get_positions_to_highlight(self, document):
"""
Return a list of (row, col) tuples that need to be highlighted.
"""
# Try for the character under the cursor.
if document.current_char and document.current_char in self.chars:
pos = document.find_matching_bracket_po... | def function[_get_positions_to_highlight, parameter[self, document]]:
constant[
Return a list of (row, col) tuples that need to be highlighted.
]
if <ast.BoolOp object at 0x7da1b080a110> begin[:]
variable[pos] assign[=] call[name[document].find_matching_bracket_position, ... | keyword[def] identifier[_get_positions_to_highlight] ( identifier[self] , identifier[document] ):
literal[string]
keyword[if] identifier[document] . identifier[current_char] keyword[and] identifier[document] . identifier[current_char] keyword[in] identifier[self] . identifier[chars] :... | def _get_positions_to_highlight(self, document):
"""
Return a list of (row, col) tuples that need to be highlighted.
"""
# Try for the character under the cursor.
if document.current_char and document.current_char in self.chars:
pos = document.find_matching_bracket_position(start_pos... |
def read_labels(filename, delimiter=DEFAULT_DELIMITER):
"""read label files. Format: ent label"""
_assert_good_file(filename)
with open(filename) as f:
labels = [_label_processing(l, delimiter) for l in f]
return labels | def function[read_labels, parameter[filename, delimiter]]:
constant[read label files. Format: ent label]
call[name[_assert_good_file], parameter[name[filename]]]
with call[name[open], parameter[name[filename]]] begin[:]
variable[labels] assign[=] <ast.ListComp object at 0x7da1b00... | keyword[def] identifier[read_labels] ( identifier[filename] , identifier[delimiter] = identifier[DEFAULT_DELIMITER] ):
literal[string]
identifier[_assert_good_file] ( identifier[filename] )
keyword[with] identifier[open] ( identifier[filename] ) keyword[as] identifier[f] :
identifier[labels... | def read_labels(filename, delimiter=DEFAULT_DELIMITER):
"""read label files. Format: ent label"""
_assert_good_file(filename)
with open(filename) as f:
labels = [_label_processing(l, delimiter) for l in f]
return labels # depends on [control=['with'], data=['f']] |
def _add_admin_views(self):
"""
Registers indexview, utilview (back function), babel views and Security views.
"""
self.indexview = self._check_and_init(self.indexview)
self.add_view_no_menu(self.indexview)
self.add_view_no_menu(UtilView())
self.bm.register_vi... | def function[_add_admin_views, parameter[self]]:
constant[
Registers indexview, utilview (back function), babel views and Security views.
]
name[self].indexview assign[=] call[name[self]._check_and_init, parameter[name[self].indexview]]
call[name[self].add_view_no_menu, param... | keyword[def] identifier[_add_admin_views] ( identifier[self] ):
literal[string]
identifier[self] . identifier[indexview] = identifier[self] . identifier[_check_and_init] ( identifier[self] . identifier[indexview] )
identifier[self] . identifier[add_view_no_menu] ( identifier[self] . identi... | def _add_admin_views(self):
"""
Registers indexview, utilview (back function), babel views and Security views.
"""
self.indexview = self._check_and_init(self.indexview)
self.add_view_no_menu(self.indexview)
self.add_view_no_menu(UtilView())
self.bm.register_views()
if self.ge... |
def insert_all(db, schema_name, table_name, columns, items):
"""
Insert all item in given items list into the specified table, schema_name.table_name.
"""
table = '{0}.{1}'.format(schema_name, table_name) if schema_name else table_name
columns_list = ', '.join(columns)
values_list = ', '.join(['... | def function[insert_all, parameter[db, schema_name, table_name, columns, items]]:
constant[
Insert all item in given items list into the specified table, schema_name.table_name.
]
variable[table] assign[=] <ast.IfExp object at 0x7da1b05db640>
variable[columns_list] assign[=] call[constan... | keyword[def] identifier[insert_all] ( identifier[db] , identifier[schema_name] , identifier[table_name] , identifier[columns] , identifier[items] ):
literal[string]
identifier[table] = literal[string] . identifier[format] ( identifier[schema_name] , identifier[table_name] ) keyword[if] identifier[schema_n... | def insert_all(db, schema_name, table_name, columns, items):
"""
Insert all item in given items list into the specified table, schema_name.table_name.
"""
table = '{0}.{1}'.format(schema_name, table_name) if schema_name else table_name
columns_list = ', '.join(columns)
values_list = ', '.join(['... |
def run(
draco_query: List[str],
constants: Dict[str, str] = None,
files: List[str] = None,
relax_hard=False,
silence_warnings=False,
debug=False,
clear_cache=False,
) -> Optional[Result]:
""" Run clingo to compute a completion of a partial spec or violations. """
# Clear file cache... | def function[run, parameter[draco_query, constants, files, relax_hard, silence_warnings, debug, clear_cache]]:
constant[ Run clingo to compute a completion of a partial spec or violations. ]
if <ast.BoolOp object at 0x7da1b0b373a0> begin[:]
call[name[logger].warning, parameter[constant[C... | keyword[def] identifier[run] (
identifier[draco_query] : identifier[List] [ identifier[str] ],
identifier[constants] : identifier[Dict] [ identifier[str] , identifier[str] ]= keyword[None] ,
identifier[files] : identifier[List] [ identifier[str] ]= keyword[None] ,
identifier[relax_hard] = keyword[False] ,
identi... | def run(draco_query: List[str], constants: Dict[str, str]=None, files: List[str]=None, relax_hard=False, silence_warnings=False, debug=False, clear_cache=False) -> Optional[Result]:
""" Run clingo to compute a completion of a partial spec or violations. """
# Clear file cache. useful during development in noteb... |
def assertFileSizeGreater(self, filename, size, msg=None):
'''Fail if ``filename``'s size is not greater than ``size`` as
determined by the '>' operator.
Parameters
----------
filename : str, bytes, file-like
size : int, float
msg : str
If not provide... | def function[assertFileSizeGreater, parameter[self, filename, size, msg]]:
constant[Fail if ``filename``'s size is not greater than ``size`` as
determined by the '>' operator.
Parameters
----------
filename : str, bytes, file-like
size : int, float
msg : str
... | keyword[def] identifier[assertFileSizeGreater] ( identifier[self] , identifier[filename] , identifier[size] , identifier[msg] = keyword[None] ):
literal[string]
identifier[fsize] = identifier[self] . identifier[_get_file_size] ( identifier[filename] )
identifier[self] . identifier[assertGr... | def assertFileSizeGreater(self, filename, size, msg=None):
"""Fail if ``filename``'s size is not greater than ``size`` as
determined by the '>' operator.
Parameters
----------
filename : str, bytes, file-like
size : int, float
msg : str
If not provided, t... |
def std(expr, **kw):
"""
Standard deviation.
:param expr:
:param kw:
:return:
"""
ddof = kw.get('ddof', kw.get('_ddof', 1))
output_type = _stats_type(expr)
return _reduction(expr, Std, output_type, _ddof=ddof) | def function[std, parameter[expr]]:
constant[
Standard deviation.
:param expr:
:param kw:
:return:
]
variable[ddof] assign[=] call[name[kw].get, parameter[constant[ddof], call[name[kw].get, parameter[constant[_ddof], constant[1]]]]]
variable[output_type] assign[=] call[name[... | keyword[def] identifier[std] ( identifier[expr] ,** identifier[kw] ):
literal[string]
identifier[ddof] = identifier[kw] . identifier[get] ( literal[string] , identifier[kw] . identifier[get] ( literal[string] , literal[int] ))
identifier[output_type] = identifier[_stats_type] ( identifier[expr] )
... | def std(expr, **kw):
"""
Standard deviation.
:param expr:
:param kw:
:return:
"""
ddof = kw.get('ddof', kw.get('_ddof', 1))
output_type = _stats_type(expr)
return _reduction(expr, Std, output_type, _ddof=ddof) |
def send_exit_with_code(cls, sock, code):
"""Send an Exit chunk over the specified socket, containing the specified return code."""
encoded_exit_status = cls.encode_int(code)
cls.send_exit(sock, payload=encoded_exit_status) | def function[send_exit_with_code, parameter[cls, sock, code]]:
constant[Send an Exit chunk over the specified socket, containing the specified return code.]
variable[encoded_exit_status] assign[=] call[name[cls].encode_int, parameter[name[code]]]
call[name[cls].send_exit, parameter[name[sock]]] | keyword[def] identifier[send_exit_with_code] ( identifier[cls] , identifier[sock] , identifier[code] ):
literal[string]
identifier[encoded_exit_status] = identifier[cls] . identifier[encode_int] ( identifier[code] )
identifier[cls] . identifier[send_exit] ( identifier[sock] , identifier[payload] = ide... | def send_exit_with_code(cls, sock, code):
"""Send an Exit chunk over the specified socket, containing the specified return code."""
encoded_exit_status = cls.encode_int(code)
cls.send_exit(sock, payload=encoded_exit_status) |
def addNode(self, node):
'''
Update the shared map with my in-construction node
'''
self.mybldgbuids[node.buid] = node
self.allbldgbuids[node.buid] = (node, self.doneevent) | def function[addNode, parameter[self, node]]:
constant[
Update the shared map with my in-construction node
]
call[name[self].mybldgbuids][name[node].buid] assign[=] name[node]
call[name[self].allbldgbuids][name[node].buid] assign[=] tuple[[<ast.Name object at 0x7da207f03160>, <as... | keyword[def] identifier[addNode] ( identifier[self] , identifier[node] ):
literal[string]
identifier[self] . identifier[mybldgbuids] [ identifier[node] . identifier[buid] ]= identifier[node]
identifier[self] . identifier[allbldgbuids] [ identifier[node] . identifier[buid] ]=( identifier[n... | def addNode(self, node):
"""
Update the shared map with my in-construction node
"""
self.mybldgbuids[node.buid] = node
self.allbldgbuids[node.buid] = (node, self.doneevent) |
def is_b_connected(H, source_node, target_node):
"""Checks if a target node is B-connected to a source node.
A node t is B-connected to a node s iff:
- t is s, or
- there exists an edge in the backward star of t such that all nodes in
the tail of that edge are B-connected to s
... | def function[is_b_connected, parameter[H, source_node, target_node]]:
constant[Checks if a target node is B-connected to a source node.
A node t is B-connected to a node s iff:
- t is s, or
- there exists an edge in the backward star of t such that all nodes in
the tail of that ... | keyword[def] identifier[is_b_connected] ( identifier[H] , identifier[source_node] , identifier[target_node] ):
literal[string]
identifier[b_visited_nodes] , identifier[Pv] , identifier[Pe] , identifier[v] = identifier[b_visit] ( identifier[H] , identifier[source_node] )
keyword[return] identifier[tar... | def is_b_connected(H, source_node, target_node):
"""Checks if a target node is B-connected to a source node.
A node t is B-connected to a node s iff:
- t is s, or
- there exists an edge in the backward star of t such that all nodes in
the tail of that edge are B-connected to s
... |
def configure():
"""Load logging configuration from our own defaults."""
log_levels = {
5: logging.NOTSET,
4: logging.DEBUG,
3: logging.INFO,
2: logging.WARNING,
1: logging.ERROR,
0: logging.CRITICAL
}
logging.captureWarnings(True)
root_logger = loggi... | def function[configure, parameter[]]:
constant[Load logging configuration from our own defaults.]
variable[log_levels] assign[=] dictionary[[<ast.Constant object at 0x7da20c7cae60>, <ast.Constant object at 0x7da20c7c8c40>, <ast.Constant object at 0x7da20c7cace0>, <ast.Constant object at 0x7da20c7c8400>,... | keyword[def] identifier[configure] ():
literal[string]
identifier[log_levels] ={
literal[int] : identifier[logging] . identifier[NOTSET] ,
literal[int] : identifier[logging] . identifier[DEBUG] ,
literal[int] : identifier[logging] . identifier[INFO] ,
literal[int] : identifier[logging] ... | def configure():
"""Load logging configuration from our own defaults."""
log_levels = {5: logging.NOTSET, 4: logging.DEBUG, 3: logging.INFO, 2: logging.WARNING, 1: logging.ERROR, 0: logging.CRITICAL}
logging.captureWarnings(True)
root_logger = logging.getLogger()
if settings.CFG['debug']:
de... |
def prepare_body(self, data, files, json=None):
"""Prepares the given HTTP body data."""
# Check if file, fo, generator, iterator.
# If not, run through normal process.
# Nottin' on you.
body = None
content_type = None
if not data and json is not None:
... | def function[prepare_body, parameter[self, data, files, json]]:
constant[Prepares the given HTTP body data.]
variable[body] assign[=] constant[None]
variable[content_type] assign[=] constant[None]
if <ast.BoolOp object at 0x7da1b1de1f60> begin[:]
variable[content_type] as... | keyword[def] identifier[prepare_body] ( identifier[self] , identifier[data] , identifier[files] , identifier[json] = keyword[None] ):
literal[string]
identifier[body] = keyword[None]
identifier[content_type] = keyword[None]
keyword[if] keyword[not]... | def prepare_body(self, data, files, json=None):
"""Prepares the given HTTP body data."""
# Check if file, fo, generator, iterator.
# If not, run through normal process.
# Nottin' on you.
body = None
content_type = None
if not data and json is not None:
# urllib3 requires a bytes-like... |
def update_collection_by_id(cls, collection_id, collection, **kwargs):
"""Update Collection
Update attributes of Collection
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_collection_by... | def function[update_collection_by_id, parameter[cls, collection_id, collection]]:
constant[Update Collection
Update attributes of Collection
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.upd... | keyword[def] identifier[update_collection_by_id] ( identifier[cls] , identifier[collection_id] , identifier[collection] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
... | def update_collection_by_id(cls, collection_id, collection, **kwargs):
"""Update Collection
Update attributes of Collection
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_collection_by_id(... |
def set(self, ctype, key, data):
"""Set or update cache content.
:param ctype: cache type
:param key: the key to be set value
:param data: cache data
"""
with zvmutils.acquire_lock(self._lock):
target_cache = self._get_ctype_cache(ctype)
target_ca... | def function[set, parameter[self, ctype, key, data]]:
constant[Set or update cache content.
:param ctype: cache type
:param key: the key to be set value
:param data: cache data
]
with call[name[zvmutils].acquire_lock, parameter[name[self]._lock]] begin[:]
... | keyword[def] identifier[set] ( identifier[self] , identifier[ctype] , identifier[key] , identifier[data] ):
literal[string]
keyword[with] identifier[zvmutils] . identifier[acquire_lock] ( identifier[self] . identifier[_lock] ):
identifier[target_cache] = identifier[self] . identifier[... | def set(self, ctype, key, data):
"""Set or update cache content.
:param ctype: cache type
:param key: the key to be set value
:param data: cache data
"""
with zvmutils.acquire_lock(self._lock):
target_cache = self._get_ctype_cache(ctype)
target_cache['data'][key]... |
def save(self, *args, **kwargs):
"""
Save the created_by and last_modified_by fields based on the current admin user.
"""
if not self.instance.id:
self.instance.created_by = self.user
self.instance.last_modified_by = self.user
return super(ChangeableContentFor... | def function[save, parameter[self]]:
constant[
Save the created_by and last_modified_by fields based on the current admin user.
]
if <ast.UnaryOp object at 0x7da1b15b0250> begin[:]
name[self].instance.created_by assign[=] name[self].user
name[self].instance.last_m... | keyword[def] identifier[save] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[instance] . identifier[id] :
identifier[self] . identifier[instance] . identifier[created_by] = identifier[self] . ide... | def save(self, *args, **kwargs):
"""
Save the created_by and last_modified_by fields based on the current admin user.
"""
if not self.instance.id:
self.instance.created_by = self.user # depends on [control=['if'], data=[]]
self.instance.last_modified_by = self.user
return super(... |
def addVariant(self,variant):
'''Appends one Variant to variants
'''
if isinstance(variant, Variant):
self.variants.append(variant)
else:
raise (VariantError,
'variant Type should be Variant, not %s' % type(variant)) | def function[addVariant, parameter[self, variant]]:
constant[Appends one Variant to variants
]
if call[name[isinstance], parameter[name[variant], name[Variant]]] begin[:]
call[name[self].variants.append, parameter[name[variant]]] | keyword[def] identifier[addVariant] ( identifier[self] , identifier[variant] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[variant] , identifier[Variant] ):
identifier[self] . identifier[variants] . identifier[append] ( identifier[variant] )
keyword[else]... | def addVariant(self, variant):
"""Appends one Variant to variants
"""
if isinstance(variant, Variant):
self.variants.append(variant) # depends on [control=['if'], data=[]]
else:
raise (VariantError, 'variant Type should be Variant, not %s' % type(variant)) |
def match_fn(match_values_and_abi, data):
"""Match function used for filtering non-indexed event arguments.
Values provided through the match_values_and_abi parameter are
compared to the abi decoded log data.
"""
abi_types, all_match_values = zip(*match_values_and_abi)
decoded_values = decode_a... | def function[match_fn, parameter[match_values_and_abi, data]]:
constant[Match function used for filtering non-indexed event arguments.
Values provided through the match_values_and_abi parameter are
compared to the abi decoded log data.
]
<ast.Tuple object at 0x7da18f813b80> assign[=] call[n... | keyword[def] identifier[match_fn] ( identifier[match_values_and_abi] , identifier[data] ):
literal[string]
identifier[abi_types] , identifier[all_match_values] = identifier[zip] (* identifier[match_values_and_abi] )
identifier[decoded_values] = identifier[decode_abi] ( identifier[abi_types] , identifi... | def match_fn(match_values_and_abi, data):
"""Match function used for filtering non-indexed event arguments.
Values provided through the match_values_and_abi parameter are
compared to the abi decoded log data.
"""
(abi_types, all_match_values) = zip(*match_values_and_abi)
decoded_values = decode... |
def take_break(minutes: hug.types.number=5):
"""Enables temporarily breaking concentration"""
print("")
print("######################################### ARE YOU SURE? #####################################")
try:
for remaining in range(60, -1, -1):
sys.stdout.write("\r")
s... | def function[take_break, parameter[minutes]]:
constant[Enables temporarily breaking concentration]
call[name[print], parameter[constant[]]]
call[name[print], parameter[constant[######################################### ARE YOU SURE? #####################################]]]
<ast.Try object at... | keyword[def] identifier[take_break] ( identifier[minutes] : identifier[hug] . identifier[types] . identifier[number] = literal[int] ):
literal[string]
identifier[print] ( literal[string] )
identifier[print] ( literal[string] )
keyword[try] :
keyword[for] identifier[remaining] keyword[i... | def take_break(minutes: hug.types.number=5):
"""Enables temporarily breaking concentration"""
print('')
print('######################################### ARE YOU SURE? #####################################')
try:
for remaining in range(60, -1, -1):
sys.stdout.write('\r')
s... |
def pulse_train(time, start, duration, repeat_time, end):
""" Implements vensim's PULSE TRAIN function
In range [-inf, start) returns 0
In range [start + n * repeat_time, start + n * repeat_time + duration) return 1
In range [start + n * repeat_time + duration, start + (n+1) * repeat_time) return 0
... | def function[pulse_train, parameter[time, start, duration, repeat_time, end]]:
constant[ Implements vensim's PULSE TRAIN function
In range [-inf, start) returns 0
In range [start + n * repeat_time, start + n * repeat_time + duration) return 1
In range [start + n * repeat_time + duration, start + (n... | keyword[def] identifier[pulse_train] ( identifier[time] , identifier[start] , identifier[duration] , identifier[repeat_time] , identifier[end] ):
literal[string]
identifier[t] = identifier[time] ()
keyword[if] identifier[start] <= identifier[t] < identifier[end] :
keyword[return] literal[in... | def pulse_train(time, start, duration, repeat_time, end):
""" Implements vensim's PULSE TRAIN function
In range [-inf, start) returns 0
In range [start + n * repeat_time, start + n * repeat_time + duration) return 1
In range [start + n * repeat_time + duration, start + (n+1) * repeat_time) return 0
... |
def _load_machines_cache(self):
"""This method should fill up `_machines_cache` from scratch.
It could happen only in two cases:
1. During class initialization
2. When all etcd members failed"""
self._update_machines_cache = True
if 'srv' not in self._config and 'host' ... | def function[_load_machines_cache, parameter[self]]:
constant[This method should fill up `_machines_cache` from scratch.
It could happen only in two cases:
1. During class initialization
2. When all etcd members failed]
name[self]._update_machines_cache assign[=] constant[True]
... | keyword[def] identifier[_load_machines_cache] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_update_machines_cache] = keyword[True]
keyword[if] literal[string] keyword[not] keyword[in] identifier[self] . identifier[_config] keyword[and] literal[string] keywo... | def _load_machines_cache(self):
"""This method should fill up `_machines_cache` from scratch.
It could happen only in two cases:
1. During class initialization
2. When all etcd members failed"""
self._update_machines_cache = True
if 'srv' not in self._config and 'host' not in self._c... |
def get_exiobase_files(path, coefficients=True):
""" Gets the EXIOBASE files in path (which can be a zip file)
Parameters
----------
path: str or pathlib.Path
Path to exiobase files or zip file
coefficients: boolean, optional
If True (default), considers the mrIot file as A matrix,
... | def function[get_exiobase_files, parameter[path, coefficients]]:
constant[ Gets the EXIOBASE files in path (which can be a zip file)
Parameters
----------
path: str or pathlib.Path
Path to exiobase files or zip file
coefficients: boolean, optional
If True (default), considers th... | keyword[def] identifier[get_exiobase_files] ( identifier[path] , identifier[coefficients] = keyword[True] ):
literal[string]
identifier[path] = identifier[os] . identifier[path] . identifier[normpath] ( identifier[str] ( identifier[path] ))
keyword[if] identifier[coefficients] :
identifier[e... | def get_exiobase_files(path, coefficients=True):
""" Gets the EXIOBASE files in path (which can be a zip file)
Parameters
----------
path: str or pathlib.Path
Path to exiobase files or zip file
coefficients: boolean, optional
If True (default), considers the mrIot file as A matrix,
... |
def addSettingsMenu(menuName, parentMenuFunction=None):
'''
Adds a 'open settings...' menu to the plugin menu.
This method should be called from the initGui() method of the plugin
:param menuName: The name of the plugin menu in which the settings menu is to be added
:param parentMenuFunction: a fun... | def function[addSettingsMenu, parameter[menuName, parentMenuFunction]]:
constant[
Adds a 'open settings...' menu to the plugin menu.
This method should be called from the initGui() method of the plugin
:param menuName: The name of the plugin menu in which the settings menu is to be added
:param... | keyword[def] identifier[addSettingsMenu] ( identifier[menuName] , identifier[parentMenuFunction] = keyword[None] ):
literal[string]
identifier[parentMenuFunction] = identifier[parentMenuFunction] keyword[or] identifier[iface] . identifier[addPluginToMenu]
identifier[namespace] = identifier[_caller... | def addSettingsMenu(menuName, parentMenuFunction=None):
"""
Adds a 'open settings...' menu to the plugin menu.
This method should be called from the initGui() method of the plugin
:param menuName: The name of the plugin menu in which the settings menu is to be added
:param parentMenuFunction: a fun... |
def get_stocks(self, symbols: List[str]) -> List[Commodity]:
""" loads stocks by symbol """
query = (
self.query
.filter(Commodity.mnemonic.in_(symbols))
).order_by(Commodity.namespace, Commodity.mnemonic)
return query.all() | def function[get_stocks, parameter[self, symbols]]:
constant[ loads stocks by symbol ]
variable[query] assign[=] call[call[name[self].query.filter, parameter[call[name[Commodity].mnemonic.in_, parameter[name[symbols]]]]].order_by, parameter[name[Commodity].namespace, name[Commodity].mnemonic]]
retur... | keyword[def] identifier[get_stocks] ( identifier[self] , identifier[symbols] : identifier[List] [ identifier[str] ])-> identifier[List] [ identifier[Commodity] ]:
literal[string]
identifier[query] =(
identifier[self] . identifier[query]
. identifier[filter] ( identifier[Commodity]... | def get_stocks(self, symbols: List[str]) -> List[Commodity]:
""" loads stocks by symbol """
query = self.query.filter(Commodity.mnemonic.in_(symbols)).order_by(Commodity.namespace, Commodity.mnemonic)
return query.all() |
def template_instances(cls, dataset, capacity=0):
"""
Uses the Instances as template to create an empty dataset.
:param dataset: the original dataset
:type dataset: Instances
:param capacity: how many data rows to reserve initially (see compactify)
:type capacity: int
... | def function[template_instances, parameter[cls, dataset, capacity]]:
constant[
Uses the Instances as template to create an empty dataset.
:param dataset: the original dataset
:type dataset: Instances
:param capacity: how many data rows to reserve initially (see compactify)
... | keyword[def] identifier[template_instances] ( identifier[cls] , identifier[dataset] , identifier[capacity] = literal[int] ):
literal[string]
keyword[return] identifier[Instances] (
identifier[javabridge] . identifier[make_instance] (
literal[string] , literal[string] , identifier... | def template_instances(cls, dataset, capacity=0):
"""
Uses the Instances as template to create an empty dataset.
:param dataset: the original dataset
:type dataset: Instances
:param capacity: how many data rows to reserve initially (see compactify)
:type capacity: int
... |
def firmware_autoupgrade_params_protocol(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
firmware = ET.SubElement(config, "firmware", xmlns="urn:brocade.com:mgmt:brocade-firmware")
autoupgrade_params = ET.SubElement(firmware, "autoupgrade-params")
... | def function[firmware_autoupgrade_params_protocol, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[firmware] assign[=] call[name[ET].SubElement, parameter[name[config], constant[firmware]]]
v... | keyword[def] identifier[firmware_autoupgrade_params_protocol] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[firmware] = identifier[ET] . identifier[SubElement] ( identifier[config] , lit... | def firmware_autoupgrade_params_protocol(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
firmware = ET.SubElement(config, 'firmware', xmlns='urn:brocade.com:mgmt:brocade-firmware')
autoupgrade_params = ET.SubElement(firmware, 'autoupgrade-params')
protocol = ET.SubE... |
def getRelationships(self, pid, subject=None, predicate=None, format=None):
'''Get information about relationships on an object.
Wrapper function for
`Fedora REST API getRelationships <https://wiki.duraspace.org/display/FEDORA34/REST+API#RESTAPI-getRelationships>`_
:param pid: object ... | def function[getRelationships, parameter[self, pid, subject, predicate, format]]:
constant[Get information about relationships on an object.
Wrapper function for
`Fedora REST API getRelationships <https://wiki.duraspace.org/display/FEDORA34/REST+API#RESTAPI-getRelationships>`_
:param ... | keyword[def] identifier[getRelationships] ( identifier[self] , identifier[pid] , identifier[subject] = keyword[None] , identifier[predicate] = keyword[None] , identifier[format] = keyword[None] ):
literal[string]
identifier[http_args] ={}
keyword[if] identifier[subject] keyword[is] keyw... | def getRelationships(self, pid, subject=None, predicate=None, format=None):
"""Get information about relationships on an object.
Wrapper function for
`Fedora REST API getRelationships <https://wiki.duraspace.org/display/FEDORA34/REST+API#RESTAPI-getRelationships>`_
:param pid: object pid
... |
def get_subs(subs_file='subreddits.txt', blacklist_file='blacklist.txt') -> List[str]:
"""
Get subs based on a file of subreddits and a file of blacklisted subreddits.
:param subs_file: List of subreddits. Each sub in a new line.
:param blacklist_file: List of blacklisted subreddits. Each sub in a new... | def function[get_subs, parameter[subs_file, blacklist_file]]:
constant[
Get subs based on a file of subreddits and a file of blacklisted subreddits.
:param subs_file: List of subreddits. Each sub in a new line.
:param blacklist_file: List of blacklisted subreddits. Each sub in a new line.
:ret... | keyword[def] identifier[get_subs] ( identifier[subs_file] = literal[string] , identifier[blacklist_file] = literal[string] )-> identifier[List] [ identifier[str] ]:
literal[string]
identifier[subsf] = identifier[open] ( identifier[subs_file] )
identifier[blacklf] = identifier[open] ( identifier[b... | def get_subs(subs_file='subreddits.txt', blacklist_file='blacklist.txt') -> List[str]:
"""
Get subs based on a file of subreddits and a file of blacklisted subreddits.
:param subs_file: List of subreddits. Each sub in a new line.
:param blacklist_file: List of blacklisted subreddits. Each sub in a new... |
def community_topic_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/topics#show-topic"
api_path = "/api/v2/community/topics/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | def function[community_topic_show, parameter[self, id]]:
constant[https://developer.zendesk.com/rest_api/docs/help_center/topics#show-topic]
variable[api_path] assign[=] constant[/api/v2/community/topics/{id}.json]
variable[api_path] assign[=] call[name[api_path].format, parameter[]]
return[... | keyword[def] identifier[community_topic_show] ( identifier[self] , identifier[id] ,** identifier[kwargs] ):
literal[string]
identifier[api_path] = literal[string]
identifier[api_path] = identifier[api_path] . identifier[format] ( identifier[id] = identifier[id] )
keyword[return] ... | def community_topic_show(self, id, **kwargs):
"""https://developer.zendesk.com/rest_api/docs/help_center/topics#show-topic"""
api_path = '/api/v2/community/topics/{id}.json'
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) |
def graph_easy(self):
"""Draw ascii diagram. graph-easy perl module require
"""
if not os.path.isfile("/usr/bin/graph-easy"):
print("Require 'graph-easy': Install with 'slpkg -s sbo "
"graph-easy'")
self.remove_dot()
raise SystemExit()
... | def function[graph_easy, parameter[self]]:
constant[Draw ascii diagram. graph-easy perl module require
]
if <ast.UnaryOp object at 0x7da2044c0370> begin[:]
call[name[print], parameter[constant[Require 'graph-easy': Install with 'slpkg -s sbo graph-easy']]]
call[na... | keyword[def] identifier[graph_easy] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isfile] ( literal[string] ):
identifier[print] ( literal[string]
literal[string] )
identifier[self] . identifie... | def graph_easy(self):
"""Draw ascii diagram. graph-easy perl module require
"""
if not os.path.isfile('/usr/bin/graph-easy'):
print("Require 'graph-easy': Install with 'slpkg -s sbo graph-easy'")
self.remove_dot()
raise SystemExit() # depends on [control=['if'], data=[]]
sub... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.