code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def assign(self, V, py):
"""Store python value in Value
"""
if isinstance(py, (bytes, unicode)):
for i,C in enumerate(V['value.choices'] or self._choices):
if py==C:
V['value.index'] = i
return
# attempt to parse as int... | def function[assign, parameter[self, V, py]]:
constant[Store python value in Value
]
if call[name[isinstance], parameter[name[py], tuple[[<ast.Name object at 0x7da1b04c9330>, <ast.Name object at 0x7da1b04cbd60>]]]] begin[:]
for taget[tuple[[<ast.Name object at 0x7da1b04cb7c0>, <a... | keyword[def] identifier[assign] ( identifier[self] , identifier[V] , identifier[py] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[py] ,( identifier[bytes] , identifier[unicode] )):
keyword[for] identifier[i] , identifier[C] keyword[in] identifier[enumerate] ( i... | def assign(self, V, py):
"""Store python value in Value
"""
if isinstance(py, (bytes, unicode)):
for (i, C) in enumerate(V['value.choices'] or self._choices):
if py == C:
V['value.index'] = i
return # depends on [control=['if'], data=[]] # depends on... |
def filter_paths(pathnames,
included_patterns=None,
excluded_patterns=None,
case_sensitive=True):
"""
Filters from a set of paths based on acceptable patterns and
ignorable patterns.
:param pathnames:
A list of path names that will be filtered ... | def function[filter_paths, parameter[pathnames, included_patterns, excluded_patterns, case_sensitive]]:
constant[
Filters from a set of paths based on acceptable patterns and
ignorable patterns.
:param pathnames:
A list of path names that will be filtered based on matching and
ignor... | keyword[def] identifier[filter_paths] ( identifier[pathnames] ,
identifier[included_patterns] = keyword[None] ,
identifier[excluded_patterns] = keyword[None] ,
identifier[case_sensitive] = keyword[True] ):
literal[string]
identifier[included] =[ literal[string] ] keyword[if] identifier[included_pattern... | def filter_paths(pathnames, included_patterns=None, excluded_patterns=None, case_sensitive=True):
"""
Filters from a set of paths based on acceptable patterns and
ignorable patterns.
:param pathnames:
A list of path names that will be filtered based on matching and
ignored patterns.
... |
def list(self,walkTrace=tuple(),case=None,element=None):
"""List section titles.
"""
if case == 'sectionmain': print(walkTrace,self.title) | def function[list, parameter[self, walkTrace, case, element]]:
constant[List section titles.
]
if compare[name[case] equal[==] constant[sectionmain]] begin[:]
call[name[print], parameter[name[walkTrace], name[self].title]] | keyword[def] identifier[list] ( identifier[self] , identifier[walkTrace] = identifier[tuple] (), identifier[case] = keyword[None] , identifier[element] = keyword[None] ):
literal[string]
keyword[if] identifier[case] == literal[string] : identifier[print] ( identifier[walkTrace] , identifier[self] ... | def list(self, walkTrace=tuple(), case=None, element=None):
"""List section titles.
"""
if case == 'sectionmain':
print(walkTrace, self.title) # depends on [control=['if'], data=[]] |
def _dump(self, tag, x, lo, hi):
"""Generate comparison results for a same-tagged range."""
for i in xrange(lo, hi):
yield '%s %s' % (tag, x[i]) | def function[_dump, parameter[self, tag, x, lo, hi]]:
constant[Generate comparison results for a same-tagged range.]
for taget[name[i]] in starred[call[name[xrange], parameter[name[lo], name[hi]]]] begin[:]
<ast.Yield object at 0x7da18dc05360> | keyword[def] identifier[_dump] ( identifier[self] , identifier[tag] , identifier[x] , identifier[lo] , identifier[hi] ):
literal[string]
keyword[for] identifier[i] keyword[in] identifier[xrange] ( identifier[lo] , identifier[hi] ):
keyword[yield] literal[string] %( identifier[tag] ... | def _dump(self, tag, x, lo, hi):
"""Generate comparison results for a same-tagged range."""
for i in xrange(lo, hi):
yield ('%s %s' % (tag, x[i])) # depends on [control=['for'], data=['i']] |
def calculate(ctx, slot, challenge, totp, digits):
"""
Perform a challenge-response operation.
Send a challenge (in hex) to a YubiKey slot with a challenge-response
credential, and read the response. Supports output as a OATH-TOTP code.
"""
controller = ctx.obj['controller']
if not challeng... | def function[calculate, parameter[ctx, slot, challenge, totp, digits]]:
constant[
Perform a challenge-response operation.
Send a challenge (in hex) to a YubiKey slot with a challenge-response
credential, and read the response. Supports output as a OATH-TOTP code.
]
variable[controller] ... | keyword[def] identifier[calculate] ( identifier[ctx] , identifier[slot] , identifier[challenge] , identifier[totp] , identifier[digits] ):
literal[string]
identifier[controller] = identifier[ctx] . identifier[obj] [ literal[string] ]
keyword[if] keyword[not] identifier[challenge] keyword[and] keyw... | def calculate(ctx, slot, challenge, totp, digits):
"""
Perform a challenge-response operation.
Send a challenge (in hex) to a YubiKey slot with a challenge-response
credential, and read the response. Supports output as a OATH-TOTP code.
"""
controller = ctx.obj['controller']
if not challeng... |
def remove_reaction(self, reaction):
"""Remove reaction from model"""
if reaction not in self._reaction_set:
return
self._reaction_set.remove(reaction)
self._limits_lower.pop(reaction, None)
self._limits_upper.pop(reaction, None)
# Remove compound from comp... | def function[remove_reaction, parameter[self, reaction]]:
constant[Remove reaction from model]
if compare[name[reaction] <ast.NotIn object at 0x7da2590d7190> name[self]._reaction_set] begin[:]
return[None]
call[name[self]._reaction_set.remove, parameter[name[reaction]]]
call[name... | keyword[def] identifier[remove_reaction] ( identifier[self] , identifier[reaction] ):
literal[string]
keyword[if] identifier[reaction] keyword[not] keyword[in] identifier[self] . identifier[_reaction_set] :
keyword[return]
identifier[self] . identifier[_reaction_set] . ... | def remove_reaction(self, reaction):
"""Remove reaction from model"""
if reaction not in self._reaction_set:
return # depends on [control=['if'], data=[]]
self._reaction_set.remove(reaction)
self._limits_lower.pop(reaction, None)
self._limits_upper.pop(reaction, None)
# Remove compound ... |
def on_shutdown(self, callback: callable, polling=True, webhook=True):
"""
Register a callback for the shutdown process
:param callback:
:param polling: use with polling
:param webhook: use with webhook
"""
self._check_frozen()
if not webhook and not poll... | def function[on_shutdown, parameter[self, callback, polling, webhook]]:
constant[
Register a callback for the shutdown process
:param callback:
:param polling: use with polling
:param webhook: use with webhook
]
call[name[self]._check_frozen, parameter[]]
... | keyword[def] identifier[on_shutdown] ( identifier[self] , identifier[callback] : identifier[callable] , identifier[polling] = keyword[True] , identifier[webhook] = keyword[True] ):
literal[string]
identifier[self] . identifier[_check_frozen] ()
keyword[if] keyword[not] identifier[webhook... | def on_shutdown(self, callback: callable, polling=True, webhook=True):
"""
Register a callback for the shutdown process
:param callback:
:param polling: use with polling
:param webhook: use with webhook
"""
self._check_frozen()
if not webhook and (not polling):
... |
def load_subcat_info( subcat_lex_file ):
''' Loads subcategorization rules (for verbs and adpositions) from a text
file.
It is expected that the rules are given as pairs, where the first item is
the lemma (of verb/adposition), followed on the next line by the
subcategori... | def function[load_subcat_info, parameter[subcat_lex_file]]:
constant[ Loads subcategorization rules (for verbs and adpositions) from a text
file.
It is expected that the rules are given as pairs, where the first item is
the lemma (of verb/adposition), followed on the next lin... | keyword[def] identifier[load_subcat_info] ( identifier[subcat_lex_file] ):
literal[string]
identifier[rules] ={}
identifier[nonSpacePattern] = identifier[re] . identifier[compile] ( literal[string] )
identifier[posTagPattern] = identifier[re] . identifier[compile] ( literal[string] )
identif... | def load_subcat_info(subcat_lex_file):
""" Loads subcategorization rules (for verbs and adpositions) from a text
file.
It is expected that the rules are given as pairs, where the first item is
the lemma (of verb/adposition), followed on the next line by the
subcategoriza... |
def deleteLayerNode(self, layername, nodeNum):
"""
Removes a particular unit/node from a layer.
"""
# first, construct an array of all of the weights
# that won't be deleted:
gene = []
for layer in self.layers:
if layer.type != 'Input':
... | def function[deleteLayerNode, parameter[self, layername, nodeNum]]:
constant[
Removes a particular unit/node from a layer.
]
variable[gene] assign[=] list[[]]
for taget[name[layer]] in starred[name[self].layers] begin[:]
if compare[name[layer].type not_equal[!=] c... | keyword[def] identifier[deleteLayerNode] ( identifier[self] , identifier[layername] , identifier[nodeNum] ):
literal[string]
identifier[gene] =[]
keyword[for] identifier[layer] keyword[in] identifier[self] . identifier[layers] :
keyword[if] identifier[lay... | def deleteLayerNode(self, layername, nodeNum):
"""
Removes a particular unit/node from a layer.
"""
# first, construct an array of all of the weights
# that won't be deleted:
gene = []
for layer in self.layers:
if layer.type != 'Input':
for i in range(layer.size):... |
def mouseReleaseEvent(self, event):
"""
Emits mouse_released signal.
:param event: QMouseEvent
"""
initial_state = event.isAccepted()
event.ignore()
self.mouse_released.emit(event)
if not event.isAccepted():
event.setAccepted(initial_state)
... | def function[mouseReleaseEvent, parameter[self, event]]:
constant[
Emits mouse_released signal.
:param event: QMouseEvent
]
variable[initial_state] assign[=] call[name[event].isAccepted, parameter[]]
call[name[event].ignore, parameter[]]
call[name[self].mouse_rel... | keyword[def] identifier[mouseReleaseEvent] ( identifier[self] , identifier[event] ):
literal[string]
identifier[initial_state] = identifier[event] . identifier[isAccepted] ()
identifier[event] . identifier[ignore] ()
identifier[self] . identifier[mouse_released] . identifier[emit]... | def mouseReleaseEvent(self, event):
"""
Emits mouse_released signal.
:param event: QMouseEvent
"""
initial_state = event.isAccepted()
event.ignore()
self.mouse_released.emit(event)
if not event.isAccepted():
event.setAccepted(initial_state)
super(CodeEdit, se... |
def _parse_msg_for_influxdb(self, msgs):
'''
>>> from logagg.forwarders import InfluxDBForwarder
>>> idbf = InfluxDBForwarder('no_host', '8086', 'deadpool',
... 'chimichanga', 'logs', 'collection')
>>> valid_log = [{u'data': {u'_force_this_as_field': ... | def function[_parse_msg_for_influxdb, parameter[self, msgs]]:
constant[
>>> from logagg.forwarders import InfluxDBForwarder
>>> idbf = InfluxDBForwarder('no_host', '8086', 'deadpool',
... 'chimichanga', 'logs', 'collection')
>>> valid_log = [{u'data':... | keyword[def] identifier[_parse_msg_for_influxdb] ( identifier[self] , identifier[msgs] ):
literal[string]
identifier[series] =[]
keyword[for] identifier[msg] keyword[in] identifier[msgs] :
keyword[if] identifier[msg] . identifier[get] ( literal[string] ):
... | def _parse_msg_for_influxdb(self, msgs):
"""
>>> from logagg.forwarders import InfluxDBForwarder
>>> idbf = InfluxDBForwarder('no_host', '8086', 'deadpool',
... 'chimichanga', 'logs', 'collection')
>>> valid_log = [{u'data': {u'_force_this_as_field': 'CXN... |
def normalizeSequence(sequence, considerDimensions=None):
"""
normalize sequence by subtracting the mean and
:param sequence: a list of data samples
:param considerDimensions: a list of dimensions to consider
:return: normalized sequence
"""
seq = np.array(sequence).astype('float64')
nSampleDim = seq.sh... | def function[normalizeSequence, parameter[sequence, considerDimensions]]:
constant[
normalize sequence by subtracting the mean and
:param sequence: a list of data samples
:param considerDimensions: a list of dimensions to consider
:return: normalized sequence
]
variable[seq] assign[=] call[cal... | keyword[def] identifier[normalizeSequence] ( identifier[sequence] , identifier[considerDimensions] = keyword[None] ):
literal[string]
identifier[seq] = identifier[np] . identifier[array] ( identifier[sequence] ). identifier[astype] ( literal[string] )
identifier[nSampleDim] = identifier[seq] . identifier[sh... | def normalizeSequence(sequence, considerDimensions=None):
"""
normalize sequence by subtracting the mean and
:param sequence: a list of data samples
:param considerDimensions: a list of dimensions to consider
:return: normalized sequence
"""
seq = np.array(sequence).astype('float64')
nSampleDim = ... |
def add_job(cls, identifier, queue_name=None, priority=0, queue_model=None,
prepend=False, delayed_for=None, delayed_until=None,
**fields_if_new):
"""
Add a job to a queue.
If this job already exists, check it's current priority. If its higher
than the new... | def function[add_job, parameter[cls, identifier, queue_name, priority, queue_model, prepend, delayed_for, delayed_until]]:
constant[
Add a job to a queue.
If this job already exists, check it's current priority. If its higher
than the new one, don't touch it, else move the job to the wan... | keyword[def] identifier[add_job] ( identifier[cls] , identifier[identifier] , identifier[queue_name] = keyword[None] , identifier[priority] = literal[int] , identifier[queue_model] = keyword[None] ,
identifier[prepend] = keyword[False] , identifier[delayed_for] = keyword[None] , identifier[delayed_until] = keyword[N... | def add_job(cls, identifier, queue_name=None, priority=0, queue_model=None, prepend=False, delayed_for=None, delayed_until=None, **fields_if_new):
"""
Add a job to a queue.
If this job already exists, check it's current priority. If its higher
than the new one, don't touch it, else move the ... |
def created_on(self):
"""The creation timestamp."""
timestamp = self._info.get('creationTime')
return _parser.Parser.parse_timestamp(timestamp) | def function[created_on, parameter[self]]:
constant[The creation timestamp.]
variable[timestamp] assign[=] call[name[self]._info.get, parameter[constant[creationTime]]]
return[call[name[_parser].Parser.parse_timestamp, parameter[name[timestamp]]]] | keyword[def] identifier[created_on] ( identifier[self] ):
literal[string]
identifier[timestamp] = identifier[self] . identifier[_info] . identifier[get] ( literal[string] )
keyword[return] identifier[_parser] . identifier[Parser] . identifier[parse_timestamp] ( identifier[timestamp] ) | def created_on(self):
"""The creation timestamp."""
timestamp = self._info.get('creationTime')
return _parser.Parser.parse_timestamp(timestamp) |
def _long_from_raw(thehash):
"""Fold to a long, a digest supplied as a string."""
hashnum = 0
for h in thehash:
hashnum <<= 8
hashnum |= ord(bytes([h]))
return hashnum | def function[_long_from_raw, parameter[thehash]]:
constant[Fold to a long, a digest supplied as a string.]
variable[hashnum] assign[=] constant[0]
for taget[name[h]] in starred[name[thehash]] begin[:]
<ast.AugAssign object at 0x7da1b072d630>
<ast.AugAssign object at 0x7da1b072f3a... | keyword[def] identifier[_long_from_raw] ( identifier[thehash] ):
literal[string]
identifier[hashnum] = literal[int]
keyword[for] identifier[h] keyword[in] identifier[thehash] :
identifier[hashnum] <<= literal[int]
identifier[hashnum] |= identifier[ord] ( identifier[bytes] ([ ide... | def _long_from_raw(thehash):
"""Fold to a long, a digest supplied as a string."""
hashnum = 0
for h in thehash:
hashnum <<= 8
hashnum |= ord(bytes([h])) # depends on [control=['for'], data=['h']]
return hashnum |
def urban_adj_factor(self):
"""
Return urban adjustment factor (UAF) used to adjust QMED and growth curves.
Methodology source: eqn. 8, Kjeldsen 2010
:return: urban adjustment factor
:rtype: float
"""
urbext = self.catchment.descriptors.urbext(self.year)
... | def function[urban_adj_factor, parameter[self]]:
constant[
Return urban adjustment factor (UAF) used to adjust QMED and growth curves.
Methodology source: eqn. 8, Kjeldsen 2010
:return: urban adjustment factor
:rtype: float
]
variable[urbext] assign[=] call[name... | keyword[def] identifier[urban_adj_factor] ( identifier[self] ):
literal[string]
identifier[urbext] = identifier[self] . identifier[catchment] . identifier[descriptors] . identifier[urbext] ( identifier[self] . identifier[year] )
identifier[result] = identifier[self] . identifier[_pruaf] ()... | def urban_adj_factor(self):
"""
Return urban adjustment factor (UAF) used to adjust QMED and growth curves.
Methodology source: eqn. 8, Kjeldsen 2010
:return: urban adjustment factor
:rtype: float
"""
urbext = self.catchment.descriptors.urbext(self.year)
result = se... |
def _handle_command_response(self, res, event):
"""Either send a message (choosing between rtm and postMessage) or ignore the response.
:param event: a slacker event dict
:param res: a string, a dict, or None.
See the command docstring for what these represent.
"""
re... | def function[_handle_command_response, parameter[self, res, event]]:
constant[Either send a message (choosing between rtm and postMessage) or ignore the response.
:param event: a slacker event dict
:param res: a string, a dict, or None.
See the command docstring for what these represe... | keyword[def] identifier[_handle_command_response] ( identifier[self] , identifier[res] , identifier[event] ):
literal[string]
identifier[response_handler] = keyword[None]
keyword[if] identifier[isinstance] ( identifier[res] , identifier[basestring] ):
identifier[response_h... | def _handle_command_response(self, res, event):
"""Either send a message (choosing between rtm and postMessage) or ignore the response.
:param event: a slacker event dict
:param res: a string, a dict, or None.
See the command docstring for what these represent.
"""
response_ha... |
def start(self):
"""
Starts the upload.
:raises SbgError: If upload is not in PREPARING state.
"""
if self._status == TransferState.PREPARING:
super(Upload, self).start()
else:
raise SbgError(
'Unable to start. Upload not in PREPARI... | def function[start, parameter[self]]:
constant[
Starts the upload.
:raises SbgError: If upload is not in PREPARING state.
]
if compare[name[self]._status equal[==] name[TransferState].PREPARING] begin[:]
call[call[name[super], parameter[name[Upload], name[self]]].... | keyword[def] identifier[start] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_status] == identifier[TransferState] . identifier[PREPARING] :
identifier[super] ( identifier[Upload] , identifier[self] ). identifier[start] ()
keyword[else] :
... | def start(self):
"""
Starts the upload.
:raises SbgError: If upload is not in PREPARING state.
"""
if self._status == TransferState.PREPARING:
super(Upload, self).start() # depends on [control=['if'], data=[]]
else:
raise SbgError('Unable to start. Upload not in PREP... |
def parse_querystring(self, req, name, field):
"""Pull a querystring value from the request."""
return core.get_value(req.args, name, field) | def function[parse_querystring, parameter[self, req, name, field]]:
constant[Pull a querystring value from the request.]
return[call[name[core].get_value, parameter[name[req].args, name[name], name[field]]]] | keyword[def] identifier[parse_querystring] ( identifier[self] , identifier[req] , identifier[name] , identifier[field] ):
literal[string]
keyword[return] identifier[core] . identifier[get_value] ( identifier[req] . identifier[args] , identifier[name] , identifier[field] ) | def parse_querystring(self, req, name, field):
"""Pull a querystring value from the request."""
return core.get_value(req.args, name, field) |
def module(self):
"""The module in which the Class is defined.
Python equivalent of the CLIPS defglobal-module command.
"""
modname = ffi.string(lib.EnvDefclassModule(self._env, self._cls))
defmodule = lib.EnvFindDefmodule(self._env, modname)
return Module(self._env, d... | def function[module, parameter[self]]:
constant[The module in which the Class is defined.
Python equivalent of the CLIPS defglobal-module command.
]
variable[modname] assign[=] call[name[ffi].string, parameter[call[name[lib].EnvDefclassModule, parameter[name[self]._env, name[self]._cls... | keyword[def] identifier[module] ( identifier[self] ):
literal[string]
identifier[modname] = identifier[ffi] . identifier[string] ( identifier[lib] . identifier[EnvDefclassModule] ( identifier[self] . identifier[_env] , identifier[self] . identifier[_cls] ))
identifier[defmodule] = identifi... | def module(self):
"""The module in which the Class is defined.
Python equivalent of the CLIPS defglobal-module command.
"""
modname = ffi.string(lib.EnvDefclassModule(self._env, self._cls))
defmodule = lib.EnvFindDefmodule(self._env, modname)
return Module(self._env, defmodule) |
def LeaseCronJobs(self, cronjob_ids=None, lease_time=None):
"""Leases all available cron jobs."""
leased_jobs = []
now = rdfvalue.RDFDatetime.Now()
expiration_time = now + lease_time
for job in itervalues(self.cronjobs):
if cronjob_ids and job.cron_job_id not in cronjob_ids:
continue... | def function[LeaseCronJobs, parameter[self, cronjob_ids, lease_time]]:
constant[Leases all available cron jobs.]
variable[leased_jobs] assign[=] list[[]]
variable[now] assign[=] call[name[rdfvalue].RDFDatetime.Now, parameter[]]
variable[expiration_time] assign[=] binary_operation[name[no... | keyword[def] identifier[LeaseCronJobs] ( identifier[self] , identifier[cronjob_ids] = keyword[None] , identifier[lease_time] = keyword[None] ):
literal[string]
identifier[leased_jobs] =[]
identifier[now] = identifier[rdfvalue] . identifier[RDFDatetime] . identifier[Now] ()
identifier[expiration_... | def LeaseCronJobs(self, cronjob_ids=None, lease_time=None):
"""Leases all available cron jobs."""
leased_jobs = []
now = rdfvalue.RDFDatetime.Now()
expiration_time = now + lease_time
for job in itervalues(self.cronjobs):
if cronjob_ids and job.cron_job_id not in cronjob_ids:
cont... |
def normalize(self, inplace=False):
"""Normalizes a Quaternion to unit length
so that it represents a valid rotation.
Args:
inplace (bool): Do an inplace normalization.
Returns:
Quaternion: Normalized quaternion.
"""
if inplace:
nrm =... | def function[normalize, parameter[self, inplace]]:
constant[Normalizes a Quaternion to unit length
so that it represents a valid rotation.
Args:
inplace (bool): Do an inplace normalization.
Returns:
Quaternion: Normalized quaternion.
]
if name[in... | keyword[def] identifier[normalize] ( identifier[self] , identifier[inplace] = keyword[False] ):
literal[string]
keyword[if] identifier[inplace] :
identifier[nrm] = identifier[self] . identifier[norm] ()
identifier[self] . identifier[data] /= identifier[nrm]
... | def normalize(self, inplace=False):
"""Normalizes a Quaternion to unit length
so that it represents a valid rotation.
Args:
inplace (bool): Do an inplace normalization.
Returns:
Quaternion: Normalized quaternion.
"""
if inplace:
nrm = self.norm()... |
def _nextOn(self, request):
"""
Formatted date/time of when this event (including any postponements)
will next be on
"""
retval = None
nextDt, event = self.__localAfterOrPostponedTo(timezone.localtime(),
dt.time.min)
... | def function[_nextOn, parameter[self, request]]:
constant[
Formatted date/time of when this event (including any postponements)
will next be on
]
variable[retval] assign[=] constant[None]
<ast.Tuple object at 0x7da20e9606a0> assign[=] call[name[self].__localAfterOrPostpon... | keyword[def] identifier[_nextOn] ( identifier[self] , identifier[request] ):
literal[string]
identifier[retval] = keyword[None]
identifier[nextDt] , identifier[event] = identifier[self] . identifier[__localAfterOrPostponedTo] ( identifier[timezone] . identifier[localtime] (),
ide... | def _nextOn(self, request):
"""
Formatted date/time of when this event (including any postponements)
will next be on
"""
retval = None
(nextDt, event) = self.__localAfterOrPostponedTo(timezone.localtime(), dt.time.min)
if nextDt is not None:
timeFrom = nextDt.time() if ev... |
def make_energy_funnel_data(self, cores=1):
"""Compares models created during the minimisation to the best model.
Returns
-------
energy_rmsd_gen: [(float, float, int)]
A list of triples containing the BUFF score, RMSD to the
top model and generation of a model g... | def function[make_energy_funnel_data, parameter[self, cores]]:
constant[Compares models created during the minimisation to the best model.
Returns
-------
energy_rmsd_gen: [(float, float, int)]
A list of triples containing the BUFF score, RMSD to the
top model an... | keyword[def] identifier[make_energy_funnel_data] ( identifier[self] , identifier[cores] = literal[int] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[parameter_log] :
keyword[raise] identifier[AttributeError] (
literal[string]
li... | def make_energy_funnel_data(self, cores=1):
"""Compares models created during the minimisation to the best model.
Returns
-------
energy_rmsd_gen: [(float, float, int)]
A list of triples containing the BUFF score, RMSD to the
top model and generation of a model gener... |
def _load_data_from_disk(file_set, preprocess_func=lambda ds: ds,
data_vars='minimal', coords='minimal',
grid_attrs=None, **kwargs):
"""Load a Dataset from a list or glob-string of files.
Datasets from files are concatenated along time,
and all grid attribu... | def function[_load_data_from_disk, parameter[file_set, preprocess_func, data_vars, coords, grid_attrs]]:
constant[Load a Dataset from a list or glob-string of files.
Datasets from files are concatenated along time,
and all grid attributes are renamed to their aospy internal names.
Parameters
-... | keyword[def] identifier[_load_data_from_disk] ( identifier[file_set] , identifier[preprocess_func] = keyword[lambda] identifier[ds] : identifier[ds] ,
identifier[data_vars] = literal[string] , identifier[coords] = literal[string] ,
identifier[grid_attrs] = keyword[None] ,** identifier[kwargs] ):
literal[strin... | def _load_data_from_disk(file_set, preprocess_func=lambda ds: ds, data_vars='minimal', coords='minimal', grid_attrs=None, **kwargs):
"""Load a Dataset from a list or glob-string of files.
Datasets from files are concatenated along time,
and all grid attributes are renamed to their aospy internal names.
... |
def candidate(self, cand_func, args=None, kwargs=None, name='Candidate', context=None):
'''
Adds a candidate function to an experiment. Can be used multiple times for
multiple candidates.
:param callable cand_func: your control function
:param iterable args: positional arguments... | def function[candidate, parameter[self, cand_func, args, kwargs, name, context]]:
constant[
Adds a candidate function to an experiment. Can be used multiple times for
multiple candidates.
:param callable cand_func: your control function
:param iterable args: positional arguments... | keyword[def] identifier[candidate] ( identifier[self] , identifier[cand_func] , identifier[args] = keyword[None] , identifier[kwargs] = keyword[None] , identifier[name] = literal[string] , identifier[context] = keyword[None] ):
literal[string]
identifier[self] . identifier[_candidates] . identifier... | def candidate(self, cand_func, args=None, kwargs=None, name='Candidate', context=None):
"""
Adds a candidate function to an experiment. Can be used multiple times for
multiple candidates.
:param callable cand_func: your control function
:param iterable args: positional arguments to ... |
def leaf_nodes(self):
"""
Return an interable of nodes with no edges pointing at them. This is
helpful to find all nodes without dependencies.
"""
# Now contains all nodes that contain dependencies.
deps = {item for sublist in self.edges.values() for item in sublist}
... | def function[leaf_nodes, parameter[self]]:
constant[
Return an interable of nodes with no edges pointing at them. This is
helpful to find all nodes without dependencies.
]
variable[deps] assign[=] <ast.SetComp object at 0x7da18f723c40>
return[binary_operation[name[self].nodes... | keyword[def] identifier[leaf_nodes] ( identifier[self] ):
literal[string]
identifier[deps] ={ identifier[item] keyword[for] identifier[sublist] keyword[in] identifier[self] . identifier[edges] . identifier[values] () keyword[for] identifier[item] keyword[in] identifier[sublist] }
... | def leaf_nodes(self):
"""
Return an interable of nodes with no edges pointing at them. This is
helpful to find all nodes without dependencies.
"""
# Now contains all nodes that contain dependencies.
deps = {item for sublist in self.edges.values() for item in sublist}
# contains a... |
def get_compound_regex(schema='mona'):
""" Create a dictionary of regex for extracting the compound information for the spectra
"""
# NOTE: will just ignore cases in the regex, to avoid repetition here
meta_parse = collections.OrderedDict()
if schema == 'mona':
meta_parse['name'] = ['^Name... | def function[get_compound_regex, parameter[schema]]:
constant[ Create a dictionary of regex for extracting the compound information for the spectra
]
variable[meta_parse] assign[=] call[name[collections].OrderedDict, parameter[]]
if compare[name[schema] equal[==] constant[mona]] begin[:]
... | keyword[def] identifier[get_compound_regex] ( identifier[schema] = literal[string] ):
literal[string]
identifier[meta_parse] = identifier[collections] . identifier[OrderedDict] ()
keyword[if] identifier[schema] == literal[string] :
identifier[meta_parse] [ literal[string] ]=[ literal[... | def get_compound_regex(schema='mona'):
""" Create a dictionary of regex for extracting the compound information for the spectra
"""
# NOTE: will just ignore cases in the regex, to avoid repetition here
meta_parse = collections.OrderedDict()
if schema == 'mona':
meta_parse['name'] = ['^Name(?... |
def read_float_matrix(rx_specifier):
""" Return float matrix as np array for the given rx specifier. """
path, offset = rx_specifier.strip().split(':', maxsplit=1)
offset = int(offset)
sample_format = 4
with open(path, 'rb') as f:
# move to offset
f.seek... | def function[read_float_matrix, parameter[rx_specifier]]:
constant[ Return float matrix as np array for the given rx specifier. ]
<ast.Tuple object at 0x7da1b0ba7040> assign[=] call[call[name[rx_specifier].strip, parameter[]].split, parameter[constant[:]]]
variable[offset] assign[=] call[name[in... | keyword[def] identifier[read_float_matrix] ( identifier[rx_specifier] ):
literal[string]
identifier[path] , identifier[offset] = identifier[rx_specifier] . identifier[strip] (). identifier[split] ( literal[string] , identifier[maxsplit] = literal[int] )
identifier[offset] = identifier[int... | def read_float_matrix(rx_specifier):
""" Return float matrix as np array for the given rx specifier. """
(path, offset) = rx_specifier.strip().split(':', maxsplit=1)
offset = int(offset)
sample_format = 4
with open(path, 'rb') as f:
# move to offset
f.seek(offset)
# assert bi... |
def _parsecsv(x):
"""Deserialize file-like object containing csv to a Python generator.
"""
for line in x:
# decode as utf-8, whitespace-strip and split on delimiter
yield line.decode('utf-8').strip().split(config.DELIMITER) | def function[_parsecsv, parameter[x]]:
constant[Deserialize file-like object containing csv to a Python generator.
]
for taget[name[line]] in starred[name[x]] begin[:]
<ast.Yield object at 0x7da20c6c5660> | keyword[def] identifier[_parsecsv] ( identifier[x] ):
literal[string]
keyword[for] identifier[line] keyword[in] identifier[x] :
keyword[yield] identifier[line] . identifier[decode] ( literal[string] ). identifier[strip] (). identifier[split] ( identifier[config] . identifi... | def _parsecsv(x):
"""Deserialize file-like object containing csv to a Python generator.
"""
for line in x:
# decode as utf-8, whitespace-strip and split on delimiter
yield line.decode('utf-8').strip().split(config.DELIMITER) # depends on [control=['for'], data=['line']] |
def pin_chat_message(chat_id, message_id, disable_notification=None, **kwargs):
"""
Use this method to pin a message in a supergroup or a channel. The bot must be an administrator in the chat for this to work and
must have the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ admin rig... | def function[pin_chat_message, parameter[chat_id, message_id, disable_notification]]:
constant[
Use this method to pin a message in a supergroup or a channel. The bot must be an administrator in the chat for this to work and
must have the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_mes... | keyword[def] identifier[pin_chat_message] ( identifier[chat_id] , identifier[message_id] , identifier[disable_notification] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[params] = identifier[dict] (
identifier[chat_id] = identifier[chat_id] ,
identifier[message_id] = ... | def pin_chat_message(chat_id, message_id, disable_notification=None, **kwargs):
"""
Use this method to pin a message in a supergroup or a channel. The bot must be an administrator in the chat for this to work and
must have the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ admin rig... |
def save(self, name=None, path=None):
"""Save file as xml
"""
if path :
name = os.path.join(path,name)
try:
self._create_table_xml_file(self.etree, name)
except (Exception,) as e:
print(e)
return False
return True | def function[save, parameter[self, name, path]]:
constant[Save file as xml
]
if name[path] begin[:]
variable[name] assign[=] call[name[os].path.join, parameter[name[path], name[name]]]
<ast.Try object at 0x7da2045663b0>
return[constant[True]] | keyword[def] identifier[save] ( identifier[self] , identifier[name] = keyword[None] , identifier[path] = keyword[None] ):
literal[string]
keyword[if] identifier[path] :
identifier[name] = identifier[os] . identifier[path] . identifier[join] ( identifier[path] , identifier[name] )
... | def save(self, name=None, path=None):
"""Save file as xml
"""
if path:
name = os.path.join(path, name) # depends on [control=['if'], data=[]]
try:
self._create_table_xml_file(self.etree, name) # depends on [control=['try'], data=[]]
except (Exception,) as e:
print(e)
... |
def mergebydepth(args):
"""
%prog mergebydepth reads.bed genome.fasta
Similar to mergeBed, but only returns regions beyond certain depth.
"""
p = OptionParser(mergebydepth.__doc__)
p.add_option("--mindepth", default=3, type="int",
help="Minimum depth required")
opts, args =... | def function[mergebydepth, parameter[args]]:
constant[
%prog mergebydepth reads.bed genome.fasta
Similar to mergeBed, but only returns regions beyond certain depth.
]
variable[p] assign[=] call[name[OptionParser], parameter[name[mergebydepth].__doc__]]
call[name[p].add_option, param... | keyword[def] identifier[mergebydepth] ( identifier[args] ):
literal[string]
identifier[p] = identifier[OptionParser] ( identifier[mergebydepth] . identifier[__doc__] )
identifier[p] . identifier[add_option] ( literal[string] , identifier[default] = literal[int] , identifier[type] = literal[string] ,
... | def mergebydepth(args):
"""
%prog mergebydepth reads.bed genome.fasta
Similar to mergeBed, but only returns regions beyond certain depth.
"""
p = OptionParser(mergebydepth.__doc__)
p.add_option('--mindepth', default=3, type='int', help='Minimum depth required')
(opts, args) = p.parse_args(a... |
def analysis_provenance_details_pdf_extractor(
impact_report, component_metadata):
"""Extracting the main provenance details to its own pdf report.
For PDF generations
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_... | def function[analysis_provenance_details_pdf_extractor, parameter[impact_report, component_metadata]]:
constant[Extracting the main provenance details to its own pdf report.
For PDF generations
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor ne... | keyword[def] identifier[analysis_provenance_details_pdf_extractor] (
identifier[impact_report] , identifier[component_metadata] ):
literal[string]
identifier[context] = identifier[QGISComposerContext] ()
identifier[html_frame_elements] =[
{
literal[string] : litera... | def analysis_provenance_details_pdf_extractor(impact_report, component_metadata):
"""Extracting the main provenance details to its own pdf report.
For PDF generations
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: s... |
def objwalk(obj, path=(), memo=None):
"""
Walks an arbitrary python pbject.
:param mixed obj: Any python object
:param tuple path: A tuple of the set attributes representing the path to the value
:param set memo: The list of attributes traversed thus far
:rtype <tuple<tuple>, <mixed>>: The pat... | def function[objwalk, parameter[obj, path, memo]]:
constant[
Walks an arbitrary python pbject.
:param mixed obj: Any python object
:param tuple path: A tuple of the set attributes representing the path to the value
:param set memo: The list of attributes traversed thus far
:rtype <tuple<tu... | keyword[def] identifier[objwalk] ( identifier[obj] , identifier[path] =(), identifier[memo] = keyword[None] ):
literal[string]
keyword[if] identifier[len] ( identifier[path] )> identifier[MAX_DEPTH] + literal[int] :
keyword[yield] identifier[path] , identifier[obj]
keyword[if] identifier[... | def objwalk(obj, path=(), memo=None):
"""
Walks an arbitrary python pbject.
:param mixed obj: Any python object
:param tuple path: A tuple of the set attributes representing the path to the value
:param set memo: The list of attributes traversed thus far
:rtype <tuple<tuple>, <mixed>>: The pat... |
def and_constraint(v=1, sense="minimize"):
""" AND constraint """
assert v in [0,1], "v must be 0 or 1 instead of %s" % v.__repr__()
model, x, y, z = _init()
r = model.addVar("r", "B")
model.addConsAnd([x,y,z], r)
model.addCons(x==v)
model.setObjective(r, sense=sense)
_optimize("AND", mo... | def function[and_constraint, parameter[v, sense]]:
constant[ AND constraint ]
assert[compare[name[v] in list[[<ast.Constant object at 0x7da1b17f46d0>, <ast.Constant object at 0x7da1b17f46a0>]]]]
<ast.Tuple object at 0x7da1b17f4550> assign[=] call[name[_init], parameter[]]
variable[r] assign[... | keyword[def] identifier[and_constraint] ( identifier[v] = literal[int] , identifier[sense] = literal[string] ):
literal[string]
keyword[assert] identifier[v] keyword[in] [ literal[int] , literal[int] ], literal[string] % identifier[v] . identifier[__repr__] ()
identifier[model] , identifier[x] , ide... | def and_constraint(v=1, sense='minimize'):
""" AND constraint """
assert v in [0, 1], 'v must be 0 or 1 instead of %s' % v.__repr__()
(model, x, y, z) = _init()
r = model.addVar('r', 'B')
model.addConsAnd([x, y, z], r)
model.addCons(x == v)
model.setObjective(r, sense=sense)
_optimize('A... |
def _get(self, url):
"""Handles api.football-data.org requests"""
self.logger.info(f'Sending request: {RequestHandler.BASE_URL+url}')
req = requests.get(RequestHandler.BASE_URL+url, headers=self.headers)
self.logger.info(f'Request returned with status code {req.status_code}')
if... | def function[_get, parameter[self, url]]:
constant[Handles api.football-data.org requests]
call[name[self].logger.info, parameter[<ast.JoinedStr object at 0x7da1b085e410>]]
variable[req] assign[=] call[name[requests].get, parameter[binary_operation[name[RequestHandler].BASE_URL + name[url]]]]
... | keyword[def] identifier[_get] ( identifier[self] , identifier[url] ):
literal[string]
identifier[self] . identifier[logger] . identifier[info] ( literal[string] )
identifier[req] = identifier[requests] . identifier[get] ( identifier[RequestHandler] . identifier[BASE_URL] + identifier[url] ... | def _get(self, url):
"""Handles api.football-data.org requests"""
self.logger.info(f'Sending request: {RequestHandler.BASE_URL + url}')
req = requests.get(RequestHandler.BASE_URL + url, headers=self.headers)
self.logger.info(f'Request returned with status code {req.status_code}')
if req.status_code ... |
def set_terminal(self, terminal):
"""Packs the terminal widget.
"""
if self.terminal is not None:
raise RuntimeError("TerminalBox: terminal already set")
self.terminal = terminal
self.terminal.connect("grab-focus", self.on_terminal_focus)
self.terminal.connect... | def function[set_terminal, parameter[self, terminal]]:
constant[Packs the terminal widget.
]
if compare[name[self].terminal is_not constant[None]] begin[:]
<ast.Raise object at 0x7da2041d9cc0>
name[self].terminal assign[=] name[terminal]
call[name[self].terminal.connect, ... | keyword[def] identifier[set_terminal] ( identifier[self] , identifier[terminal] ):
literal[string]
keyword[if] identifier[self] . identifier[terminal] keyword[is] keyword[not] keyword[None] :
keyword[raise] identifier[RuntimeError] ( literal[string] )
identifier[self] . i... | def set_terminal(self, terminal):
"""Packs the terminal widget.
"""
if self.terminal is not None:
raise RuntimeError('TerminalBox: terminal already set') # depends on [control=['if'], data=[]]
self.terminal = terminal
self.terminal.connect('grab-focus', self.on_terminal_focus)
self.... |
def _put_policy_set(self, policy_set_id, body):
"""
Will create or update a policy set for the given path.
"""
assert isinstance(body, (dict)), "PUT requires body to be a dict."
uri = self._get_policy_set_uri(guid=policy_set_id)
return self.service._put(uri, body) | def function[_put_policy_set, parameter[self, policy_set_id, body]]:
constant[
Will create or update a policy set for the given path.
]
assert[call[name[isinstance], parameter[name[body], name[dict]]]]
variable[uri] assign[=] call[name[self]._get_policy_set_uri, parameter[]]
retu... | keyword[def] identifier[_put_policy_set] ( identifier[self] , identifier[policy_set_id] , identifier[body] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[body] ,( identifier[dict] )), literal[string]
identifier[uri] = identifier[self] . identifier[_get_policy_set_... | def _put_policy_set(self, policy_set_id, body):
"""
Will create or update a policy set for the given path.
"""
assert isinstance(body, dict), 'PUT requires body to be a dict.'
uri = self._get_policy_set_uri(guid=policy_set_id)
return self.service._put(uri, body) |
def validate_groupby_func(name, args, kwargs, allowed=None):
"""
'args' and 'kwargs' should be empty, except for allowed
kwargs because all of
their necessary parameters are explicitly listed in
the function signature
"""
if allowed is None:
allowed = []
kwargs = set(kwargs) - s... | def function[validate_groupby_func, parameter[name, args, kwargs, allowed]]:
constant[
'args' and 'kwargs' should be empty, except for allowed
kwargs because all of
their necessary parameters are explicitly listed in
the function signature
]
if compare[name[allowed] is constant[None]... | keyword[def] identifier[validate_groupby_func] ( identifier[name] , identifier[args] , identifier[kwargs] , identifier[allowed] = keyword[None] ):
literal[string]
keyword[if] identifier[allowed] keyword[is] keyword[None] :
identifier[allowed] =[]
identifier[kwargs] = identifier[set] ( ide... | def validate_groupby_func(name, args, kwargs, allowed=None):
"""
'args' and 'kwargs' should be empty, except for allowed
kwargs because all of
their necessary parameters are explicitly listed in
the function signature
"""
if allowed is None:
allowed = [] # depends on [control=['if']... |
def _taskdict(task):
'''
Note: No locking is provided. Under normal circumstances, like the other task is not running (e.g. this is running
from the same event loop as the task) or task is the current task, this is fine.
'''
if task is None:
task = asyncio.current_task()
assert task
... | def function[_taskdict, parameter[task]]:
constant[
Note: No locking is provided. Under normal circumstances, like the other task is not running (e.g. this is running
from the same event loop as the task) or task is the current task, this is fine.
]
if compare[name[task] is constant[None]] ... | keyword[def] identifier[_taskdict] ( identifier[task] ):
literal[string]
keyword[if] identifier[task] keyword[is] keyword[None] :
identifier[task] = identifier[asyncio] . identifier[current_task] ()
keyword[assert] identifier[task]
identifier[taskvars] = identifier[getattr] ( ident... | def _taskdict(task):
"""
Note: No locking is provided. Under normal circumstances, like the other task is not running (e.g. this is running
from the same event loop as the task) or task is the current task, this is fine.
"""
if task is None:
task = asyncio.current_task() # depends on [cont... |
def _handle_job_set(function):
"""A decorator for handling `taskhandle.JobSet`\s
A decorator for handling `taskhandle.JobSet`\s for `do` and `undo`
methods of `Change`\s.
"""
def call(self, job_set=taskhandle.NullJobSet()):
job_set.started_job(str(self))
function(self)
job_s... | def function[_handle_job_set, parameter[function]]:
constant[A decorator for handling `taskhandle.JobSet`\s
A decorator for handling `taskhandle.JobSet`\s for `do` and `undo`
methods of `Change`\s.
]
def function[call, parameter[self, job_set]]:
call[name[job_set].started_jo... | keyword[def] identifier[_handle_job_set] ( identifier[function] ):
literal[string]
keyword[def] identifier[call] ( identifier[self] , identifier[job_set] = identifier[taskhandle] . identifier[NullJobSet] ()):
identifier[job_set] . identifier[started_job] ( identifier[str] ( identifier[self] ))
... | def _handle_job_set(function):
"""A decorator for handling `taskhandle.JobSet`\\s
A decorator for handling `taskhandle.JobSet`\\s for `do` and `undo`
methods of `Change`\\s.
"""
def call(self, job_set=taskhandle.NullJobSet()):
job_set.started_job(str(self))
function(self)
j... |
def _get_sampling_freq(self, r):
"""Raises BitReaderError"""
samplingFrequencyIndex = r.bits(4)
if samplingFrequencyIndex == 0xf:
samplingFrequency = r.bits(24)
else:
try:
samplingFrequency = self._FREQS[samplingFrequencyIndex]
except ... | def function[_get_sampling_freq, parameter[self, r]]:
constant[Raises BitReaderError]
variable[samplingFrequencyIndex] assign[=] call[name[r].bits, parameter[constant[4]]]
if compare[name[samplingFrequencyIndex] equal[==] constant[15]] begin[:]
variable[samplingFrequency] assign[... | keyword[def] identifier[_get_sampling_freq] ( identifier[self] , identifier[r] ):
literal[string]
identifier[samplingFrequencyIndex] = identifier[r] . identifier[bits] ( literal[int] )
keyword[if] identifier[samplingFrequencyIndex] == literal[int] :
identifier[samplingFreque... | def _get_sampling_freq(self, r):
"""Raises BitReaderError"""
samplingFrequencyIndex = r.bits(4)
if samplingFrequencyIndex == 15:
samplingFrequency = r.bits(24) # depends on [control=['if'], data=[]]
else:
try:
samplingFrequency = self._FREQS[samplingFrequencyIndex] # depend... |
def create_payload(self):
"""Wrap submitted data within an extra dict.
For more information, see `Bugzilla #1151220
<https://bugzilla.redhat.com/show_bug.cgi?id=1151220>`_.
In addition, rename the ``search_`` field to ``search``.
"""
payload = super(DiscoveryRule, self... | def function[create_payload, parameter[self]]:
constant[Wrap submitted data within an extra dict.
For more information, see `Bugzilla #1151220
<https://bugzilla.redhat.com/show_bug.cgi?id=1151220>`_.
In addition, rename the ``search_`` field to ``search``.
]
variable[p... | keyword[def] identifier[create_payload] ( identifier[self] ):
literal[string]
identifier[payload] = identifier[super] ( identifier[DiscoveryRule] , identifier[self] ). identifier[create_payload] ()
keyword[if] literal[string] keyword[in] identifier[payload] :
identifier[pay... | def create_payload(self):
"""Wrap submitted data within an extra dict.
For more information, see `Bugzilla #1151220
<https://bugzilla.redhat.com/show_bug.cgi?id=1151220>`_.
In addition, rename the ``search_`` field to ``search``.
"""
payload = super(DiscoveryRule, self).create... |
def _generate_key(pass_id, passphrases, salt, algorithm):
'''Generate and return PBKDF2 key'''
if pass_id not in passphrases:
raise Exception('Passphrase not defined for id: %d' % pass_id)
passphrase = passphrases[pass_id]
if len(passphrase) < 32:
raise Excepti... | def function[_generate_key, parameter[pass_id, passphrases, salt, algorithm]]:
constant[Generate and return PBKDF2 key]
if compare[name[pass_id] <ast.NotIn object at 0x7da2590d7190> name[passphrases]] begin[:]
<ast.Raise object at 0x7da2054a6ec0>
variable[passphrase] assign[=] call[name[... | keyword[def] identifier[_generate_key] ( identifier[pass_id] , identifier[passphrases] , identifier[salt] , identifier[algorithm] ):
literal[string]
keyword[if] identifier[pass_id] keyword[not] keyword[in] identifier[passphrases] :
keyword[raise] identifier[Exception] ( literal[s... | def _generate_key(pass_id, passphrases, salt, algorithm):
"""Generate and return PBKDF2 key"""
if pass_id not in passphrases:
raise Exception('Passphrase not defined for id: %d' % pass_id) # depends on [control=['if'], data=['pass_id']]
passphrase = passphrases[pass_id]
if len(passphrase) < 32:... |
def on_input_path_textChanged(self):
"""Action when input file name is changed."""
input_path = self.input_path.text()
input_not_grid_msg = tr('input file is not .xml')
if input_path and not input_path.endswith('.xml'):
self.warning_text.add(input_not_grid_msg)
elif ... | def function[on_input_path_textChanged, parameter[self]]:
constant[Action when input file name is changed.]
variable[input_path] assign[=] call[name[self].input_path.text, parameter[]]
variable[input_not_grid_msg] assign[=] call[name[tr], parameter[constant[input file is not .xml]]]
if <... | keyword[def] identifier[on_input_path_textChanged] ( identifier[self] ):
literal[string]
identifier[input_path] = identifier[self] . identifier[input_path] . identifier[text] ()
identifier[input_not_grid_msg] = identifier[tr] ( literal[string] )
keyword[if] identifier[input_path... | def on_input_path_textChanged(self):
"""Action when input file name is changed."""
input_path = self.input_path.text()
input_not_grid_msg = tr('input file is not .xml')
if input_path and (not input_path.endswith('.xml')):
self.warning_text.add(input_not_grid_msg) # depends on [control=['if'], d... |
def compute(self):
"""
This method can be used for computing one MaxSAT solution,
i.e. for computing an assignment satisfying all hard
clauses of the input formula and maximizing the sum of
weights of satisfied soft clauses. It is a wrapper for the
int... | def function[compute, parameter[self]]:
constant[
This method can be used for computing one MaxSAT solution,
i.e. for computing an assignment satisfying all hard
clauses of the input formula and maximizing the sum of
weights of satisfied soft clauses. It is a wrap... | keyword[def] identifier[compute] ( identifier[self] ):
literal[string]
identifier[res] = identifier[self] . identifier[compute_] ()
keyword[if] identifier[res] :
identifier[self] . identifier[model] = identifier[self] . identifier[oracle] . identifier[get_... | def compute(self):
"""
This method can be used for computing one MaxSAT solution,
i.e. for computing an assignment satisfying all hard
clauses of the input formula and maximizing the sum of
weights of satisfied soft clauses. It is a wrapper for the
interna... |
def output_reduce_list(path_list, force=False):
"""Generates structure file with protons from a list of structure files."""
output_paths = []
for path in path_list:
output_path = output_reduce(path, force=force)
if output_path:
output_paths.append(output_path)
return output_p... | def function[output_reduce_list, parameter[path_list, force]]:
constant[Generates structure file with protons from a list of structure files.]
variable[output_paths] assign[=] list[[]]
for taget[name[path]] in starred[name[path_list]] begin[:]
variable[output_path] assign[=] call... | keyword[def] identifier[output_reduce_list] ( identifier[path_list] , identifier[force] = keyword[False] ):
literal[string]
identifier[output_paths] =[]
keyword[for] identifier[path] keyword[in] identifier[path_list] :
identifier[output_path] = identifier[output_reduce] ( identifier[path] ... | def output_reduce_list(path_list, force=False):
"""Generates structure file with protons from a list of structure files."""
output_paths = []
for path in path_list:
output_path = output_reduce(path, force=force)
if output_path:
output_paths.append(output_path) # depends on [cont... |
def get_service_url(request, redirect_to=None):
"""Generates application django service URL for CAS"""
if hasattr(django_settings, 'CAS_ROOT_PROXIED_AS'):
service = django_settings.CAS_ROOT_PROXIED_AS + request.path
else:
protocol = get_protocol(request)
host = request.get_host()
... | def function[get_service_url, parameter[request, redirect_to]]:
constant[Generates application django service URL for CAS]
if call[name[hasattr], parameter[name[django_settings], constant[CAS_ROOT_PROXIED_AS]]] begin[:]
variable[service] assign[=] binary_operation[name[django_settings].C... | keyword[def] identifier[get_service_url] ( identifier[request] , identifier[redirect_to] = keyword[None] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[django_settings] , literal[string] ):
identifier[service] = identifier[django_settings] . identifier[CAS_ROOT_PROXIED_AS] + iden... | def get_service_url(request, redirect_to=None):
"""Generates application django service URL for CAS"""
if hasattr(django_settings, 'CAS_ROOT_PROXIED_AS'):
service = django_settings.CAS_ROOT_PROXIED_AS + request.path # depends on [control=['if'], data=[]]
else:
protocol = get_protocol(reques... |
def clean_pages_from_space(confluence, space_key, limit=500):
"""
Remove all pages from trash for related space
:param limit:
:param confluence:
:param space_key:
:return:
"""
flag = True
while flag:
values = confluence.get_all_pages_from_space_trash(space=space_key, start=0,... | def function[clean_pages_from_space, parameter[confluence, space_key, limit]]:
constant[
Remove all pages from trash for related space
:param limit:
:param confluence:
:param space_key:
:return:
]
variable[flag] assign[=] constant[True]
while name[flag] begin[:]
... | keyword[def] identifier[clean_pages_from_space] ( identifier[confluence] , identifier[space_key] , identifier[limit] = literal[int] ):
literal[string]
identifier[flag] = keyword[True]
keyword[while] identifier[flag] :
identifier[values] = identifier[confluence] . identifier[get_all_pages_fr... | def clean_pages_from_space(confluence, space_key, limit=500):
"""
Remove all pages from trash for related space
:param limit:
:param confluence:
:param space_key:
:return:
"""
flag = True
while flag:
values = confluence.get_all_pages_from_space_trash(space=space_key, start=0,... |
def _send_message(self, msg):
"""Add message to queue and start processing the queue."""
LWLink.the_queue.put_nowait(msg)
if LWLink.thread is None or not LWLink.thread.isAlive():
LWLink.thread = Thread(target=self._send_queue)
LWLink.thread.start() | def function[_send_message, parameter[self, msg]]:
constant[Add message to queue and start processing the queue.]
call[name[LWLink].the_queue.put_nowait, parameter[name[msg]]]
if <ast.BoolOp object at 0x7da1b01a6200> begin[:]
name[LWLink].thread assign[=] call[name[Thread], param... | keyword[def] identifier[_send_message] ( identifier[self] , identifier[msg] ):
literal[string]
identifier[LWLink] . identifier[the_queue] . identifier[put_nowait] ( identifier[msg] )
keyword[if] identifier[LWLink] . identifier[thread] keyword[is] keyword[None] keyword[or] keyword[not]... | def _send_message(self, msg):
"""Add message to queue and start processing the queue."""
LWLink.the_queue.put_nowait(msg)
if LWLink.thread is None or not LWLink.thread.isAlive():
LWLink.thread = Thread(target=self._send_queue)
LWLink.thread.start() # depends on [control=['if'], data=[]] |
def get_rendered_fields(self, ctx=None):
'''
:param ctx: rendering context in which the method was called
:return: ordered list of the fields that will be rendered
'''
if ctx is None:
ctx = RenderContext()
ctx.push(self)
result = []
for f in se... | def function[get_rendered_fields, parameter[self, ctx]]:
constant[
:param ctx: rendering context in which the method was called
:return: ordered list of the fields that will be rendered
]
if compare[name[ctx] is constant[None]] begin[:]
variable[ctx] assign[=] cal... | keyword[def] identifier[get_rendered_fields] ( identifier[self] , identifier[ctx] = keyword[None] ):
literal[string]
keyword[if] identifier[ctx] keyword[is] keyword[None] :
identifier[ctx] = identifier[RenderContext] ()
identifier[ctx] . identifier[push] ( identifier[self] ... | def get_rendered_fields(self, ctx=None):
"""
:param ctx: rendering context in which the method was called
:return: ordered list of the fields that will be rendered
"""
if ctx is None:
ctx = RenderContext() # depends on [control=['if'], data=['ctx']]
ctx.push(self)
result... |
def from_name(cls, name):
""" Retrieve a snapshot profile accsociated to a name."""
snps = cls.list({'name': name})
if len(snps) == 1:
return snps[0]['id']
elif not snps:
return
raise DuplicateResults('snapshot profile name %s is ambiguous.' % name) | def function[from_name, parameter[cls, name]]:
constant[ Retrieve a snapshot profile accsociated to a name.]
variable[snps] assign[=] call[name[cls].list, parameter[dictionary[[<ast.Constant object at 0x7da20e956050>], [<ast.Name object at 0x7da20e957af0>]]]]
if compare[call[name[len], parameter... | keyword[def] identifier[from_name] ( identifier[cls] , identifier[name] ):
literal[string]
identifier[snps] = identifier[cls] . identifier[list] ({ literal[string] : identifier[name] })
keyword[if] identifier[len] ( identifier[snps] )== literal[int] :
keyword[return] identif... | def from_name(cls, name):
""" Retrieve a snapshot profile accsociated to a name."""
snps = cls.list({'name': name})
if len(snps) == 1:
return snps[0]['id'] # depends on [control=['if'], data=[]]
elif not snps:
return # depends on [control=['if'], data=[]]
raise DuplicateResults('sn... |
def read_yaml_file(self, file_name):
"""
Parses a YAML file into a matrix.
:param file_name: name of the YAML file
:return: a matrix with the file's contents
"""
with open(os.path.join(self.__path(), os.path.basename(file_name)),
'rt') as yamlfile:
... | def function[read_yaml_file, parameter[self, file_name]]:
constant[
Parses a YAML file into a matrix.
:param file_name: name of the YAML file
:return: a matrix with the file's contents
]
with call[name[open], parameter[call[name[os].path.join, parameter[call[name[self]._... | keyword[def] identifier[read_yaml_file] ( identifier[self] , identifier[file_name] ):
literal[string]
keyword[with] identifier[open] ( identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[__path] (), identifier[os] . identifier[path] . identifier[basename] ( identif... | def read_yaml_file(self, file_name):
"""
Parses a YAML file into a matrix.
:param file_name: name of the YAML file
:return: a matrix with the file's contents
"""
with open(os.path.join(self.__path(), os.path.basename(file_name)), 'rt') as yamlfile:
return yaml.load(yamlf... |
def init_plugins(settings):
"""Load plugins and call register()."""
logger = logging.getLogger(__name__)
logger.debug('Plugin paths: %s', settings['plugin_paths'])
for path in settings['plugin_paths']:
sys.path.insert(0, path)
for plugin in settings['plugins']:
try:
if... | def function[init_plugins, parameter[settings]]:
constant[Load plugins and call register().]
variable[logger] assign[=] call[name[logging].getLogger, parameter[name[__name__]]]
call[name[logger].debug, parameter[constant[Plugin paths: %s], call[name[settings]][constant[plugin_paths]]]]
f... | keyword[def] identifier[init_plugins] ( identifier[settings] ):
literal[string]
identifier[logger] = identifier[logging] . identifier[getLogger] ( identifier[__name__] )
identifier[logger] . identifier[debug] ( literal[string] , identifier[settings] [ literal[string] ])
keyword[for] identifier... | def init_plugins(settings):
"""Load plugins and call register()."""
logger = logging.getLogger(__name__)
logger.debug('Plugin paths: %s', settings['plugin_paths'])
for path in settings['plugin_paths']:
sys.path.insert(0, path) # depends on [control=['for'], data=['path']]
for plugin in sett... |
def mul_at(self, other, k):
'''Compute the multiplication between two polynomials only at the specified coefficient (this is a lot cheaper than doing the full polynomial multiplication and then extract only the required coefficient)'''
if k > (self.degree + other.degree) or k > self.degree: return 0 # o... | def function[mul_at, parameter[self, other, k]]:
constant[Compute the multiplication between two polynomials only at the specified coefficient (this is a lot cheaper than doing the full polynomial multiplication and then extract only the required coefficient)]
if <ast.BoolOp object at 0x7da18f00f940> be... | keyword[def] identifier[mul_at] ( identifier[self] , identifier[other] , identifier[k] ):
literal[string]
keyword[if] identifier[k] >( identifier[self] . identifier[degree] + identifier[other] . identifier[degree] ) keyword[or] identifier[k] > identifier[self] . identifier[degree] : keyword[retur... | def mul_at(self, other, k):
"""Compute the multiplication between two polynomials only at the specified coefficient (this is a lot cheaper than doing the full polynomial multiplication and then extract only the required coefficient)"""
if k > self.degree + other.degree or k > self.degree:
return 0 # op... |
def log_batch(self, log_data):
"""Logs batch of messages with attachment.
Args:
log_data: list of log records.
log record is a dict of;
time, message, level, attachment
attachment is a dict of:
name: name of attachment
... | def function[log_batch, parameter[self, log_data]]:
constant[Logs batch of messages with attachment.
Args:
log_data: list of log records.
log record is a dict of;
time, message, level, attachment
attachment is a dict of:
name: ... | keyword[def] identifier[log_batch] ( identifier[self] , identifier[log_data] ):
literal[string]
identifier[url] = identifier[uri_join] ( identifier[self] . identifier[base_url] , literal[string] )
identifier[attachments] =[]
keyword[for] identifier[log_item] keyword[in] ident... | def log_batch(self, log_data):
"""Logs batch of messages with attachment.
Args:
log_data: list of log records.
log record is a dict of;
time, message, level, attachment
attachment is a dict of:
name: name of attachment
... |
def focus(self, model):
"""Sets the passed model as focused element
:param ModelMT model: The element to be focused
"""
if model is None:
del self.focus
return
self._check_model_types(model)
self.add(model)
focus_msg = FocusSignalMsg(mode... | def function[focus, parameter[self, model]]:
constant[Sets the passed model as focused element
:param ModelMT model: The element to be focused
]
if compare[name[model] is constant[None]] begin[:]
<ast.Delete object at 0x7da18ede6170>
return[None]
call[name[self].... | keyword[def] identifier[focus] ( identifier[self] , identifier[model] ):
literal[string]
keyword[if] identifier[model] keyword[is] keyword[None] :
keyword[del] identifier[self] . identifier[focus]
keyword[return]
identifier[self] . identifier[_check_model_t... | def focus(self, model):
"""Sets the passed model as focused element
:param ModelMT model: The element to be focused
"""
if model is None:
del self.focus
return # depends on [control=['if'], data=[]]
self._check_model_types(model)
self.add(model)
focus_msg = FocusSig... |
def find_all_runs(self, session=None):
"""
Return all tasks that have been updated.
"""
with self._session(session) as session:
return session.query(TaskRecord).all() | def function[find_all_runs, parameter[self, session]]:
constant[
Return all tasks that have been updated.
]
with call[name[self]._session, parameter[name[session]]] begin[:]
return[call[call[name[session].query, parameter[name[TaskRecord]]].all, parameter[]]] | keyword[def] identifier[find_all_runs] ( identifier[self] , identifier[session] = keyword[None] ):
literal[string]
keyword[with] identifier[self] . identifier[_session] ( identifier[session] ) keyword[as] identifier[session] :
keyword[return] identifier[session] . identifier[query] ... | def find_all_runs(self, session=None):
"""
Return all tasks that have been updated.
"""
with self._session(session) as session:
return session.query(TaskRecord).all() # depends on [control=['with'], data=['session']] |
def set_actuator_control_target_encode(self, time_usec, group_mlx, target_system, target_component, controls):
'''
Set the vehicle attitude and body angular rates.
time_usec : Timestamp (micros since boot or Unix epoch) (uint64_t)
group_ml... | def function[set_actuator_control_target_encode, parameter[self, time_usec, group_mlx, target_system, target_component, controls]]:
constant[
Set the vehicle attitude and body angular rates.
time_usec : Timestamp (micros since boot or Unix epoch) (uint64_t)
... | keyword[def] identifier[set_actuator_control_target_encode] ( identifier[self] , identifier[time_usec] , identifier[group_mlx] , identifier[target_system] , identifier[target_component] , identifier[controls] ):
literal[string]
keyword[return] identifier[MAVLink_set_actuator_contro... | def set_actuator_control_target_encode(self, time_usec, group_mlx, target_system, target_component, controls):
"""
Set the vehicle attitude and body angular rates.
time_usec : Timestamp (micros since boot or Unix epoch) (uint64_t)
group_mlx ... |
def init_node(cls, *args, **kwargs):
"""Initializes an ast node with the provided attributes.
Python 2.6+ supports this in the node class initializers, but Python 2.5
does not, so this is intended to be an equivalent.
"""
node = cls()
for name, value in zip(cls._fields, args):
seta... | def function[init_node, parameter[cls]]:
constant[Initializes an ast node with the provided attributes.
Python 2.6+ supports this in the node class initializers, but Python 2.5
does not, so this is intended to be an equivalent.
]
variable[node] assign[=] call[name[cls], parameter[]]
... | keyword[def] identifier[init_node] ( identifier[cls] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[node] = identifier[cls] ()
keyword[for] identifier[name] , identifier[value] keyword[in] identifier[zip] ( identifier[cls] . identifier[_fields] , identifier[args] ):
... | def init_node(cls, *args, **kwargs):
"""Initializes an ast node with the provided attributes.
Python 2.6+ supports this in the node class initializers, but Python 2.5
does not, so this is intended to be an equivalent.
"""
node = cls()
for (name, value) in zip(cls._fields, args):
se... |
def get_stacker_env_file(path, environment, region):
"""Determine Stacker environment file name."""
for name in gen_stacker_env_files(environment, region):
if os.path.isfile(os.path.join(path, name)):
return name
return "%s-%s.env" % (environment, region) | def function[get_stacker_env_file, parameter[path, environment, region]]:
constant[Determine Stacker environment file name.]
for taget[name[name]] in starred[call[name[gen_stacker_env_files], parameter[name[environment], name[region]]]] begin[:]
if call[name[os].path.isfile, parameter[ca... | keyword[def] identifier[get_stacker_env_file] ( identifier[path] , identifier[environment] , identifier[region] ):
literal[string]
keyword[for] identifier[name] keyword[in] identifier[gen_stacker_env_files] ( identifier[environment] , identifier[region] ):
keyword[if] identifier[os] . identifi... | def get_stacker_env_file(path, environment, region):
"""Determine Stacker environment file name."""
for name in gen_stacker_env_files(environment, region):
if os.path.isfile(os.path.join(path, name)):
return name # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['... |
def writeGlobalFile(self, localFileName, cleanup=False):
"""
Takes a file (as a path) and uploads it to the job store. Depending on the jobstore
used, carry out the appropriate cache functions.
"""
absLocalFileName = self._resolveAbsoluteLocalPath(localFileName)
# What d... | def function[writeGlobalFile, parameter[self, localFileName, cleanup]]:
constant[
Takes a file (as a path) and uploads it to the job store. Depending on the jobstore
used, carry out the appropriate cache functions.
]
variable[absLocalFileName] assign[=] call[name[self]._resolveA... | keyword[def] identifier[writeGlobalFile] ( identifier[self] , identifier[localFileName] , identifier[cleanup] = keyword[False] ):
literal[string]
identifier[absLocalFileName] = identifier[self] . identifier[_resolveAbsoluteLocalPath] ( identifier[localFileName] )
identifier[cleanu... | def writeGlobalFile(self, localFileName, cleanup=False):
"""
Takes a file (as a path) and uploads it to the job store. Depending on the jobstore
used, carry out the appropriate cache functions.
"""
absLocalFileName = self._resolveAbsoluteLocalPath(localFileName)
# What does this do?... |
def _add(self, error: "Err"):
"""
Adds an error to the trace if required
"""
if self.trace_errs is True:
self.errors.append(error) | def function[_add, parameter[self, error]]:
constant[
Adds an error to the trace if required
]
if compare[name[self].trace_errs is constant[True]] begin[:]
call[name[self].errors.append, parameter[name[error]]] | keyword[def] identifier[_add] ( identifier[self] , identifier[error] : literal[string] ):
literal[string]
keyword[if] identifier[self] . identifier[trace_errs] keyword[is] keyword[True] :
identifier[self] . identifier[errors] . identifier[append] ( identifier[error] ) | def _add(self, error: 'Err'):
"""
Adds an error to the trace if required
"""
if self.trace_errs is True:
self.errors.append(error) # depends on [control=['if'], data=[]] |
def get_license_checker_config_path(config_dir='.'):
# type: (str) -> List[str]
"""Checks for local config overrides for license checker,
if not found it returns the package default.
:param config_dir:
:return: str
"""
if LICENSE_CHECKER_CONFIG_NAME in os.listdir(config_dir):
licens... | def function[get_license_checker_config_path, parameter[config_dir]]:
constant[Checks for local config overrides for license checker,
if not found it returns the package default.
:param config_dir:
:return: str
]
if compare[name[LICENSE_CHECKER_CONFIG_NAME] in call[name[os].listdir, par... | keyword[def] identifier[get_license_checker_config_path] ( identifier[config_dir] = literal[string] ):
literal[string]
keyword[if] identifier[LICENSE_CHECKER_CONFIG_NAME] keyword[in] identifier[os] . identifier[listdir] ( identifier[config_dir] ):
identifier[license_checker_config_path] = iden... | def get_license_checker_config_path(config_dir='.'):
# type: (str) -> List[str]
'Checks for local config overrides for license checker,\n if not found it returns the package default.\n\n :param config_dir:\n :return: str\n '
if LICENSE_CHECKER_CONFIG_NAME in os.listdir(config_dir):
licen... |
def _parse_executable_spec(src_dir, json_file_name, parser):
"""
Returns the parsed contents of a json specification.
Raises WorkflowBuilderException (exit code 3) if this cannot be done.
"""
if not os.path.isdir(src_dir):
parser.error("{} is not a directory".format(src_dir))
if not os.... | def function[_parse_executable_spec, parameter[src_dir, json_file_name, parser]]:
constant[
Returns the parsed contents of a json specification.
Raises WorkflowBuilderException (exit code 3) if this cannot be done.
]
if <ast.UnaryOp object at 0x7da20c6e64d0> begin[:]
call[nam... | keyword[def] identifier[_parse_executable_spec] ( identifier[src_dir] , identifier[json_file_name] , identifier[parser] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isdir] ( identifier[src_dir] ):
identifier[parser] . identifier[error] ( literal[stri... | def _parse_executable_spec(src_dir, json_file_name, parser):
"""
Returns the parsed contents of a json specification.
Raises WorkflowBuilderException (exit code 3) if this cannot be done.
"""
if not os.path.isdir(src_dir):
parser.error('{} is not a directory'.format(src_dir)) # depends on [... |
def tokens_delete(name=None, user=None, read_access_token=None, force=False):
"""Delete a personal OAuth token."""
if not (name or user) and not read_access_token:
click.get_current_context().fail(
'You have to pass either a "name" and "user" or the "token"')
if name and user:
cl... | def function[tokens_delete, parameter[name, user, read_access_token, force]]:
constant[Delete a personal OAuth token.]
if <ast.BoolOp object at 0x7da1b2581780> begin[:]
call[call[name[click].get_current_context, parameter[]].fail, parameter[constant[You have to pass either a "name" and "... | keyword[def] identifier[tokens_delete] ( identifier[name] = keyword[None] , identifier[user] = keyword[None] , identifier[read_access_token] = keyword[None] , identifier[force] = keyword[False] ):
literal[string]
keyword[if] keyword[not] ( identifier[name] keyword[or] identifier[user] ) keyword[and] ke... | def tokens_delete(name=None, user=None, read_access_token=None, force=False):
"""Delete a personal OAuth token."""
if not (name or user) and (not read_access_token):
click.get_current_context().fail('You have to pass either a "name" and "user" or the "token"') # depends on [control=['if'], data=[]]
... |
def self_sign_jwks(keyjar, iss, kid='', lifetime=3600):
"""
Create a signed JWT containing a JWKS. The JWT is signed by one of the
keys in the JWKS.
:param keyjar: A KeyJar instance with at least one private signing key
:param iss: issuer of the JWT, should be the owner of the keys
:param kid: ... | def function[self_sign_jwks, parameter[keyjar, iss, kid, lifetime]]:
constant[
Create a signed JWT containing a JWKS. The JWT is signed by one of the
keys in the JWKS.
:param keyjar: A KeyJar instance with at least one private signing key
:param iss: issuer of the JWT, should be the owner of th... | keyword[def] identifier[self_sign_jwks] ( identifier[keyjar] , identifier[iss] , identifier[kid] = literal[string] , identifier[lifetime] = literal[int] ):
literal[string]
identifier[_jwt] = identifier[JWT] ( identifier[keyjar] , identifier[iss] = identifier[iss] , identifier[lifetime] = identifier[l... | def self_sign_jwks(keyjar, iss, kid='', lifetime=3600):
"""
Create a signed JWT containing a JWKS. The JWT is signed by one of the
keys in the JWKS.
:param keyjar: A KeyJar instance with at least one private signing key
:param iss: issuer of the JWT, should be the owner of the keys
:param kid: ... |
def __capture(self, checkout_id, **kwargs):
"""Call documentation: `/checkout/capture
<https://www.wepay.com/developer/reference/checkout#capture>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``... | def function[__capture, parameter[self, checkout_id]]:
constant[Call documentation: `/checkout/capture
<https://www.wepay.com/developer/reference/checkout#capture>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access... | keyword[def] identifier[__capture] ( identifier[self] , identifier[checkout_id] ,** identifier[kwargs] ):
literal[string]
identifier[params] ={
literal[string] : identifier[checkout_id]
}
keyword[return] identifier[self] . identifier[make_call] ( identifier[self] . ident... | def __capture(self, checkout_id, **kwargs):
"""Call documentation: `/checkout/capture
<https://www.wepay.com/developer/reference/checkout#capture>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batc... |
def sct_report_string(report):
"""Return a human-readable string representation of the error report
returned by lxml's schematron validator.
"""
ret = []
namespaces = {"svrl": "http://purl.oclc.org/dsdl/svrl"}
for index, failed_assert_el in enumerate(
report.findall("svrl:failed-assert",... | def function[sct_report_string, parameter[report]]:
constant[Return a human-readable string representation of the error report
returned by lxml's schematron validator.
]
variable[ret] assign[=] list[[]]
variable[namespaces] assign[=] dictionary[[<ast.Constant object at 0x7da1b1b84730>], ... | keyword[def] identifier[sct_report_string] ( identifier[report] ):
literal[string]
identifier[ret] =[]
identifier[namespaces] ={ literal[string] : literal[string] }
keyword[for] identifier[index] , identifier[failed_assert_el] keyword[in] identifier[enumerate] (
identifier[report] . ident... | def sct_report_string(report):
"""Return a human-readable string representation of the error report
returned by lxml's schematron validator.
"""
ret = []
namespaces = {'svrl': 'http://purl.oclc.org/dsdl/svrl'}
for (index, failed_assert_el) in enumerate(report.findall('svrl:failed-assert', namesp... |
def handle(self, *args, **options):
"""
Run the specified Selenium test(s) the indicated number of times in
the specified browser.
"""
browser_name = options['browser_name']
count = options['count']
if len(args) > 0:
tests = list(args)
else:
... | def function[handle, parameter[self]]:
constant[
Run the specified Selenium test(s) the indicated number of times in
the specified browser.
]
variable[browser_name] assign[=] call[name[options]][constant[browser_name]]
variable[count] assign[=] call[name[options]][constan... | keyword[def] identifier[handle] ( identifier[self] ,* identifier[args] ,** identifier[options] ):
literal[string]
identifier[browser_name] = identifier[options] [ literal[string] ]
identifier[count] = identifier[options] [ literal[string] ]
keyword[if] identifier[len] ( identifie... | def handle(self, *args, **options):
"""
Run the specified Selenium test(s) the indicated number of times in
the specified browser.
"""
browser_name = options['browser_name']
count = options['count']
if len(args) > 0:
tests = list(args) # depends on [control=['if'], data=... |
def apply_mask_4d(image, mask_img): # , smooth_mm=None, remove_nans=True):
"""Read a Nifti file nii_file and a mask Nifti file.
Extract the signals in nii_file that are within the mask, the mask indices
and the mask shape.
Parameters
----------
image: img-like object or boyle.nifti.NeuroImage ... | def function[apply_mask_4d, parameter[image, mask_img]]:
constant[Read a Nifti file nii_file and a mask Nifti file.
Extract the signals in nii_file that are within the mask, the mask indices
and the mask shape.
Parameters
----------
image: img-like object or boyle.nifti.NeuroImage or str
... | keyword[def] identifier[apply_mask_4d] ( identifier[image] , identifier[mask_img] ):
literal[string]
identifier[img] = identifier[check_img] ( identifier[image] )
identifier[mask] = identifier[check_img] ( identifier[mask_img] )
identifier[check_img_compatibility] ( identifier[img] , identifier[m... | def apply_mask_4d(image, mask_img): # , smooth_mm=None, remove_nans=True):
'Read a Nifti file nii_file and a mask Nifti file.\n Extract the signals in nii_file that are within the mask, the mask indices\n and the mask shape.\n\n Parameters\n ----------\n image: img-like object or boyle.nifti.NeuroIm... |
def _parse(
self,
item_iter, # type: Iterable[ET.Element]
state # type: _ProcessorState
):
# type: (...) -> List
"""Parse the array data using the provided iterator of XML elements."""
parsed_array = []
for i, item in enumerate(item_iter):
... | def function[_parse, parameter[self, item_iter, state]]:
constant[Parse the array data using the provided iterator of XML elements.]
variable[parsed_array] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da1b25d2440>, <ast.Name object at 0x7da1b25d3850>]]] in starred[call[name[enumera... | keyword[def] identifier[_parse] (
identifier[self] ,
identifier[item_iter] ,
identifier[state]
):
literal[string]
identifier[parsed_array] =[]
keyword[for] identifier[i] , identifier[item] keyword[in] identifier[enumerate] ( identifier[item_iter] ):
identifier[state] ... | def _parse(self, item_iter, state): # type: Iterable[ET.Element]
# type: _ProcessorState
# type: (...) -> List
'Parse the array data using the provided iterator of XML elements.'
parsed_array = []
for (i, item) in enumerate(item_iter):
state.push_location(self._item_processor.element_path, ... |
def mkdir(self, path, mode=o777):
"""
Create a folder (directory) named ``path`` with numeric mode ``mode``.
The default mode is 0777 (octal). On some systems, mode is ignored.
Where it is used, the current umask value is first masked out.
:param str path: name of the folder to... | def function[mkdir, parameter[self, path, mode]]:
constant[
Create a folder (directory) named ``path`` with numeric mode ``mode``.
The default mode is 0777 (octal). On some systems, mode is ignored.
Where it is used, the current umask value is first masked out.
:param str path:... | keyword[def] identifier[mkdir] ( identifier[self] , identifier[path] , identifier[mode] = identifier[o777] ):
literal[string]
identifier[path] = identifier[self] . identifier[_adjust_cwd] ( identifier[path] )
identifier[self] . identifier[_log] ( identifier[DEBUG] , literal[string] . ident... | def mkdir(self, path, mode=o777):
"""
Create a folder (directory) named ``path`` with numeric mode ``mode``.
The default mode is 0777 (octal). On some systems, mode is ignored.
Where it is used, the current umask value is first masked out.
:param str path: name of the folder to cre... |
def _bnot32(ins):
""" Negates top (Bitwise NOT) of the stack (32 bits in DEHL)
"""
output = _32bit_oper(ins.quad[2])
output.append('call __BNOT32')
output.append('push de')
output.append('push hl')
REQUIRES.add('bnot32.asm')
return output | def function[_bnot32, parameter[ins]]:
constant[ Negates top (Bitwise NOT) of the stack (32 bits in DEHL)
]
variable[output] assign[=] call[name[_32bit_oper], parameter[call[name[ins].quad][constant[2]]]]
call[name[output].append, parameter[constant[call __BNOT32]]]
call[name[output]... | keyword[def] identifier[_bnot32] ( identifier[ins] ):
literal[string]
identifier[output] = identifier[_32bit_oper] ( identifier[ins] . identifier[quad] [ literal[int] ])
identifier[output] . identifier[append] ( literal[string] )
identifier[output] . identifier[append] ( literal[string] )
id... | def _bnot32(ins):
""" Negates top (Bitwise NOT) of the stack (32 bits in DEHL)
"""
output = _32bit_oper(ins.quad[2])
output.append('call __BNOT32')
output.append('push de')
output.append('push hl')
REQUIRES.add('bnot32.asm')
return output |
def intermediary_to_dot(tables, relationships, output):
""" Save the intermediary representation to dot format. """
dot_file = _intermediary_to_dot(tables, relationships)
with open(output, "w") as file_out:
file_out.write(dot_file) | def function[intermediary_to_dot, parameter[tables, relationships, output]]:
constant[ Save the intermediary representation to dot format. ]
variable[dot_file] assign[=] call[name[_intermediary_to_dot], parameter[name[tables], name[relationships]]]
with call[name[open], parameter[name[output], c... | keyword[def] identifier[intermediary_to_dot] ( identifier[tables] , identifier[relationships] , identifier[output] ):
literal[string]
identifier[dot_file] = identifier[_intermediary_to_dot] ( identifier[tables] , identifier[relationships] )
keyword[with] identifier[open] ( identifier[output] , litera... | def intermediary_to_dot(tables, relationships, output):
""" Save the intermediary representation to dot format. """
dot_file = _intermediary_to_dot(tables, relationships)
with open(output, 'w') as file_out:
file_out.write(dot_file) # depends on [control=['with'], data=['file_out']] |
def normalize_query_parameters(query_string):
"""
normalize_query_parameters(query_string) -> dict
Converts a query string into a dictionary mapping parameter names to a
list of the sorted values. This ensurses that the query string follows
% encoding rules according to RFC 3986 and checks for dup... | def function[normalize_query_parameters, parameter[query_string]]:
constant[
normalize_query_parameters(query_string) -> dict
Converts a query string into a dictionary mapping parameter names to a
list of the sorted values. This ensurses that the query string follows
% encoding rules according... | keyword[def] identifier[normalize_query_parameters] ( identifier[query_string] ):
literal[string]
keyword[if] identifier[query_string] == literal[string] :
keyword[return] {}
identifier[components] = identifier[query_string] . identifier[split] ( literal[string] )
identifier[result] ={... | def normalize_query_parameters(query_string):
"""
normalize_query_parameters(query_string) -> dict
Converts a query string into a dictionary mapping parameter names to a
list of the sorted values. This ensurses that the query string follows
% encoding rules according to RFC 3986 and checks for dup... |
def get_bel_stmts(self, filter=False):
"""Get relevant statements from the BEL large corpus.
Performs a series of neighborhood queries and then takes the union of
all the statements. Because the query process can take a long time for
large gene lists, the resulting list of statements ar... | def function[get_bel_stmts, parameter[self, filter]]:
constant[Get relevant statements from the BEL large corpus.
Performs a series of neighborhood queries and then takes the union of
all the statements. Because the query process can take a long time for
large gene lists, the resulting ... | keyword[def] identifier[get_bel_stmts] ( identifier[self] , identifier[filter] = keyword[False] ):
literal[string]
keyword[if] identifier[self] . identifier[basename] keyword[is] keyword[not] keyword[None] :
identifier[bel_stmt_path] = literal[string] % identifier[self] . identifie... | def get_bel_stmts(self, filter=False):
"""Get relevant statements from the BEL large corpus.
Performs a series of neighborhood queries and then takes the union of
all the statements. Because the query process can take a long time for
large gene lists, the resulting list of statements are ca... |
def dst(self, dt):
"""
http://docs.python.org/library/datetime.html#datetime.tzinfo.dst
"""
if self.__is_daylight_time(dt):
return self.__dst_offset - self.__offset
else:
return datetime.timedelta(0) | def function[dst, parameter[self, dt]]:
constant[
http://docs.python.org/library/datetime.html#datetime.tzinfo.dst
]
if call[name[self].__is_daylight_time, parameter[name[dt]]] begin[:]
return[binary_operation[name[self].__dst_offset - name[self].__offset]] | keyword[def] identifier[dst] ( identifier[self] , identifier[dt] ):
literal[string]
keyword[if] identifier[self] . identifier[__is_daylight_time] ( identifier[dt] ):
keyword[return] identifier[self] . identifier[__dst_offset] - identifier[self] . identifier[__offset]
keywor... | def dst(self, dt):
"""
http://docs.python.org/library/datetime.html#datetime.tzinfo.dst
"""
if self.__is_daylight_time(dt):
return self.__dst_offset - self.__offset # depends on [control=['if'], data=[]]
else:
return datetime.timedelta(0) |
def import_words_from_file(self,
inputfile: str,
is_diceware: bool) -> None:
"""Import words for the wordlist from a given file.
The file can have a single column with words or be diceware-like
(two columns).
Keyword argumen... | def function[import_words_from_file, parameter[self, inputfile, is_diceware]]:
constant[Import words for the wordlist from a given file.
The file can have a single column with words or be diceware-like
(two columns).
Keyword arguments:
inputfile -- A string with the path to the... | keyword[def] identifier[import_words_from_file] ( identifier[self] ,
identifier[inputfile] : identifier[str] ,
identifier[is_diceware] : identifier[bool] )-> keyword[None] :
literal[string]
keyword[if] keyword[not] identifier[Aux] . identifier[isfile_notempty] ( identifier[inputfile] ):
... | def import_words_from_file(self, inputfile: str, is_diceware: bool) -> None:
"""Import words for the wordlist from a given file.
The file can have a single column with words or be diceware-like
(two columns).
Keyword arguments:
inputfile -- A string with the path to the wordlist fi... |
def eval(self, script, keys=[], args=[]):
"""Execute a Lua script server side."""
return self.execute(b'EVAL', script, len(keys), *(keys + args)) | def function[eval, parameter[self, script, keys, args]]:
constant[Execute a Lua script server side.]
return[call[name[self].execute, parameter[constant[b'EVAL'], name[script], call[name[len], parameter[name[keys]]], <ast.Starred object at 0x7da2041dbdc0>]]] | keyword[def] identifier[eval] ( identifier[self] , identifier[script] , identifier[keys] =[], identifier[args] =[]):
literal[string]
keyword[return] identifier[self] . identifier[execute] ( literal[string] , identifier[script] , identifier[len] ( identifier[keys] ),*( identifier[keys] + identifier... | def eval(self, script, keys=[], args=[]):
"""Execute a Lua script server side."""
return self.execute(b'EVAL', script, len(keys), *keys + args) |
def validateDtdFinal(self, doc):
"""Does the final step for the dtds validation once all the
subsets have been parsed basically it does the following
checks described by the XML Rec - check that ENTITY and
ENTITIES type attributes default or possible values matches
one o... | def function[validateDtdFinal, parameter[self, doc]]:
constant[Does the final step for the dtds validation once all the
subsets have been parsed basically it does the following
checks described by the XML Rec - check that ENTITY and
ENTITIES type attributes default or possible val... | keyword[def] identifier[validateDtdFinal] ( identifier[self] , identifier[doc] ):
literal[string]
keyword[if] identifier[doc] keyword[is] keyword[None] : identifier[doc__o] = keyword[None]
keyword[else] : identifier[doc__o] = identifier[doc] . identifier[_o]
identifier[ret] =... | def validateDtdFinal(self, doc):
"""Does the final step for the dtds validation once all the
subsets have been parsed basically it does the following
checks described by the XML Rec - check that ENTITY and
ENTITIES type attributes default or possible values matches
one of th... |
def past(self, rev=None):
"""Return a Mapping of items at or before the given revision.
Default revision is the last one looked up.
"""
if rev is not None:
self.seek(rev)
return WindowDictPastView(self._past) | def function[past, parameter[self, rev]]:
constant[Return a Mapping of items at or before the given revision.
Default revision is the last one looked up.
]
if compare[name[rev] is_not constant[None]] begin[:]
call[name[self].seek, parameter[name[rev]]]
return[call[n... | keyword[def] identifier[past] ( identifier[self] , identifier[rev] = keyword[None] ):
literal[string]
keyword[if] identifier[rev] keyword[is] keyword[not] keyword[None] :
identifier[self] . identifier[seek] ( identifier[rev] )
keyword[return] identifier[WindowDictPastView... | def past(self, rev=None):
"""Return a Mapping of items at or before the given revision.
Default revision is the last one looked up.
"""
if rev is not None:
self.seek(rev) # depends on [control=['if'], data=['rev']]
return WindowDictPastView(self._past) |
def run_daemon(self):
"""
Used as daemon starter.
Warning:
DO NOT OVERRIDE THIS.
"""
try:
self.daemon_runner.do_action()
except daemon.runner.DaemonRunnerStopFailureError:
self.onStopFail()
except SystemExit:
self.o... | def function[run_daemon, parameter[self]]:
constant[
Used as daemon starter.
Warning:
DO NOT OVERRIDE THIS.
]
<ast.Try object at 0x7da1b09be6e0> | keyword[def] identifier[run_daemon] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[self] . identifier[daemon_runner] . identifier[do_action] ()
keyword[except] identifier[daemon] . identifier[runner] . identifier[DaemonRunnerStopFailureError] :
i... | def run_daemon(self):
"""
Used as daemon starter.
Warning:
DO NOT OVERRIDE THIS.
"""
try:
self.daemon_runner.do_action() # depends on [control=['try'], data=[]]
except daemon.runner.DaemonRunnerStopFailureError:
self.onStopFail() # depends on [control=[... |
def _get_perm_obj_or_404(self, pk=None):
"""
If is send parameter pk is returned object according this pk,
else is returned object from get_obj method, but it search only inside filtered values for current user,
finally if object is still None is returned according the input key from all... | def function[_get_perm_obj_or_404, parameter[self, pk]]:
constant[
If is send parameter pk is returned object according this pk,
else is returned object from get_obj method, but it search only inside filtered values for current user,
finally if object is still None is returned according ... | keyword[def] identifier[_get_perm_obj_or_404] ( identifier[self] , identifier[pk] = keyword[None] ):
literal[string]
keyword[if] identifier[pk] :
identifier[obj] = identifier[get_object_or_none] ( identifier[self] . identifier[core] . identifier[model] , identifier[pk] = identifier[pk... | def _get_perm_obj_or_404(self, pk=None):
"""
If is send parameter pk is returned object according this pk,
else is returned object from get_obj method, but it search only inside filtered values for current user,
finally if object is still None is returned according the input key from all obj... |
def add_option(self, section, name, value):
"""Add an option to a section of the unit file
Args:
section (str): The name of the section, If it doesn't exist it will be created
name (str): The name of the option to add
value (str): The value of the option
Ret... | def function[add_option, parameter[self, section, name, value]]:
constant[Add an option to a section of the unit file
Args:
section (str): The name of the section, If it doesn't exist it will be created
name (str): The name of the option to add
value (str): The value... | keyword[def] identifier[add_option] ( identifier[self] , identifier[section] , identifier[name] , identifier[value] ):
literal[string]
keyword[if] identifier[self] . identifier[_is_live] ():
keyword[raise] identifier[RuntimeError] ( literal[string] )
identifier[op... | def add_option(self, section, name, value):
"""Add an option to a section of the unit file
Args:
section (str): The name of the section, If it doesn't exist it will be created
name (str): The name of the option to add
value (str): The value of the option
Returns... |
def upvotes(self, option):
"""
Set whether to filter by a user's upvoted list. Options available are
user.ONLY, user.NOT, and None; default is None.
"""
params = join_params(self.parameters, {"upvotes": option})
return self.__class__(**params) | def function[upvotes, parameter[self, option]]:
constant[
Set whether to filter by a user's upvoted list. Options available are
user.ONLY, user.NOT, and None; default is None.
]
variable[params] assign[=] call[name[join_params], parameter[name[self].parameters, dictionary[[<ast.Constant obje... | keyword[def] identifier[upvotes] ( identifier[self] , identifier[option] ):
literal[string]
identifier[params] = identifier[join_params] ( identifier[self] . identifier[parameters] ,{ literal[string] : identifier[option] })
keyword[return] identifier[self] . identifier[__class__] (** identifier[para... | def upvotes(self, option):
"""
Set whether to filter by a user's upvoted list. Options available are
user.ONLY, user.NOT, and None; default is None.
"""
params = join_params(self.parameters, {'upvotes': option})
return self.__class__(**params) |
def result_dataframe(count, x, width, xmin=None, xmax=None):
"""
Create a dataframe to hold bin information
"""
if xmin is None:
xmin = x-width/2
if xmax is None:
xmax = x+width/2
# Eliminate any numerical roundoff discrepancies
# between the edges
xmin[1:] = xmax[:-1]
... | def function[result_dataframe, parameter[count, x, width, xmin, xmax]]:
constant[
Create a dataframe to hold bin information
]
if compare[name[xmin] is constant[None]] begin[:]
variable[xmin] assign[=] binary_operation[name[x] - binary_operation[name[width] / constant[2]]]
... | keyword[def] identifier[result_dataframe] ( identifier[count] , identifier[x] , identifier[width] , identifier[xmin] = keyword[None] , identifier[xmax] = keyword[None] ):
literal[string]
keyword[if] identifier[xmin] keyword[is] keyword[None] :
identifier[xmin] = identifier[x] - identifier[width... | def result_dataframe(count, x, width, xmin=None, xmax=None):
"""
Create a dataframe to hold bin information
"""
if xmin is None:
xmin = x - width / 2 # depends on [control=['if'], data=['xmin']]
if xmax is None:
xmax = x + width / 2 # depends on [control=['if'], data=['xmax']]
... |
def CQO(cpu):
"""
RDX:RAX = sign-extend of RAX.
"""
res = Operators.SEXTEND(cpu.RAX, 64, 128)
cpu.RAX = Operators.EXTRACT(res, 0, 64)
cpu.RDX = Operators.EXTRACT(res, 64, 64) | def function[CQO, parameter[cpu]]:
constant[
RDX:RAX = sign-extend of RAX.
]
variable[res] assign[=] call[name[Operators].SEXTEND, parameter[name[cpu].RAX, constant[64], constant[128]]]
name[cpu].RAX assign[=] call[name[Operators].EXTRACT, parameter[name[res], constant[0], consta... | keyword[def] identifier[CQO] ( identifier[cpu] ):
literal[string]
identifier[res] = identifier[Operators] . identifier[SEXTEND] ( identifier[cpu] . identifier[RAX] , literal[int] , literal[int] )
identifier[cpu] . identifier[RAX] = identifier[Operators] . identifier[EXTRACT] ( identifier[r... | def CQO(cpu):
"""
RDX:RAX = sign-extend of RAX.
"""
res = Operators.SEXTEND(cpu.RAX, 64, 128)
cpu.RAX = Operators.EXTRACT(res, 0, 64)
cpu.RDX = Operators.EXTRACT(res, 64, 64) |
def _extend_component_definitions(self, graph):
"""
Read graph and update component definitions with related elements
"""
for def_uri, comp_def in self._components.items():
# Store created components indexed for later lookup
component_index = {}
identi... | def function[_extend_component_definitions, parameter[self, graph]]:
constant[
Read graph and update component definitions with related elements
]
for taget[tuple[[<ast.Name object at 0x7da2047ebe20>, <ast.Name object at 0x7da2047e9210>]]] in starred[call[name[self]._components.items, pa... | keyword[def] identifier[_extend_component_definitions] ( identifier[self] , identifier[graph] ):
literal[string]
keyword[for] identifier[def_uri] , identifier[comp_def] keyword[in] identifier[self] . identifier[_components] . identifier[items] ():
identifier[component_index... | def _extend_component_definitions(self, graph):
"""
Read graph and update component definitions with related elements
"""
for (def_uri, comp_def) in self._components.items():
# Store created components indexed for later lookup
component_index = {}
identity = URIRef(def_ur... |
def generate_voxel_grid(bbox, szval, use_cubes=False):
""" Generates the voxel grid with the desired size.
:param bbox: bounding box
:type bbox: list, tuple
:param szval: size in x-, y-, z-directions
:type szval: list, tuple
:param use_cubes: use cube voxels instead of cuboid ones
:type use... | def function[generate_voxel_grid, parameter[bbox, szval, use_cubes]]:
constant[ Generates the voxel grid with the desired size.
:param bbox: bounding box
:type bbox: list, tuple
:param szval: size in x-, y-, z-directions
:type szval: list, tuple
:param use_cubes: use cube voxels instead of ... | keyword[def] identifier[generate_voxel_grid] ( identifier[bbox] , identifier[szval] , identifier[use_cubes] = keyword[False] ):
literal[string]
keyword[if] identifier[szval] [ literal[int] ]<= literal[int] keyword[or] identifier[szval] [ literal[int] ]<= literal[int] keyword[or] identifier[szval]... | def generate_voxel_grid(bbox, szval, use_cubes=False):
""" Generates the voxel grid with the desired size.
:param bbox: bounding box
:type bbox: list, tuple
:param szval: size in x-, y-, z-directions
:type szval: list, tuple
:param use_cubes: use cube voxels instead of cuboid ones
:type use... |
def precipitation(self, val):
""""Precipitation is a value in [-1,1]"""
try:
data, thresholds = val
except ValueError:
raise ValueError("Pass an iterable: (data, thresholds)")
else:
if data.shape[0] != self.height:
raise Exception("Sett... | def function[precipitation, parameter[self, val]]:
constant["Precipitation is a value in [-1,1]]
<ast.Try object at 0x7da1b0655180> | keyword[def] identifier[precipitation] ( identifier[self] , identifier[val] ):
literal[string]
keyword[try] :
identifier[data] , identifier[thresholds] = identifier[val]
keyword[except] identifier[ValueError] :
keyword[raise] identifier[ValueError] ( literal[st... | def precipitation(self, val):
""""Precipitation is a value in [-1,1]"""
try:
(data, thresholds) = val # depends on [control=['try'], data=[]]
except ValueError:
raise ValueError('Pass an iterable: (data, thresholds)') # depends on [control=['except'], data=[]]
else:
if data.sha... |
def word(self, _id, padding=75):
"""
Get words
"""
word = self.words[_id][2]
vec = word_to_vector(word)
vec += [-1] * (padding - len(vec))
return np.array(vec, dtype=np.int32) | def function[word, parameter[self, _id, padding]]:
constant[
Get words
]
variable[word] assign[=] call[call[name[self].words][name[_id]]][constant[2]]
variable[vec] assign[=] call[name[word_to_vector], parameter[name[word]]]
<ast.AugAssign object at 0x7da1b1ff50f0>
return... | keyword[def] identifier[word] ( identifier[self] , identifier[_id] , identifier[padding] = literal[int] ):
literal[string]
identifier[word] = identifier[self] . identifier[words] [ identifier[_id] ][ literal[int] ]
identifier[vec] = identifier[word_to_vector] ( identifier[word] )
... | def word(self, _id, padding=75):
"""
Get words
"""
word = self.words[_id][2]
vec = word_to_vector(word)
vec += [-1] * (padding - len(vec))
return np.array(vec, dtype=np.int32) |
def any(self, values, axis=0):
"""compute if any item evaluates to true in each group
Parameters
----------
values : array_like, [keys, ...]
values to take boolean predicate over per group
axis : int, optional
alternative reduction axis for values
... | def function[any, parameter[self, values, axis]]:
constant[compute if any item evaluates to true in each group
Parameters
----------
values : array_like, [keys, ...]
values to take boolean predicate over per group
axis : int, optional
alternative reductio... | keyword[def] identifier[any] ( identifier[self] , identifier[values] , identifier[axis] = literal[int] ):
literal[string]
identifier[values] = identifier[np] . identifier[asarray] ( identifier[values] )
keyword[if] keyword[not] identifier[values] . identifier[dtype] == identifier[np] . i... | def any(self, values, axis=0):
"""compute if any item evaluates to true in each group
Parameters
----------
values : array_like, [keys, ...]
values to take boolean predicate over per group
axis : int, optional
alternative reduction axis for values
Re... |
def _create_element(name, element_type, data, server=None):
'''
Create a new element
'''
# Define property and id from name and properties + remove SaltStack parameters
if 'properties' in data:
data['property'] = ''
for key, value in data['properties'].items():
if not dat... | def function[_create_element, parameter[name, element_type, data, server]]:
constant[
Create a new element
]
if compare[constant[properties] in name[data]] begin[:]
call[name[data]][constant[property]] assign[=] constant[]
for taget[tuple[[<ast.Name object at 0x7d... | keyword[def] identifier[_create_element] ( identifier[name] , identifier[element_type] , identifier[data] , identifier[server] = keyword[None] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[data] :
identifier[data] [ literal[string] ]= literal[string]
keywo... | def _create_element(name, element_type, data, server=None):
"""
Create a new element
"""
# Define property and id from name and properties + remove SaltStack parameters
if 'properties' in data:
data['property'] = ''
for (key, value) in data['properties'].items():
if not d... |
def hyperparameters(self):
"""Return hyperparameters used by your custom Chainer code during training."""
hyperparameters = super(Chainer, self).hyperparameters()
additional_hyperparameters = {Chainer._use_mpi: self.use_mpi,
Chainer._num_processes: self.num... | def function[hyperparameters, parameter[self]]:
constant[Return hyperparameters used by your custom Chainer code during training.]
variable[hyperparameters] assign[=] call[call[name[super], parameter[name[Chainer], name[self]]].hyperparameters, parameter[]]
variable[additional_hyperparameters] a... | keyword[def] identifier[hyperparameters] ( identifier[self] ):
literal[string]
identifier[hyperparameters] = identifier[super] ( identifier[Chainer] , identifier[self] ). identifier[hyperparameters] ()
identifier[additional_hyperparameters] ={ identifier[Chainer] . identifier[_use_mpi] : ... | def hyperparameters(self):
"""Return hyperparameters used by your custom Chainer code during training."""
hyperparameters = super(Chainer, self).hyperparameters()
additional_hyperparameters = {Chainer._use_mpi: self.use_mpi, Chainer._num_processes: self.num_processes, Chainer._process_slots_per_host: self.p... |
def spec_compliant_encrypt(claims, jwk, add_header=None, alg='RSA-OAEP',
enc='A128CBC-HS256', rng=get_random_bytes):
""" Encrypts the given claims and produces a :class:`~jose.JWE`
:param claims: A `dict` representing the claims for this
:class:`~jose.JWE`.
:pa... | def function[spec_compliant_encrypt, parameter[claims, jwk, add_header, alg, enc, rng]]:
constant[ Encrypts the given claims and produces a :class:`~jose.JWE`
:param claims: A `dict` representing the claims for this
:class:`~jose.JWE`.
:param jwk: A `dict` representing the JWK to be ... | keyword[def] identifier[spec_compliant_encrypt] ( identifier[claims] , identifier[jwk] , identifier[add_header] = keyword[None] , identifier[alg] = literal[string] ,
identifier[enc] = literal[string] , identifier[rng] = identifier[get_random_bytes] ):
literal[string]
identifier[header] = identif... | def spec_compliant_encrypt(claims, jwk, add_header=None, alg='RSA-OAEP', enc='A128CBC-HS256', rng=get_random_bytes):
""" Encrypts the given claims and produces a :class:`~jose.JWE`
:param claims: A `dict` representing the claims for this
:class:`~jose.JWE`.
:param jwk: A `dict` represent... |
def mass_3d_lens(self, R, Rs, theta_Rs):
"""
mass enclosed a 3d sphere or radius r
:param r:
:param Ra:
:param Rs:
:return:
"""
rho0 = self._alpha2rho0(theta_Rs, Rs)
m_3d = self.mass_3d(R, Rs, rho0)
return m_3d | def function[mass_3d_lens, parameter[self, R, Rs, theta_Rs]]:
constant[
mass enclosed a 3d sphere or radius r
:param r:
:param Ra:
:param Rs:
:return:
]
variable[rho0] assign[=] call[name[self]._alpha2rho0, parameter[name[theta_Rs], name[Rs]]]
vari... | keyword[def] identifier[mass_3d_lens] ( identifier[self] , identifier[R] , identifier[Rs] , identifier[theta_Rs] ):
literal[string]
identifier[rho0] = identifier[self] . identifier[_alpha2rho0] ( identifier[theta_Rs] , identifier[Rs] )
identifier[m_3d] = identifier[self] . identifier[mass_... | def mass_3d_lens(self, R, Rs, theta_Rs):
"""
mass enclosed a 3d sphere or radius r
:param r:
:param Ra:
:param Rs:
:return:
"""
rho0 = self._alpha2rho0(theta_Rs, Rs)
m_3d = self.mass_3d(R, Rs, rho0)
return m_3d |
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_2_0):
"""
Read the data encoding the DefaultsInformation structure and decode it
into its constituent parts.
Args:
input_buffer (stream): A data stream containing encoded object
data, supporting... | def function[read, parameter[self, input_buffer, kmip_version]]:
constant[
Read the data encoding the DefaultsInformation structure and decode it
into its constituent parts.
Args:
input_buffer (stream): A data stream containing encoded object
data, supporting... | keyword[def] identifier[read] ( identifier[self] , identifier[input_buffer] , identifier[kmip_version] = identifier[enums] . identifier[KMIPVersion] . identifier[KMIP_2_0] ):
literal[string]
keyword[if] identifier[kmip_version] < identifier[enums] . identifier[KMIPVersion] . identifier[KMIP_2_0] :... | def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_2_0):
"""
Read the data encoding the DefaultsInformation structure and decode it
into its constituent parts.
Args:
input_buffer (stream): A data stream containing encoded object
data, supporting a r... |
def variability_prob(self, whiteness):
"""Use the probability of the spectral variability
to identify clouds over land.
Equation 15 (Zhu and Woodcock, 2012)
Parameters
----------
ndvi: ndarray
ndsi: ndarray
whiteness: ndarray
Output
------
... | def function[variability_prob, parameter[self, whiteness]]:
constant[Use the probability of the spectral variability
to identify clouds over land.
Equation 15 (Zhu and Woodcock, 2012)
Parameters
----------
ndvi: ndarray
ndsi: ndarray
whiteness: ndarray
... | keyword[def] identifier[variability_prob] ( identifier[self] , identifier[whiteness] ):
literal[string]
keyword[if] identifier[self] . identifier[sat] keyword[in] [ literal[string] , literal[string] ]:
identifier[mod_ndvi] = identifier[np] . identifier[where] ( id... | def variability_prob(self, whiteness):
"""Use the probability of the spectral variability
to identify clouds over land.
Equation 15 (Zhu and Woodcock, 2012)
Parameters
----------
ndvi: ndarray
ndsi: ndarray
whiteness: ndarray
Output
------
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.