code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _reverse_problem_hparams(p_hparams):
"""Swap input/output modalities, vocab, and space ids."""
p = p_hparams
# Swap modalities.
# TODO(trandustin): Note this assumes target modalities have feature name
# 'target', and each intended feature to swap has feature name 'input'.
# In the future, remove need ... | def function[_reverse_problem_hparams, parameter[p_hparams]]:
constant[Swap input/output modalities, vocab, and space ids.]
variable[p] assign[=] name[p_hparams]
variable[reversed_modality] assign[=] dictionary[[], []]
for taget[name[feature_name]] in starred[name[p].modality] begin[:]
... | keyword[def] identifier[_reverse_problem_hparams] ( identifier[p_hparams] ):
literal[string]
identifier[p] = identifier[p_hparams]
identifier[reversed_modality] ={}
keyword[for] identifier[feature_name] keyword[in] identifier[p] . identifier[modality] :
identifier[reversed_feature_n... | def _reverse_problem_hparams(p_hparams):
"""Swap input/output modalities, vocab, and space ids."""
p = p_hparams
# Swap modalities.
# TODO(trandustin): Note this assumes target modalities have feature name
# 'target', and each intended feature to swap has feature name 'input'.
# In the future, r... |
def get_max_return(self, weights, returns):
"""
Maximizes the returns of a portfolio.
"""
def func(weights):
"""The objective function that maximizes returns."""
return np.dot(weights, returns.values) * -1
constraints = ({'type': 'eq', 'fun': lambda weig... | def function[get_max_return, parameter[self, weights, returns]]:
constant[
Maximizes the returns of a portfolio.
]
def function[func, parameter[weights]]:
constant[The objective function that maximizes returns.]
return[binary_operation[call[name[np].dot, parameter... | keyword[def] identifier[get_max_return] ( identifier[self] , identifier[weights] , identifier[returns] ):
literal[string]
keyword[def] identifier[func] ( identifier[weights] ):
literal[string]
keyword[return] identifier[np] . identifier[dot] ( identifier[weights] , ide... | def get_max_return(self, weights, returns):
"""
Maximizes the returns of a portfolio.
"""
def func(weights):
"""The objective function that maximizes returns."""
return np.dot(weights, returns.values) * -1
constraints = {'type': 'eq', 'fun': lambda weights: weights.sum() - 1... |
def update(self, first_reading=False):
"""Read raw data and update compensated variables."""
try:
if first_reading or not self._ok:
self._bus.write_byte_data(self._i2c_add, 0xF2,
self.ctrl_hum_reg)
self._bus.write_byte... | def function[update, parameter[self, first_reading]]:
constant[Read raw data and update compensated variables.]
<ast.Try object at 0x7da20c7cac20>
variable[pres_raw] assign[=] binary_operation[binary_operation[binary_operation[call[name[data]][constant[0]] <ast.LShift object at 0x7da2590d69e0> const... | keyword[def] identifier[update] ( identifier[self] , identifier[first_reading] = keyword[False] ):
literal[string]
keyword[try] :
keyword[if] identifier[first_reading] keyword[or] keyword[not] identifier[self] . identifier[_ok] :
identifier[self] . identifier[_bus]... | def update(self, first_reading=False):
"""Read raw data and update compensated variables."""
try:
if first_reading or not self._ok:
self._bus.write_byte_data(self._i2c_add, 242, self.ctrl_hum_reg)
self._bus.write_byte_data(self._i2c_add, 245, self.config_reg)
self._bu... |
def pesn(number, separator=u''):
'''
Printable Pseudo Electronic Serial Number.
:param number: hexadecimal string
>>> print(pesn('1B69B4BA630F34E'))
805F9EF7
'''
number = re.sub(r'[\s-]', '', meid(number))
serial = hashlib.sha1(unhexlify(number[:14]))
return separator.join(['80', ... | def function[pesn, parameter[number, separator]]:
constant[
Printable Pseudo Electronic Serial Number.
:param number: hexadecimal string
>>> print(pesn('1B69B4BA630F34E'))
805F9EF7
]
variable[number] assign[=] call[name[re].sub, parameter[constant[[\s-]], constant[], call[name[meid... | keyword[def] identifier[pesn] ( identifier[number] , identifier[separator] = literal[string] ):
literal[string]
identifier[number] = identifier[re] . identifier[sub] ( literal[string] , literal[string] , identifier[meid] ( identifier[number] ))
identifier[serial] = identifier[hashlib] . identifier[sh... | def pesn(number, separator=u''):
"""
Printable Pseudo Electronic Serial Number.
:param number: hexadecimal string
>>> print(pesn('1B69B4BA630F34E'))
805F9EF7
"""
number = re.sub('[\\s-]', '', meid(number))
serial = hashlib.sha1(unhexlify(number[:14]))
return separator.join(['80', s... |
def plot_lifetimes(
durations,
event_observed=None,
entry=None,
left_truncated=False,
sort_by_duration=True,
event_observed_color="#A60628",
event_censored_color="#348ABD",
**kwargs
):
"""
Returns a lifetime plot, see examples: https://lifelines.readthedocs.io/en/latest/Survival%... | def function[plot_lifetimes, parameter[durations, event_observed, entry, left_truncated, sort_by_duration, event_observed_color, event_censored_color]]:
constant[
Returns a lifetime plot, see examples: https://lifelines.readthedocs.io/en/latest/Survival%20Analysis%20intro.html#Censoring
Parameters
... | keyword[def] identifier[plot_lifetimes] (
identifier[durations] ,
identifier[event_observed] = keyword[None] ,
identifier[entry] = keyword[None] ,
identifier[left_truncated] = keyword[False] ,
identifier[sort_by_duration] = keyword[True] ,
identifier[event_observed_color] = literal[string] ,
identifier[event_c... | def plot_lifetimes(durations, event_observed=None, entry=None, left_truncated=False, sort_by_duration=True, event_observed_color='#A60628', event_censored_color='#348ABD', **kwargs):
"""
Returns a lifetime plot, see examples: https://lifelines.readthedocs.io/en/latest/Survival%20Analysis%20intro.html#Censoring
... |
def read_pickle(path, compression='infer'):
"""
Load pickled pandas object (or any object) from file.
.. warning::
Loading pickled data received from untrusted sources can be
unsafe. See `here <https://docs.python.org/3/library/pickle.html>`__.
Parameters
----------
path : str
... | def function[read_pickle, parameter[path, compression]]:
constant[
Load pickled pandas object (or any object) from file.
.. warning::
Loading pickled data received from untrusted sources can be
unsafe. See `here <https://docs.python.org/3/library/pickle.html>`__.
Parameters
----... | keyword[def] identifier[read_pickle] ( identifier[path] , identifier[compression] = literal[string] ):
literal[string]
identifier[path] = identifier[_stringify_path] ( identifier[path] )
identifier[f] , identifier[fh] = identifier[_get_handle] ( identifier[path] , literal[string] , identifier[compress... | def read_pickle(path, compression='infer'):
"""
Load pickled pandas object (or any object) from file.
.. warning::
Loading pickled data received from untrusted sources can be
unsafe. See `here <https://docs.python.org/3/library/pickle.html>`__.
Parameters
----------
path : str
... |
def list_files(self, project):
"""
List files in the project on computes
"""
path = "/projects/{}/files".format(project.id)
res = yield from self.http_query("GET", path, timeout=120)
return res.json | def function[list_files, parameter[self, project]]:
constant[
List files in the project on computes
]
variable[path] assign[=] call[constant[/projects/{}/files].format, parameter[name[project].id]]
variable[res] assign[=] <ast.YieldFrom object at 0x7da204962860>
return[name[r... | keyword[def] identifier[list_files] ( identifier[self] , identifier[project] ):
literal[string]
identifier[path] = literal[string] . identifier[format] ( identifier[project] . identifier[id] )
identifier[res] = keyword[yield] keyword[from] identifier[self] . identifier[http_query] ( lite... | def list_files(self, project):
"""
List files in the project on computes
"""
path = '/projects/{}/files'.format(project.id)
res = (yield from self.http_query('GET', path, timeout=120))
return res.json |
def wda(X, y, p=2, reg=1, k=10, solver=None, maxiter=100, verbose=0, P0=None):
"""
Wasserstein Discriminant Analysis [11]_
The function solves the following optimization problem:
.. math::
P = \\text{arg}\min_P \\frac{\\sum_i W(PX^i,PX^i)}{\\sum_{i,j\\neq i} W(PX^i,PX^j)}
where :
- :... | def function[wda, parameter[X, y, p, reg, k, solver, maxiter, verbose, P0]]:
constant[
Wasserstein Discriminant Analysis [11]_
The function solves the following optimization problem:
.. math::
P = \text{arg}\min_P \frac{\sum_i W(PX^i,PX^i)}{\sum_{i,j\neq i} W(PX^i,PX^j)}
where :
... | keyword[def] identifier[wda] ( identifier[X] , identifier[y] , identifier[p] = literal[int] , identifier[reg] = literal[int] , identifier[k] = literal[int] , identifier[solver] = keyword[None] , identifier[maxiter] = literal[int] , identifier[verbose] = literal[int] , identifier[P0] = keyword[None] ):
literal[st... | def wda(X, y, p=2, reg=1, k=10, solver=None, maxiter=100, verbose=0, P0=None):
"""
Wasserstein Discriminant Analysis [11]_
The function solves the following optimization problem:
.. math::
P = \\text{arg}\\min_P \\frac{\\sum_i W(PX^i,PX^i)}{\\sum_{i,j\\neq i} W(PX^i,PX^j)}
where :
- ... |
def mach2cas(Mach, H):
"""Mach number to Calibrated Airspeed"""
Vtas = mach2tas(Mach, H)
Vcas = tas2cas(Vtas, H)
return Vcas | def function[mach2cas, parameter[Mach, H]]:
constant[Mach number to Calibrated Airspeed]
variable[Vtas] assign[=] call[name[mach2tas], parameter[name[Mach], name[H]]]
variable[Vcas] assign[=] call[name[tas2cas], parameter[name[Vtas], name[H]]]
return[name[Vcas]] | keyword[def] identifier[mach2cas] ( identifier[Mach] , identifier[H] ):
literal[string]
identifier[Vtas] = identifier[mach2tas] ( identifier[Mach] , identifier[H] )
identifier[Vcas] = identifier[tas2cas] ( identifier[Vtas] , identifier[H] )
keyword[return] identifier[Vcas] | def mach2cas(Mach, H):
"""Mach number to Calibrated Airspeed"""
Vtas = mach2tas(Mach, H)
Vcas = tas2cas(Vtas, H)
return Vcas |
def _infer_spaces(s):
"""
Uses dynamic programming to infer the location of spaces in a string
without spaces.
"""
s = s.lower()
# Find the best match for the i first characters, assuming cost has
# been built for the i-1 first characters.
# Returns a pair (match_cost, match_length).
... | def function[_infer_spaces, parameter[s]]:
constant[
Uses dynamic programming to infer the location of spaces in a string
without spaces.
]
variable[s] assign[=] call[name[s].lower, parameter[]]
def function[best_match, parameter[i]]:
variable[candidates] assign[=] ca... | keyword[def] identifier[_infer_spaces] ( identifier[s] ):
literal[string]
identifier[s] = identifier[s] . identifier[lower] ()
keyword[def] identifier[best_match] ( identifier[i] ):
identifier[candidates] = identifier[enumerate] ( identifier[reversed] ( identifier[cost] [ ide... | def _infer_spaces(s):
"""
Uses dynamic programming to infer the location of spaces in a string
without spaces.
"""
s = s.lower()
# Find the best match for the i first characters, assuming cost has
# been built for the i-1 first characters.
# Returns a pair (match_cost, match_length).
... |
def signOp(self,
op: Dict,
identifier: Identifier=None) -> Request:
"""
Signs the message if a signer is configured
:param identifier: signing identifier; if not supplied the default for
the wallet is used.
:param op: Operation to be signed
... | def function[signOp, parameter[self, op, identifier]]:
constant[
Signs the message if a signer is configured
:param identifier: signing identifier; if not supplied the default for
the wallet is used.
:param op: Operation to be signed
:return: a signed Request object
... | keyword[def] identifier[signOp] ( identifier[self] ,
identifier[op] : identifier[Dict] ,
identifier[identifier] : identifier[Identifier] = keyword[None] )-> identifier[Request] :
literal[string]
identifier[request] = identifier[Request] ( identifier[operation] = identifier[op] ,
identifi... | def signOp(self, op: Dict, identifier: Identifier=None) -> Request:
"""
Signs the message if a signer is configured
:param identifier: signing identifier; if not supplied the default for
the wallet is used.
:param op: Operation to be signed
:return: a signed Request obje... |
def _to_string(self):
"""
Return a string representing this location.
"""
parts = [self.org, self.course, self.run, self.block_type, self.block_id]
return u"+".join(parts) | def function[_to_string, parameter[self]]:
constant[
Return a string representing this location.
]
variable[parts] assign[=] list[[<ast.Attribute object at 0x7da18fe92cb0>, <ast.Attribute object at 0x7da18fe93100>, <ast.Attribute object at 0x7da18fe91bd0>, <ast.Attribute object at 0x7da1... | keyword[def] identifier[_to_string] ( identifier[self] ):
literal[string]
identifier[parts] =[ identifier[self] . identifier[org] , identifier[self] . identifier[course] , identifier[self] . identifier[run] , identifier[self] . identifier[block_type] , identifier[self] . identifier[block_id] ]
... | def _to_string(self):
"""
Return a string representing this location.
"""
parts = [self.org, self.course, self.run, self.block_type, self.block_id]
return u'+'.join(parts) |
def auth_interactive(self, username, handler, event, submethods=''):
"""
response_list = handler(title, instructions, prompt_list)
"""
self.transport.lock.acquire()
try:
self.auth_event = event
self.auth_method = 'keyboard-interactive'
self.use... | def function[auth_interactive, parameter[self, username, handler, event, submethods]]:
constant[
response_list = handler(title, instructions, prompt_list)
]
call[name[self].transport.lock.acquire, parameter[]]
<ast.Try object at 0x7da1b0f11ed0> | keyword[def] identifier[auth_interactive] ( identifier[self] , identifier[username] , identifier[handler] , identifier[event] , identifier[submethods] = literal[string] ):
literal[string]
identifier[self] . identifier[transport] . identifier[lock] . identifier[acquire] ()
keyword[try] :
... | def auth_interactive(self, username, handler, event, submethods=''):
"""
response_list = handler(title, instructions, prompt_list)
"""
self.transport.lock.acquire()
try:
self.auth_event = event
self.auth_method = 'keyboard-interactive'
self.username = username
... |
def _force_on_change(self):
"""
Handle force_on_change feature.
"""
for layout in self.force_on_change:
if layout in self.available_combinations:
if self.active_layout != layout:
self.displayed = layout
self._apply(force... | def function[_force_on_change, parameter[self]]:
constant[
Handle force_on_change feature.
]
for taget[name[layout]] in starred[name[self].force_on_change] begin[:]
if compare[name[layout] in name[self].available_combinations] begin[:]
if compare[n... | keyword[def] identifier[_force_on_change] ( identifier[self] ):
literal[string]
keyword[for] identifier[layout] keyword[in] identifier[self] . identifier[force_on_change] :
keyword[if] identifier[layout] keyword[in] identifier[self] . identifier[available_combinations] :
... | def _force_on_change(self):
"""
Handle force_on_change feature.
"""
for layout in self.force_on_change:
if layout in self.available_combinations:
if self.active_layout != layout:
self.displayed = layout
self._apply(force=True)
s... |
def parse(self):
"""Parse options and handle defaults.
When using OptionParser, returns tuple (options,args) of
options and list of non-option command line arguments. When
using ArgumentParser, returns Namespace object containing both
options and arguments. In other words, parse... | def function[parse, parameter[self]]:
constant[Parse options and handle defaults.
When using OptionParser, returns tuple (options,args) of
options and list of non-option command line arguments. When
using ArgumentParser, returns Namespace object containing both
options and argum... | keyword[def] identifier[parse] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[parseTool] == literal[string] :
identifier[self] . identifier[options] = identifier[self] . identifier[parser] . identifier[parse_args] ()
keyword[else] :
... | def parse(self):
"""Parse options and handle defaults.
When using OptionParser, returns tuple (options,args) of
options and list of non-option command line arguments. When
using ArgumentParser, returns Namespace object containing both
options and arguments. In other words, parse() r... |
def _compute_distance_term(self, C, mag, dists):
"""
Computes the distance scaling term, as contained within equation (1b)
"""
return ((C['theta2'] + C['theta14'] + C['theta3'] *
(mag - 7.8)) * np.log(dists.rhypo + self.CONSTS['c4'] *
np.exp((mag - 6.) * s... | def function[_compute_distance_term, parameter[self, C, mag, dists]]:
constant[
Computes the distance scaling term, as contained within equation (1b)
]
return[binary_operation[binary_operation[binary_operation[binary_operation[binary_operation[call[name[C]][constant[theta2]] + call[name[C]][... | keyword[def] identifier[_compute_distance_term] ( identifier[self] , identifier[C] , identifier[mag] , identifier[dists] ):
literal[string]
keyword[return] (( identifier[C] [ literal[string] ]+ identifier[C] [ literal[string] ]+ identifier[C] [ literal[string] ]*
( identifier[mag] - literal... | def _compute_distance_term(self, C, mag, dists):
"""
Computes the distance scaling term, as contained within equation (1b)
"""
return (C['theta2'] + C['theta14'] + C['theta3'] * (mag - 7.8)) * np.log(dists.rhypo + self.CONSTS['c4'] * np.exp((mag - 6.0) * self.CONSTS['theta9'])) + C['theta6'] * d... |
def heappop_max(heap):
"""Maxheap version of a heappop."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
returnitem = heap[0]
heap[0] = lastelt
_siftup_max(heap, 0)
return returnitem
return lastelt | def function[heappop_max, parameter[heap]]:
constant[Maxheap version of a heappop.]
variable[lastelt] assign[=] call[name[heap].pop, parameter[]]
if name[heap] begin[:]
variable[returnitem] assign[=] call[name[heap]][constant[0]]
call[name[heap]][constant[0]] assi... | keyword[def] identifier[heappop_max] ( identifier[heap] ):
literal[string]
identifier[lastelt] = identifier[heap] . identifier[pop] ()
keyword[if] identifier[heap] :
identifier[returnitem] = identifier[heap] [ literal[int] ]
identifier[heap] [ literal[int] ]= identifier[lastelt]
... | def heappop_max(heap):
"""Maxheap version of a heappop."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
returnitem = heap[0]
heap[0] = lastelt
_siftup_max(heap, 0)
return returnitem # depends on [control=['if'], data=[]]
return lastelt |
def poller_tasker_handler(event, context): # pylint: disable=W0613
"""
Historical VPC Poller Tasker.
The Poller is run at a set interval in order to ensure that changes do not go undetected by Historical.
Historical pollers generate `polling events` which simulate changes. These polling events contai... | def function[poller_tasker_handler, parameter[event, context]]:
constant[
Historical VPC Poller Tasker.
The Poller is run at a set interval in order to ensure that changes do not go undetected by Historical.
Historical pollers generate `polling events` which simulate changes. These polling events ... | keyword[def] identifier[poller_tasker_handler] ( identifier[event] , identifier[context] ):
literal[string]
identifier[LOG] . identifier[debug] ( literal[string] )
identifier[queue_url] = identifier[get_queue_url] ( identifier[os] . identifier[environ] . identifier[get] ( literal[string] , literal[st... | def poller_tasker_handler(event, context): # pylint: disable=W0613
'\n Historical VPC Poller Tasker.\n\n The Poller is run at a set interval in order to ensure that changes do not go undetected by Historical.\n\n Historical pollers generate `polling events` which simulate changes. These polling events con... |
def _compute_aggregation(aggregation: str, data: Iterable[Any]):
"""
Compute the specified aggregation on the given data.
:param aggregation: the name of an arbitrary NumPy function (e.g., mean, max, median, nanmean, ...)
or one of :py:attr:`EXTRA_AGGREGATIONS`.
... | def function[_compute_aggregation, parameter[aggregation, data]]:
constant[
Compute the specified aggregation on the given data.
:param aggregation: the name of an arbitrary NumPy function (e.g., mean, max, median, nanmean, ...)
or one of :py:attr:`EXTRA_AGGREGATIONS... | keyword[def] identifier[_compute_aggregation] ( identifier[aggregation] : identifier[str] , identifier[data] : identifier[Iterable] [ identifier[Any] ]):
literal[string]
identifier[ComputeStats] . identifier[_raise_check_aggregation] ( identifier[aggregation] )
keyword[if] identifier[aggr... | def _compute_aggregation(aggregation: str, data: Iterable[Any]):
"""
Compute the specified aggregation on the given data.
:param aggregation: the name of an arbitrary NumPy function (e.g., mean, max, median, nanmean, ...)
or one of :py:attr:`EXTRA_AGGREGATIONS`.
... |
def get_all_access_keys(user_name, marker=None, max_items=None,
region=None, key=None, keyid=None, profile=None):
'''
Get all access keys from a user.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_iam.get_all_access_keys myuser
... | def function[get_all_access_keys, parameter[user_name, marker, max_items, region, key, keyid, profile]]:
constant[
Get all access keys from a user.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_iam.get_all_access_keys myuser
]
variable[co... | keyword[def] identifier[get_all_access_keys] ( identifier[user_name] , identifier[marker] = keyword[None] , identifier[max_items] = keyword[None] ,
identifier[region] = keyword[None] , identifier[key] = keyword[None] , identifier[keyid] = keyword[None] , identifier[profile] = keyword[None] ):
literal[string]
... | def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None):
"""
Get all access keys from a user.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_iam.get_all_access_keys myuser
"""
conn = _get_co... |
def add_highdepth_genome_exclusion(items):
"""Add exclusions to input items to avoid slow runtimes on whole genomes.
"""
out = []
for d in items:
d = utils.deepish_copy(d)
if dd.get_coverage_interval(d) == "genome":
e = dd.get_exclude_regions(d)
if "highdepth" not... | def function[add_highdepth_genome_exclusion, parameter[items]]:
constant[Add exclusions to input items to avoid slow runtimes on whole genomes.
]
variable[out] assign[=] list[[]]
for taget[name[d]] in starred[name[items]] begin[:]
variable[d] assign[=] call[name[utils].deepis... | keyword[def] identifier[add_highdepth_genome_exclusion] ( identifier[items] ):
literal[string]
identifier[out] =[]
keyword[for] identifier[d] keyword[in] identifier[items] :
identifier[d] = identifier[utils] . identifier[deepish_copy] ( identifier[d] )
keyword[if] identifier[dd] ... | def add_highdepth_genome_exclusion(items):
"""Add exclusions to input items to avoid slow runtimes on whole genomes.
"""
out = []
for d in items:
d = utils.deepish_copy(d)
if dd.get_coverage_interval(d) == 'genome':
e = dd.get_exclude_regions(d)
if 'highdepth' not... |
def add_resource(self, data):
"""Add binary resource
:param string data: Binary Data
"""
data = gntp.shim.b(data)
identifier = hashlib.md5(data).hexdigest()
self.resources[identifier] = data
return 'x-growl-resource://%s' % identifier | def function[add_resource, parameter[self, data]]:
constant[Add binary resource
:param string data: Binary Data
]
variable[data] assign[=] call[name[gntp].shim.b, parameter[name[data]]]
variable[identifier] assign[=] call[call[name[hashlib].md5, parameter[name[data]]].hexdigest, parameter[]... | keyword[def] identifier[add_resource] ( identifier[self] , identifier[data] ):
literal[string]
identifier[data] = identifier[gntp] . identifier[shim] . identifier[b] ( identifier[data] )
identifier[identifier] = identifier[hashlib] . identifier[md5] ( identifier[data] ). identifier[hexdigest] ()
identifi... | def add_resource(self, data):
"""Add binary resource
:param string data: Binary Data
"""
data = gntp.shim.b(data)
identifier = hashlib.md5(data).hexdigest()
self.resources[identifier] = data
return 'x-growl-resource://%s' % identifier |
def analyze(self, chunkSize, *sinks):
""" Figure out the best diffs to use to reach all our required volumes. """
measureSize = False
if self.measureSize:
for sink in sinks:
if sink.isRemote:
measureSize = True
# Use destination (already ... | def function[analyze, parameter[self, chunkSize]]:
constant[ Figure out the best diffs to use to reach all our required volumes. ]
variable[measureSize] assign[=] constant[False]
if name[self].measureSize begin[:]
for taget[name[sink]] in starred[name[sinks]] begin[:]
... | keyword[def] identifier[analyze] ( identifier[self] , identifier[chunkSize] ,* identifier[sinks] ):
literal[string]
identifier[measureSize] = keyword[False]
keyword[if] identifier[self] . identifier[measureSize] :
keyword[for] identifier[sink] keyword[in] identifier[sinks... | def analyze(self, chunkSize, *sinks):
""" Figure out the best diffs to use to reach all our required volumes. """
measureSize = False
if self.measureSize:
for sink in sinks:
if sink.isRemote:
measureSize = True # depends on [control=['if'], data=[]] # depends on [contr... |
def __up_cmp(self, obj1, obj2):
"""Defines how our updatable objects should be sorted"""
if obj1.update_order > obj2.update_order:
return 1
elif obj1.update_order < obj2.update_order:
return -1
else:
return 0 | def function[__up_cmp, parameter[self, obj1, obj2]]:
constant[Defines how our updatable objects should be sorted]
if compare[name[obj1].update_order greater[>] name[obj2].update_order] begin[:]
return[constant[1]] | keyword[def] identifier[__up_cmp] ( identifier[self] , identifier[obj1] , identifier[obj2] ):
literal[string]
keyword[if] identifier[obj1] . identifier[update_order] > identifier[obj2] . identifier[update_order] :
keyword[return] literal[int]
keyword[elif] identifier[obj1]... | def __up_cmp(self, obj1, obj2):
"""Defines how our updatable objects should be sorted"""
if obj1.update_order > obj2.update_order:
return 1 # depends on [control=['if'], data=[]]
elif obj1.update_order < obj2.update_order:
return -1 # depends on [control=['if'], data=[]]
else:
... |
def is_timeout(self):
'''
Check if the lapse between initialization and now is more than ``self.timeout``.
'''
lapse = datetime.datetime.now() - self.init_time
return lapse > datetime.timedelta(seconds=self.timeout) | def function[is_timeout, parameter[self]]:
constant[
Check if the lapse between initialization and now is more than ``self.timeout``.
]
variable[lapse] assign[=] binary_operation[call[name[datetime].datetime.now, parameter[]] - name[self].init_time]
return[compare[name[lapse] greater... | keyword[def] identifier[is_timeout] ( identifier[self] ):
literal[string]
identifier[lapse] = identifier[datetime] . identifier[datetime] . identifier[now] ()- identifier[self] . identifier[init_time]
keyword[return] identifier[lapse] > identifier[datetime] . identifier[timedelta] ( iden... | def is_timeout(self):
"""
Check if the lapse between initialization and now is more than ``self.timeout``.
"""
lapse = datetime.datetime.now() - self.init_time
return lapse > datetime.timedelta(seconds=self.timeout) |
def find_method(self, decl):
"""Find class method to call for declaration based on name."""
name = decl.name
method = None
try:
method = getattr(self, u'do_{}'.format(
(name).replace('-', '_')))
except AttributeError:
if name.s... | def function[find_method, parameter[self, decl]]:
constant[Find class method to call for declaration based on name.]
variable[name] assign[=] name[decl].name
variable[method] assign[=] constant[None]
<ast.Try object at 0x7da18c4cd660>
if name[method] begin[:]
call[nam... | keyword[def] identifier[find_method] ( identifier[self] , identifier[decl] ):
literal[string]
identifier[name] = identifier[decl] . identifier[name]
identifier[method] = keyword[None]
keyword[try] :
identifier[method] = identifier[getattr] ( identifier[self] , liter... | def find_method(self, decl):
"""Find class method to call for declaration based on name."""
name = decl.name
method = None
try:
method = getattr(self, u'do_{}'.format(name.replace('-', '_'))) # depends on [control=['try'], data=[]]
except AttributeError:
if name.startswith('data-'):... |
def verify_response(response, status_code, content_type=None):
"""Verifies that a response has the expected status and content type.
Args:
response: The ResponseTuple to be checked.
status_code: An int, the HTTP status code to be compared with response
status.
content_type: A string w... | def function[verify_response, parameter[response, status_code, content_type]]:
constant[Verifies that a response has the expected status and content type.
Args:
response: The ResponseTuple to be checked.
status_code: An int, the HTTP status code to be compared with response
status.
... | keyword[def] identifier[verify_response] ( identifier[response] , identifier[status_code] , identifier[content_type] = keyword[None] ):
literal[string]
identifier[status] = identifier[int] ( identifier[response] . identifier[status] . identifier[split] ( literal[string] , literal[int] )[ literal[int] ])
... | def verify_response(response, status_code, content_type=None):
"""Verifies that a response has the expected status and content type.
Args:
response: The ResponseTuple to be checked.
status_code: An int, the HTTP status code to be compared with response
status.
content_type: A string w... |
def set_standby_timeout(timeout, power='ac', scheme=None):
'''
Set the standby timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer sleeps
power (str):
Set the value for AC or DC power. Default is ``ac`... | def function[set_standby_timeout, parameter[timeout, power, scheme]]:
constant[
Set the standby timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer sleeps
power (str):
Set the value for AC or DC po... | keyword[def] identifier[set_standby_timeout] ( identifier[timeout] , identifier[power] = literal[string] , identifier[scheme] = keyword[None] ):
literal[string]
keyword[return] identifier[_set_powercfg_value] (
identifier[scheme] = identifier[scheme] ,
identifier[sub_group] = literal[string] ,
... | def set_standby_timeout(timeout, power='ac', scheme=None):
"""
Set the standby timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer sleeps
power (str):
Set the value for AC or DC power. Default is ``ac`... |
def array_bytes(array):
""" Estimates the memory of the supplied array in bytes """
return np.product(array.shape)*np.dtype(array.dtype).itemsize | def function[array_bytes, parameter[array]]:
constant[ Estimates the memory of the supplied array in bytes ]
return[binary_operation[call[name[np].product, parameter[name[array].shape]] * call[name[np].dtype, parameter[name[array].dtype]].itemsize]] | keyword[def] identifier[array_bytes] ( identifier[array] ):
literal[string]
keyword[return] identifier[np] . identifier[product] ( identifier[array] . identifier[shape] )* identifier[np] . identifier[dtype] ( identifier[array] . identifier[dtype] ). identifier[itemsize] | def array_bytes(array):
""" Estimates the memory of the supplied array in bytes """
return np.product(array.shape) * np.dtype(array.dtype).itemsize |
async def start_component(workload: CoroutineFunction[T], *args: Any, **kwargs: Any) -> Component[T]:
"""\
Starts the passed `workload` with additional `commands` and `events` pipes.
The workload will be executed as a task.
A simple example. Note that here, the component is exclusively reacting to comm... | <ast.AsyncFunctionDef object at 0x7da20c794b80> | keyword[async] keyword[def] identifier[start_component] ( identifier[workload] : identifier[CoroutineFunction] [ identifier[T] ],* identifier[args] : identifier[Any] ,** identifier[kwargs] : identifier[Any] )-> identifier[Component] [ identifier[T] ]:
literal[string]
identifier[commands_a] , identifier[c... | async def start_component(workload: CoroutineFunction[T], *args: Any, **kwargs: Any) -> Component[T]:
""" Starts the passed `workload` with additional `commands` and `events` pipes.
The workload will be executed as a task.
A simple example. Note that here, the component is exclusively reacting to comman... |
def _list_clouds(self):
"""
Request a list of all added clouds.
Populates self._clouds dict with mist.client.model.Cloud instances
"""
req = self.request(self.uri + '/clouds')
clouds = req.get().json()
if clouds:
for cloud in clouds:
s... | def function[_list_clouds, parameter[self]]:
constant[
Request a list of all added clouds.
Populates self._clouds dict with mist.client.model.Cloud instances
]
variable[req] assign[=] call[name[self].request, parameter[binary_operation[name[self].uri + constant[/clouds]]]]
... | keyword[def] identifier[_list_clouds] ( identifier[self] ):
literal[string]
identifier[req] = identifier[self] . identifier[request] ( identifier[self] . identifier[uri] + literal[string] )
identifier[clouds] = identifier[req] . identifier[get] (). identifier[json] ()
keyword[if] ... | def _list_clouds(self):
"""
Request a list of all added clouds.
Populates self._clouds dict with mist.client.model.Cloud instances
"""
req = self.request(self.uri + '/clouds')
clouds = req.get().json()
if clouds:
for cloud in clouds:
self._clouds[cloud['id']]... |
def message_from_string(s, *args, **kws):
"""Parse a string into a Message object model.
Optional _class and strict are passed to the Parser constructor.
"""
from future.backports.email.parser import Parser
return Parser(*args, **kws).parsestr(s) | def function[message_from_string, parameter[s]]:
constant[Parse a string into a Message object model.
Optional _class and strict are passed to the Parser constructor.
]
from relative_module[future.backports.email.parser] import module[Parser]
return[call[call[name[Parser], parameter[<ast.Starre... | keyword[def] identifier[message_from_string] ( identifier[s] ,* identifier[args] ,** identifier[kws] ):
literal[string]
keyword[from] identifier[future] . identifier[backports] . identifier[email] . identifier[parser] keyword[import] identifier[Parser]
keyword[return] identifier[Parser] (* identi... | def message_from_string(s, *args, **kws):
"""Parse a string into a Message object model.
Optional _class and strict are passed to the Parser constructor.
"""
from future.backports.email.parser import Parser
return Parser(*args, **kws).parsestr(s) |
def _analyze_function(self):
"""
Go over the variable information in variable manager for this function, and return all uninitialized
register/stack variables.
:return:
"""
if not self._function.is_simprocedure \
and not self._function.is_plt \
... | def function[_analyze_function, parameter[self]]:
constant[
Go over the variable information in variable manager for this function, and return all uninitialized
register/stack variables.
:return:
]
if <ast.BoolOp object at 0x7da18dc05090> begin[:]
call[na... | keyword[def] identifier[_analyze_function] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_function] . identifier[is_simprocedure] keyword[and] keyword[not] identifier[self] . identifier[_function] . identifier[is_plt] keyword[and] keyword[not] ... | def _analyze_function(self):
"""
Go over the variable information in variable manager for this function, and return all uninitialized
register/stack variables.
:return:
"""
if not self._function.is_simprocedure and (not self._function.is_plt) and (not self._variable_manager.has_... |
def update(self, cookies):
"""Add specified cookies to our cookie jar, and persists it.
:param cookies: Any iterable that yields http.cookiejar.Cookie instances, such as a CookieJar.
"""
cookie_jar = self.get_cookie_jar()
for cookie in cookies:
cookie_jar.set_cookie(cookie)
with self._loc... | def function[update, parameter[self, cookies]]:
constant[Add specified cookies to our cookie jar, and persists it.
:param cookies: Any iterable that yields http.cookiejar.Cookie instances, such as a CookieJar.
]
variable[cookie_jar] assign[=] call[name[self].get_cookie_jar, parameter[]]
... | keyword[def] identifier[update] ( identifier[self] , identifier[cookies] ):
literal[string]
identifier[cookie_jar] = identifier[self] . identifier[get_cookie_jar] ()
keyword[for] identifier[cookie] keyword[in] identifier[cookies] :
identifier[cookie_jar] . identifier[set_cookie] ( identifier... | def update(self, cookies):
"""Add specified cookies to our cookie jar, and persists it.
:param cookies: Any iterable that yields http.cookiejar.Cookie instances, such as a CookieJar.
"""
cookie_jar = self.get_cookie_jar()
for cookie in cookies:
cookie_jar.set_cookie(cookie) # depends on [c... |
def update_domain_smarthost(self, domainid, serverid, data):
"""Update a domain smarthost"""
return self.api_call(
ENDPOINTS['domainsmarthosts']['update'],
dict(domainid=domainid, serverid=serverid),
body=data) | def function[update_domain_smarthost, parameter[self, domainid, serverid, data]]:
constant[Update a domain smarthost]
return[call[name[self].api_call, parameter[call[call[name[ENDPOINTS]][constant[domainsmarthosts]]][constant[update]], call[name[dict], parameter[]]]]] | keyword[def] identifier[update_domain_smarthost] ( identifier[self] , identifier[domainid] , identifier[serverid] , identifier[data] ):
literal[string]
keyword[return] identifier[self] . identifier[api_call] (
identifier[ENDPOINTS] [ literal[string] ][ literal[string] ],
identifi... | def update_domain_smarthost(self, domainid, serverid, data):
"""Update a domain smarthost"""
return self.api_call(ENDPOINTS['domainsmarthosts']['update'], dict(domainid=domainid, serverid=serverid), body=data) |
def solve_potts_autogamma(y, w, beta=None, **kw):
"""Solve Potts problem with automatically determined gamma.
The optimal value is determined by minimizing the information measure::
f(gamma) = beta J(x(gamma)) + log sum(abs(x(gamma) - y)**p)
where x(gamma) is the solution to the Potts problem for... | def function[solve_potts_autogamma, parameter[y, w, beta]]:
constant[Solve Potts problem with automatically determined gamma.
The optimal value is determined by minimizing the information measure::
f(gamma) = beta J(x(gamma)) + log sum(abs(x(gamma) - y)**p)
where x(gamma) is the solution to t... | keyword[def] identifier[solve_potts_autogamma] ( identifier[y] , identifier[w] , identifier[beta] = keyword[None] ,** identifier[kw] ):
literal[string]
identifier[n] = identifier[len] ( identifier[y] )
keyword[if] identifier[n] == literal[int] :
keyword[return] [],[],[], keyword[None]
... | def solve_potts_autogamma(y, w, beta=None, **kw):
"""Solve Potts problem with automatically determined gamma.
The optimal value is determined by minimizing the information measure::
f(gamma) = beta J(x(gamma)) + log sum(abs(x(gamma) - y)**p)
where x(gamma) is the solution to the Potts problem for... |
def do_classdesc(self, parent=None, ident=0):
"""
Handles a TC_CLASSDESC opcode
:param parent:
:param ident: Log indentation level
:return: A JavaClass object
"""
# TC_CLASSDESC className serialVersionUID newHandle classDescInfo
# classDescInfo:
#... | def function[do_classdesc, parameter[self, parent, ident]]:
constant[
Handles a TC_CLASSDESC opcode
:param parent:
:param ident: Log indentation level
:return: A JavaClass object
]
variable[clazz] assign[=] call[name[JavaClass], parameter[]]
call[name[log... | keyword[def] identifier[do_classdesc] ( identifier[self] , identifier[parent] = keyword[None] , identifier[ident] = literal[int] ):
literal[string]
identifier[clazz] = iden... | def do_classdesc(self, parent=None, ident=0):
"""
Handles a TC_CLASSDESC opcode
:param parent:
:param ident: Log indentation level
:return: A JavaClass object
"""
# TC_CLASSDESC className serialVersionUID newHandle classDescInfo
# classDescInfo:
# classDescFlag... |
def subscribe(
self,
plan,
charge_immediately=True,
application_fee_percent=None,
coupon=None,
quantity=None,
metadata=None,
tax_percent=None,
billing_cycle_anchor=None,
trial_end=None,
trial_from_plan=None,
trial_period_days=None,
):
"""
Subscribes this customer to a plan.
:param plan: ... | def function[subscribe, parameter[self, plan, charge_immediately, application_fee_percent, coupon, quantity, metadata, tax_percent, billing_cycle_anchor, trial_end, trial_from_plan, trial_period_days]]:
constant[
Subscribes this customer to a plan.
:param plan: The plan to which to subscribe the customer.
... | keyword[def] identifier[subscribe] (
identifier[self] ,
identifier[plan] ,
identifier[charge_immediately] = keyword[True] ,
identifier[application_fee_percent] = keyword[None] ,
identifier[coupon] = keyword[None] ,
identifier[quantity] = keyword[None] ,
identifier[metadata] = keyword[None] ,
identifier[tax_pe... | def subscribe(self, plan, charge_immediately=True, application_fee_percent=None, coupon=None, quantity=None, metadata=None, tax_percent=None, billing_cycle_anchor=None, trial_end=None, trial_from_plan=None, trial_period_days=None):
"""
Subscribes this customer to a plan.
:param plan: The plan to which to subsc... |
async def send_poll(self, chat_id: typing.Union[base.Integer, base.String],
question: base.String,
options: typing.List[base.String],
disable_notification: typing.Optional[base.Boolean],
reply_to_message_id: typing.Union[bas... | <ast.AsyncFunctionDef object at 0x7da1b18ff100> | keyword[async] keyword[def] identifier[send_poll] ( identifier[self] , identifier[chat_id] : identifier[typing] . identifier[Union] [ identifier[base] . identifier[Integer] , identifier[base] . identifier[String] ],
identifier[question] : identifier[base] . identifier[String] ,
identifier[options] : identifier[typ... | async def send_poll(self, chat_id: typing.Union[base.Integer, base.String], question: base.String, options: typing.List[base.String], disable_notification: typing.Optional[base.Boolean], reply_to_message_id: typing.Union[base.Integer, None], reply_markup: typing.Union[types.InlineKeyboardMarkup, types.ReplyKeyboardMark... |
def argmin(self, axis=None, skipna=True, *args, **kwargs):
"""
Returns the indices of the minimum values along an axis.
See `numpy.ndarray.argmin` for more information on the
`axis` parameter.
See Also
--------
numpy.ndarray.argmin
"""
nv.validat... | def function[argmin, parameter[self, axis, skipna]]:
constant[
Returns the indices of the minimum values along an axis.
See `numpy.ndarray.argmin` for more information on the
`axis` parameter.
See Also
--------
numpy.ndarray.argmin
]
call[name[nv... | keyword[def] identifier[argmin] ( identifier[self] , identifier[axis] = keyword[None] , identifier[skipna] = keyword[True] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[nv] . identifier[validate_argmin] ( identifier[args] , identifier[kwargs] )
identifier[nv] . i... | def argmin(self, axis=None, skipna=True, *args, **kwargs):
"""
Returns the indices of the minimum values along an axis.
See `numpy.ndarray.argmin` for more information on the
`axis` parameter.
See Also
--------
numpy.ndarray.argmin
"""
nv.validate_argmin... |
def snip_this(tag="",write_date=True):
""" When this function is invoced in a notebook cell, the cell is snipped. """
snip(tag=tag,start=-1,write_date=write_date) | def function[snip_this, parameter[tag, write_date]]:
constant[ When this function is invoced in a notebook cell, the cell is snipped. ]
call[name[snip], parameter[]] | keyword[def] identifier[snip_this] ( identifier[tag] = literal[string] , identifier[write_date] = keyword[True] ):
literal[string]
identifier[snip] ( identifier[tag] = identifier[tag] , identifier[start] =- literal[int] , identifier[write_date] = identifier[write_date] ) | def snip_this(tag='', write_date=True):
""" When this function is invoced in a notebook cell, the cell is snipped. """
snip(tag=tag, start=-1, write_date=write_date) |
def authorized_response(self, args=None):
"""Handles authorization response smartly."""
if args is None:
args = request.args
if 'oauth_verifier' in args:
data = self.handle_oauth1_response(args)
elif 'code' in args:
data = self.handle_oauth2_response(a... | def function[authorized_response, parameter[self, args]]:
constant[Handles authorization response smartly.]
if compare[name[args] is constant[None]] begin[:]
variable[args] assign[=] name[request].args
if compare[constant[oauth_verifier] in name[args]] begin[:]
va... | keyword[def] identifier[authorized_response] ( identifier[self] , identifier[args] = keyword[None] ):
literal[string]
keyword[if] identifier[args] keyword[is] keyword[None] :
identifier[args] = identifier[request] . identifier[args]
keyword[if] literal[string] keyword[in... | def authorized_response(self, args=None):
"""Handles authorization response smartly."""
if args is None:
args = request.args # depends on [control=['if'], data=['args']]
if 'oauth_verifier' in args:
data = self.handle_oauth1_response(args) # depends on [control=['if'], data=['args']]
e... |
def roots_of_cubic_polynom(a1, a2, a3):
'''
Finds the roots of a 3 dim polymon of the form x^3 + a1 * x^2 + a2 * x + a3.
The roots are returned as complex numbers.
'''
q = (a1 * a1 - 3.0 * a2) / 9.0
r = (2 * a1 * a1 * a1 - 9.0 * a1 * a2 + 27.0 * a3) / 54.0
r2 = r * r
q3 = q * q * q
a... | def function[roots_of_cubic_polynom, parameter[a1, a2, a3]]:
constant[
Finds the roots of a 3 dim polymon of the form x^3 + a1 * x^2 + a2 * x + a3.
The roots are returned as complex numbers.
]
variable[q] assign[=] binary_operation[binary_operation[binary_operation[name[a1] * name[a1]] - bin... | keyword[def] identifier[roots_of_cubic_polynom] ( identifier[a1] , identifier[a2] , identifier[a3] ):
literal[string]
identifier[q] =( identifier[a1] * identifier[a1] - literal[int] * identifier[a2] )/ literal[int]
identifier[r] =( literal[int] * identifier[a1] * identifier[a1] * identifier[a1] - lit... | def roots_of_cubic_polynom(a1, a2, a3):
"""
Finds the roots of a 3 dim polymon of the form x^3 + a1 * x^2 + a2 * x + a3.
The roots are returned as complex numbers.
"""
q = (a1 * a1 - 3.0 * a2) / 9.0
r = (2 * a1 * a1 * a1 - 9.0 * a1 * a2 + 27.0 * a3) / 54.0
r2 = r * r
q3 = q * q * q
a... |
def _rename_file(self, line=""):
"""Rename an ontology
2016-04-11: not a direct command anymore """
if not self.all_ontologies:
self._help_nofiles()
else:
out = []
for each in self.all_ontologies:
if line in each:
... | def function[_rename_file, parameter[self, line]]:
constant[Rename an ontology
2016-04-11: not a direct command anymore ]
if <ast.UnaryOp object at 0x7da1b119fca0> begin[:]
call[name[self]._help_nofiles, parameter[]]
return[None] | keyword[def] identifier[_rename_file] ( identifier[self] , identifier[line] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[all_ontologies] :
identifier[self] . identifier[_help_nofiles] ()
keyword[else] :
identifier[... | def _rename_file(self, line=''):
"""Rename an ontology
2016-04-11: not a direct command anymore """
if not self.all_ontologies:
self._help_nofiles() # depends on [control=['if'], data=[]]
else:
out = []
for each in self.all_ontologies:
if line in each:
... |
def qax(mt, x, q, m=1):
""" geometrica """
q = float(q)
j = (mt.i - q) / (1 + q)
mtj = Actuarial(nt=mt.nt, i=j)
return ax(mtj, x, m) | def function[qax, parameter[mt, x, q, m]]:
constant[ geometrica ]
variable[q] assign[=] call[name[float], parameter[name[q]]]
variable[j] assign[=] binary_operation[binary_operation[name[mt].i - name[q]] / binary_operation[constant[1] + name[q]]]
variable[mtj] assign[=] call[name[Actuari... | keyword[def] identifier[qax] ( identifier[mt] , identifier[x] , identifier[q] , identifier[m] = literal[int] ):
literal[string]
identifier[q] = identifier[float] ( identifier[q] )
identifier[j] =( identifier[mt] . identifier[i] - identifier[q] )/( literal[int] + identifier[q] )
identifier[mtj] = ... | def qax(mt, x, q, m=1):
""" geometrica """
q = float(q)
j = (mt.i - q) / (1 + q)
mtj = Actuarial(nt=mt.nt, i=j)
return ax(mtj, x, m) |
def to_string(self, format_, fps=None, **kwargs):
"""
Get subtitle file as a string.
See :meth:`SSAFile.save()` for full description.
Returns:
str
"""
fp = io.StringIO()
self.to_file(fp, format_, fps=fps, **kwargs)
return fp.getvalue() | def function[to_string, parameter[self, format_, fps]]:
constant[
Get subtitle file as a string.
See :meth:`SSAFile.save()` for full description.
Returns:
str
]
variable[fp] assign[=] call[name[io].StringIO, parameter[]]
call[name[self].to_file, par... | keyword[def] identifier[to_string] ( identifier[self] , identifier[format_] , identifier[fps] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[fp] = identifier[io] . identifier[StringIO] ()
identifier[self] . identifier[to_file] ( identifier[fp] , identifier[format_] , ... | def to_string(self, format_, fps=None, **kwargs):
"""
Get subtitle file as a string.
See :meth:`SSAFile.save()` for full description.
Returns:
str
"""
fp = io.StringIO()
self.to_file(fp, format_, fps=fps, **kwargs)
return fp.getvalue() |
def simDeath(self):
'''
Trivial function that returns boolean array of all False, as there is no death.
Parameters
----------
None
Returns
-------
which_agents : np.array(bool)
Boolean array of size AgentCount indicating which agents die.
... | def function[simDeath, parameter[self]]:
constant[
Trivial function that returns boolean array of all False, as there is no death.
Parameters
----------
None
Returns
-------
which_agents : np.array(bool)
Boolean array of size AgentCount indic... | keyword[def] identifier[simDeath] ( identifier[self] ):
literal[string]
identifier[which_agents] = identifier[np] . identifier[zeros] ( identifier[self] . identifier[AgentCount] , identifier[dtype] = identifier[bool] )
keyword[return] identifier[which_agents] | def simDeath(self):
"""
Trivial function that returns boolean array of all False, as there is no death.
Parameters
----------
None
Returns
-------
which_agents : np.array(bool)
Boolean array of size AgentCount indicating which agents die.
... |
def prev_content(self, start, amount=1):
"""Returns the prev non-whitespace characters"""
while start > 0 and self.code[start] in (' ', '\t', '\n'):
start -= 1
return self.code[(start or amount) - amount: start] | def function[prev_content, parameter[self, start, amount]]:
constant[Returns the prev non-whitespace characters]
while <ast.BoolOp object at 0x7da207f005e0> begin[:]
<ast.AugAssign object at 0x7da207f03250>
return[call[name[self].code][<ast.Slice object at 0x7da207f01e40>]] | keyword[def] identifier[prev_content] ( identifier[self] , identifier[start] , identifier[amount] = literal[int] ):
literal[string]
keyword[while] identifier[start] > literal[int] keyword[and] identifier[self] . identifier[code] [ identifier[start] ] keyword[in] ( literal[string] , literal[strin... | def prev_content(self, start, amount=1):
"""Returns the prev non-whitespace characters"""
while start > 0 and self.code[start] in (' ', '\t', '\n'):
start -= 1 # depends on [control=['while'], data=[]]
return self.code[(start or amount) - amount:start] |
def find_closest(db, pos):
"""Find the closest point in db to pos.
:returns: Closest dataset as well as the distance in meters.
"""
def get_dist(d1, d2):
"""Get distance between d1 and d2 in meters."""
lat1, lon1 = d1['latitude'], d1['longitude']
lat2, lon2 = d2['latitude'], d2['... | def function[find_closest, parameter[db, pos]]:
constant[Find the closest point in db to pos.
:returns: Closest dataset as well as the distance in meters.
]
def function[get_dist, parameter[d1, d2]]:
constant[Get distance between d1 and d2 in meters.]
<ast.Tuple o... | keyword[def] identifier[find_closest] ( identifier[db] , identifier[pos] ):
literal[string]
keyword[def] identifier[get_dist] ( identifier[d1] , identifier[d2] ):
literal[string]
identifier[lat1] , identifier[lon1] = identifier[d1] [ literal[string] ], identifier[d1] [ literal[string] ]... | def find_closest(db, pos):
"""Find the closest point in db to pos.
:returns: Closest dataset as well as the distance in meters.
"""
def get_dist(d1, d2):
"""Get distance between d1 and d2 in meters."""
(lat1, lon1) = (d1['latitude'], d1['longitude'])
(lat2, lon2) = (d2['latitude... |
def _insert_entity(entity, encryption_required=False,
key_encryption_key=None, encryption_resolver=None):
'''
Constructs an insert entity request.
:param entity:
The entity to insert. Could be a dict or an entity object.
:param object key_encryption_key:
The user-provi... | def function[_insert_entity, parameter[entity, encryption_required, key_encryption_key, encryption_resolver]]:
constant[
Constructs an insert entity request.
:param entity:
The entity to insert. Could be a dict or an entity object.
:param object key_encryption_key:
The user-provided ... | keyword[def] identifier[_insert_entity] ( identifier[entity] , identifier[encryption_required] = keyword[False] ,
identifier[key_encryption_key] = keyword[None] , identifier[encryption_resolver] = keyword[None] ):
literal[string]
identifier[_validate_entity] ( identifier[entity] , identifier[key_encryptio... | def _insert_entity(entity, encryption_required=False, key_encryption_key=None, encryption_resolver=None):
"""
Constructs an insert entity request.
:param entity:
The entity to insert. Could be a dict or an entity object.
:param object key_encryption_key:
The user-provided key-encryption-... |
def dump(obj, fp, **kwargs):
"""Like :func:`dumps` but writes into a file object."""
_dump_arg_defaults(kwargs)
encoding = kwargs.pop('encoding', None)
if encoding is not None:
fp = _wrap_writer_for_text(fp, encoding)
_json.dump(obj, fp, **kwargs) | def function[dump, parameter[obj, fp]]:
constant[Like :func:`dumps` but writes into a file object.]
call[name[_dump_arg_defaults], parameter[name[kwargs]]]
variable[encoding] assign[=] call[name[kwargs].pop, parameter[constant[encoding], constant[None]]]
if compare[name[encoding] is_not ... | keyword[def] identifier[dump] ( identifier[obj] , identifier[fp] ,** identifier[kwargs] ):
literal[string]
identifier[_dump_arg_defaults] ( identifier[kwargs] )
identifier[encoding] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[None] )
keyword[if] identifier[encoding] keywo... | def dump(obj, fp, **kwargs):
"""Like :func:`dumps` but writes into a file object."""
_dump_arg_defaults(kwargs)
encoding = kwargs.pop('encoding', None)
if encoding is not None:
fp = _wrap_writer_for_text(fp, encoding) # depends on [control=['if'], data=['encoding']]
_json.dump(obj, fp, **kw... |
def evaluate(self, genomes, config):
"""
Evaluates the genomes.
This method raises a ModeError if the
DistributedEvaluator is not in primary mode.
"""
if self.mode != MODE_PRIMARY:
raise ModeError("Not in primary mode!")
tasks = [(genome_id, genome, co... | def function[evaluate, parameter[self, genomes, config]]:
constant[
Evaluates the genomes.
This method raises a ModeError if the
DistributedEvaluator is not in primary mode.
]
if compare[name[self].mode not_equal[!=] name[MODE_PRIMARY]] begin[:]
<ast.Raise object ... | keyword[def] identifier[evaluate] ( identifier[self] , identifier[genomes] , identifier[config] ):
literal[string]
keyword[if] identifier[self] . identifier[mode] != identifier[MODE_PRIMARY] :
keyword[raise] identifier[ModeError] ( literal[string] )
identifier[tasks] =[( ide... | def evaluate(self, genomes, config):
"""
Evaluates the genomes.
This method raises a ModeError if the
DistributedEvaluator is not in primary mode.
"""
if self.mode != MODE_PRIMARY:
raise ModeError('Not in primary mode!') # depends on [control=['if'], data=[]]
tasks =... |
def showEvent(self, event):
"""
Raises this widget when it is shown.
:param event | <QtCore.QShowEvent>
"""
super(XWalkthroughWidget, self).showEvent(event)
self.autoLayout()
self.restart()
self.setFocus()
self.rai... | def function[showEvent, parameter[self, event]]:
constant[
Raises this widget when it is shown.
:param event | <QtCore.QShowEvent>
]
call[call[name[super], parameter[name[XWalkthroughWidget], name[self]]].showEvent, parameter[name[event]]]
call[name[self].au... | keyword[def] identifier[showEvent] ( identifier[self] , identifier[event] ):
literal[string]
identifier[super] ( identifier[XWalkthroughWidget] , identifier[self] ). identifier[showEvent] ( identifier[event] )
identifier[self] . identifier[autoLayout] ()
identifier[self] . i... | def showEvent(self, event):
"""
Raises this widget when it is shown.
:param event | <QtCore.QShowEvent>
"""
super(XWalkthroughWidget, self).showEvent(event)
self.autoLayout()
self.restart()
self.setFocus()
self.raise_() |
def next(self):
"""
Yields the next row from the source files.
"""
for self._filename in self._filenames:
self._open()
for row in self._csv_reader:
self._row_number += 1
if self._fields:
yield dict(zip_longest(se... | def function[next, parameter[self]]:
constant[
Yields the next row from the source files.
]
for taget[name[self]._filename] in starred[name[self]._filenames] begin[:]
call[name[self]._open, parameter[]]
for taget[name[row]] in starred[name[self]._csv_reade... | keyword[def] identifier[next] ( identifier[self] ):
literal[string]
keyword[for] identifier[self] . identifier[_filename] keyword[in] identifier[self] . identifier[_filenames] :
identifier[self] . identifier[_open] ()
keyword[for] identifier[row] keyword[in] identifi... | def next(self):
"""
Yields the next row from the source files.
"""
for self._filename in self._filenames:
self._open()
for row in self._csv_reader:
self._row_number += 1
if self._fields:
yield dict(zip_longest(self._fields, row, fillvalue='... |
def xadd(self, stream, fields, message_id=b'*', max_len=None,
exact_len=False):
"""Add a message to a stream."""
args = []
if max_len is not None:
if exact_len:
args.extend((b'MAXLEN', max_len))
else:
args.extend((b'MAXLEN', b'... | def function[xadd, parameter[self, stream, fields, message_id, max_len, exact_len]]:
constant[Add a message to a stream.]
variable[args] assign[=] list[[]]
if compare[name[max_len] is_not constant[None]] begin[:]
if name[exact_len] begin[:]
call[name[args]... | keyword[def] identifier[xadd] ( identifier[self] , identifier[stream] , identifier[fields] , identifier[message_id] = literal[string] , identifier[max_len] = keyword[None] ,
identifier[exact_len] = keyword[False] ):
literal[string]
identifier[args] =[]
keyword[if] identifier[max_len] ke... | def xadd(self, stream, fields, message_id=b'*', max_len=None, exact_len=False):
"""Add a message to a stream."""
args = []
if max_len is not None:
if exact_len:
args.extend((b'MAXLEN', max_len)) # depends on [control=['if'], data=[]]
else:
args.extend((b'MAXLEN', b'~... |
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
... | def function[mod_repo, parameter[repo]]:
constant[
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for ... | keyword[def] identifier[mod_repo] ( identifier[repo] ,** identifier[kwargs] ):
literal[string]
identifier[root] = identifier[kwargs] . identifier[get] ( literal[string] ) keyword[or] keyword[None]
identifier[repos_cfg] = identifier[_get_configured_repos] ( identifier[root] = identifier[root] )
... | def mod_repo(repo, **kwargs):
"""
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
... |
def buildPrices(data, roles=None, regex=default_price_regex,
default=None, additional={}):
''' Create a dictionary with price information. Multiple ways are
supported.
:rtype: :obj:`dict`: keys are role as str, values are the prices as
cent count'''
if isinstance(da... | def function[buildPrices, parameter[data, roles, regex, default, additional]]:
constant[ Create a dictionary with price information. Multiple ways are
supported.
:rtype: :obj:`dict`: keys are role as str, values are the prices as
cent count]
if call[name[isinstance], parame... | keyword[def] identifier[buildPrices] ( identifier[data] , identifier[roles] = keyword[None] , identifier[regex] = identifier[default_price_regex] ,
identifier[default] = keyword[None] , identifier[additional] ={}):
literal[string]
keyword[if] identifier[isinstance] ( identifier[data] , identifier[dict] )... | def buildPrices(data, roles=None, regex=default_price_regex, default=None, additional={}):
""" Create a dictionary with price information. Multiple ways are
supported.
:rtype: :obj:`dict`: keys are role as str, values are the prices as
cent count"""
if isinstance(data, dict):
... |
def _select_by_field_or_tag(self, tag=None, field=None):
"""For internal use only. Returns an OrderedDict of {identifier: field}
representing fields which match the supplied field/tag.
Parameters
----------
tag : str
Optionally specifies that the mask should only inc... | def function[_select_by_field_or_tag, parameter[self, tag, field]]:
constant[For internal use only. Returns an OrderedDict of {identifier: field}
representing fields which match the supplied field/tag.
Parameters
----------
tag : str
Optionally specifies that the mas... | keyword[def] identifier[_select_by_field_or_tag] ( identifier[self] , identifier[tag] = keyword[None] , identifier[field] = keyword[None] ):
literal[string]
keyword[if] identifier[field] keyword[is] keyword[not] keyword[None] :
identifier[field_obj] = identifier[s... | def _select_by_field_or_tag(self, tag=None, field=None):
"""For internal use only. Returns an OrderedDict of {identifier: field}
representing fields which match the supplied field/tag.
Parameters
----------
tag : str
Optionally specifies that the mask should only include... |
def _handle_chat(self, data):
"""Handle chat messages"""
self.conn.enqueue_data(
"chat", ChatMessage.from_data(self.room, self.conn, data)
) | def function[_handle_chat, parameter[self, data]]:
constant[Handle chat messages]
call[name[self].conn.enqueue_data, parameter[constant[chat], call[name[ChatMessage].from_data, parameter[name[self].room, name[self].conn, name[data]]]]] | keyword[def] identifier[_handle_chat] ( identifier[self] , identifier[data] ):
literal[string]
identifier[self] . identifier[conn] . identifier[enqueue_data] (
literal[string] , identifier[ChatMessage] . identifier[from_data] ( identifier[self] . identifier[room] , identifier[self] . iden... | def _handle_chat(self, data):
"""Handle chat messages"""
self.conn.enqueue_data('chat', ChatMessage.from_data(self.room, self.conn, data)) |
def _process_windows_merge_stack(self, func, **kwargs):
"""Load (resampled) array of all windows, apply custom function on it, merge and stack results to one array."""
ji_results = self._process_windows(func, **kwargs)
for idx_layer in range(len(ji_results[0])): # this is the number of output l... | def function[_process_windows_merge_stack, parameter[self, func]]:
constant[Load (resampled) array of all windows, apply custom function on it, merge and stack results to one array.]
variable[ji_results] assign[=] call[name[self]._process_windows, parameter[name[func]]]
for taget[name[idx_layer]... | keyword[def] identifier[_process_windows_merge_stack] ( identifier[self] , identifier[func] ,** identifier[kwargs] ):
literal[string]
identifier[ji_results] = identifier[self] . identifier[_process_windows] ( identifier[func] ,** identifier[kwargs] )
keyword[for] identifier[idx_layer] ke... | def _process_windows_merge_stack(self, func, **kwargs):
"""Load (resampled) array of all windows, apply custom function on it, merge and stack results to one array."""
ji_results = self._process_windows(func, **kwargs)
for idx_layer in range(len(ji_results[0])): # this is the number of output layers
... |
def list_joysticks():
'''Print a list of available joysticks'''
print('Available joysticks:')
print()
for jid in range(pygame.joystick.get_count()):
j = pygame.joystick.Joystick(jid)
print('({}) {}'.format(jid, j.get_name())) | def function[list_joysticks, parameter[]]:
constant[Print a list of available joysticks]
call[name[print], parameter[constant[Available joysticks:]]]
call[name[print], parameter[]]
for taget[name[jid]] in starred[call[name[range], parameter[call[name[pygame].joystick.get_count, parameter... | keyword[def] identifier[list_joysticks] ():
literal[string]
identifier[print] ( literal[string] )
identifier[print] ()
keyword[for] identifier[jid] keyword[in] identifier[range] ( identifier[pygame] . identifier[joystick] . identifier[get_count] ()):
identifier[j] = identifier[pygame... | def list_joysticks():
"""Print a list of available joysticks"""
print('Available joysticks:')
print()
for jid in range(pygame.joystick.get_count()):
j = pygame.joystick.Joystick(jid)
print('({}) {}'.format(jid, j.get_name())) # depends on [control=['for'], data=['jid']] |
def is_attribute_deprecated(self, attribute):
"""
Check if the attribute is deprecated by the current KMIP version.
Args:
attribute (string): The name of the attribute
(e.g., 'Unique Identifier'). Required.
"""
rule_set = self._attribute_rule_sets.get... | def function[is_attribute_deprecated, parameter[self, attribute]]:
constant[
Check if the attribute is deprecated by the current KMIP version.
Args:
attribute (string): The name of the attribute
(e.g., 'Unique Identifier'). Required.
]
variable[rule_s... | keyword[def] identifier[is_attribute_deprecated] ( identifier[self] , identifier[attribute] ):
literal[string]
identifier[rule_set] = identifier[self] . identifier[_attribute_rule_sets] . identifier[get] ( identifier[attribute] )
keyword[if] identifier[rule_set] . identifier[version_depre... | def is_attribute_deprecated(self, attribute):
"""
Check if the attribute is deprecated by the current KMIP version.
Args:
attribute (string): The name of the attribute
(e.g., 'Unique Identifier'). Required.
"""
rule_set = self._attribute_rule_sets.get(attribu... |
def color_format():
"""
Main entry point to get a colored formatter, it will use the
BASE_FORMAT by default and fall back to no colors if the system
does not support it
"""
str_format = BASE_COLOR_FORMAT if supports_color() else BASE_FORMAT
color_format = color_message(str_format)
return... | def function[color_format, parameter[]]:
constant[
Main entry point to get a colored formatter, it will use the
BASE_FORMAT by default and fall back to no colors if the system
does not support it
]
variable[str_format] assign[=] <ast.IfExp object at 0x7da1b16bdf00>
variable[color... | keyword[def] identifier[color_format] ():
literal[string]
identifier[str_format] = identifier[BASE_COLOR_FORMAT] keyword[if] identifier[supports_color] () keyword[else] identifier[BASE_FORMAT]
identifier[color_format] = identifier[color_message] ( identifier[str_format] )
keyword[return] ide... | def color_format():
"""
Main entry point to get a colored formatter, it will use the
BASE_FORMAT by default and fall back to no colors if the system
does not support it
"""
str_format = BASE_COLOR_FORMAT if supports_color() else BASE_FORMAT
color_format = color_message(str_format)
return... |
def _convert_markup_basic(self, soup):
"""
Perform basic conversion of instructions markup. This includes
replacement of several textual markup tags with their HTML equivalents.
@param soup: BeautifulSoup instance.
@type soup: BeautifulSoup
"""
# Inject meta char... | def function[_convert_markup_basic, parameter[self, soup]]:
constant[
Perform basic conversion of instructions markup. This includes
replacement of several textual markup tags with their HTML equivalents.
@param soup: BeautifulSoup instance.
@type soup: BeautifulSoup
]
... | keyword[def] identifier[_convert_markup_basic] ( identifier[self] , identifier[soup] ):
literal[string]
identifier[meta] = identifier[soup] . identifier[new_tag] ( literal[string] , identifier[charset] = literal[string] )
identifier[soup] . identifier[insert] ( literal[int] , iden... | def _convert_markup_basic(self, soup):
"""
Perform basic conversion of instructions markup. This includes
replacement of several textual markup tags with their HTML equivalents.
@param soup: BeautifulSoup instance.
@type soup: BeautifulSoup
"""
# Inject meta charset tag
... |
def _read_df(f,nrows,names,converters,defaults=None):
""" a private method to read part of an open file into a pandas.DataFrame.
Parameters
----------
f : file object
nrows : int
number of rows to read
names : list
names to set the columns of the ... | def function[_read_df, parameter[f, nrows, names, converters, defaults]]:
constant[ a private method to read part of an open file into a pandas.DataFrame.
Parameters
----------
f : file object
nrows : int
number of rows to read
names : list
names ... | keyword[def] identifier[_read_df] ( identifier[f] , identifier[nrows] , identifier[names] , identifier[converters] , identifier[defaults] = keyword[None] ):
literal[string]
identifier[seek_point] = identifier[f] . identifier[tell] ()
identifier[line] = identifier[f] . identifier[readline] ... | def _read_df(f, nrows, names, converters, defaults=None):
""" a private method to read part of an open file into a pandas.DataFrame.
Parameters
----------
f : file object
nrows : int
number of rows to read
names : list
names to set the columns of the ... |
def _update(self, commit=False):
"""Forces an update of this rating (useful for when Vote objects are removed)."""
votes = Vote.objects.filter(
content_type = self.get_content_type(),
object_id = self.instance.pk,
key = self.field.key,
)
... | def function[_update, parameter[self, commit]]:
constant[Forces an update of this rating (useful for when Vote objects are removed).]
variable[votes] assign[=] call[name[Vote].objects.filter, parameter[]]
variable[obj_score] assign[=] call[name[sum], parameter[<ast.ListComp object at 0x7da20e957... | keyword[def] identifier[_update] ( identifier[self] , identifier[commit] = keyword[False] ):
literal[string]
identifier[votes] = identifier[Vote] . identifier[objects] . identifier[filter] (
identifier[content_type] = identifier[self] . identifier[get_content_type] (),
identifier[... | def _update(self, commit=False):
"""Forces an update of this rating (useful for when Vote objects are removed)."""
votes = Vote.objects.filter(content_type=self.get_content_type(), object_id=self.instance.pk, key=self.field.key)
obj_score = sum([v.score for v in votes])
obj_votes = len(votes)
(score... |
def delete(self):
"""
Delete this NIC.
Authorization requirements:
* Object-access permission to the Partition containing this HBA.
* Task permission to the "Partition Details" task.
Raises:
:exc:`~zhmcclient.HTTPError`
:exc:`~zhmcclient.ParseError... | def function[delete, parameter[self]]:
constant[
Delete this NIC.
Authorization requirements:
* Object-access permission to the Partition containing this HBA.
* Task permission to the "Partition Details" task.
Raises:
:exc:`~zhmcclient.HTTPError`
:... | keyword[def] identifier[delete] ( identifier[self] ):
literal[string]
identifier[self] . identifier[manager] . identifier[session] . identifier[delete] ( identifier[self] . identifier[_uri] )
identifier[self] . identifier[manager] . identifier[_name_uri_cache] . identifier[delete] (
... | def delete(self):
"""
Delete this NIC.
Authorization requirements:
* Object-access permission to the Partition containing this HBA.
* Task permission to the "Partition Details" task.
Raises:
:exc:`~zhmcclient.HTTPError`
:exc:`~zhmcclient.ParseError`
... |
def create_folder_cmd_line(query, default_name=None, default_path=None):
"""Queries the user for a path to be created
:param str query: Query that asks the user for a specific folder path to be created
:param str default_name: Default name of the folder to be created
:param str default_path: Path in w... | def function[create_folder_cmd_line, parameter[query, default_name, default_path]]:
constant[Queries the user for a path to be created
:param str query: Query that asks the user for a specific folder path to be created
:param str default_name: Default name of the folder to be created
:param str de... | keyword[def] identifier[create_folder_cmd_line] ( identifier[query] , identifier[default_name] = keyword[None] , identifier[default_path] = keyword[None] ):
literal[string]
identifier[default] = keyword[None]
keyword[if] identifier[default_name] keyword[and] identifier[default_path] :
ide... | def create_folder_cmd_line(query, default_name=None, default_path=None):
"""Queries the user for a path to be created
:param str query: Query that asks the user for a specific folder path to be created
:param str default_name: Default name of the folder to be created
:param str default_path: Path in w... |
def resolve_role_to_path(role):
"""
Given a role definition from a service's list of roles, returns the file path to the role
"""
loader = DataLoader()
try:
variable_manager = VariableManager(loader=loader)
except TypeError:
# If Ansible prior to ansible/ansible@8f97aef1a365
... | def function[resolve_role_to_path, parameter[role]]:
constant[
Given a role definition from a service's list of roles, returns the file path to the role
]
variable[loader] assign[=] call[name[DataLoader], parameter[]]
<ast.Try object at 0x7da18bc71bd0>
variable[role_obj] assign[=] ca... | keyword[def] identifier[resolve_role_to_path] ( identifier[role] ):
literal[string]
identifier[loader] = identifier[DataLoader] ()
keyword[try] :
identifier[variable_manager] = identifier[VariableManager] ( identifier[loader] = identifier[loader] )
keyword[except] identifier[TypeError] ... | def resolve_role_to_path(role):
"""
Given a role definition from a service's list of roles, returns the file path to the role
"""
loader = DataLoader()
try:
variable_manager = VariableManager(loader=loader) # depends on [control=['try'], data=[]]
except TypeError:
# If Ansible p... |
def for_class(digobj, repo):
'''Generate a ContentModel object for the specified
:class:`DigitalObject` class. Content model object is saved
in the specified repository if it doesn't already exist.'''
full_name = '%s.%s' % (digobj.__module__, digobj.__name__)
cmodels = getattr(d... | def function[for_class, parameter[digobj, repo]]:
constant[Generate a ContentModel object for the specified
:class:`DigitalObject` class. Content model object is saved
in the specified repository if it doesn't already exist.]
variable[full_name] assign[=] binary_operation[constant[%s.%s... | keyword[def] identifier[for_class] ( identifier[digobj] , identifier[repo] ):
literal[string]
identifier[full_name] = literal[string] %( identifier[digobj] . identifier[__module__] , identifier[digobj] . identifier[__name__] )
identifier[cmodels] = identifier[getattr] ( identifier[digobj] ... | def for_class(digobj, repo):
"""Generate a ContentModel object for the specified
:class:`DigitalObject` class. Content model object is saved
in the specified repository if it doesn't already exist."""
full_name = '%s.%s' % (digobj.__module__, digobj.__name__)
cmodels = getattr(digobj, 'CONT... |
def enqueue_request(self, request):
'''
Pushes a request from the spider into the proper throttled queue
'''
if not request.dont_filter and self.dupefilter.request_seen(request):
self.logger.debug("Request not added back to redis")
return
req_dict = self.r... | def function[enqueue_request, parameter[self, request]]:
constant[
Pushes a request from the spider into the proper throttled queue
]
if <ast.BoolOp object at 0x7da1b1983b50> begin[:]
call[name[self].logger.debug, parameter[constant[Request not added back to redis]]]
... | keyword[def] identifier[enqueue_request] ( identifier[self] , identifier[request] ):
literal[string]
keyword[if] keyword[not] identifier[request] . identifier[dont_filter] keyword[and] identifier[self] . identifier[dupefilter] . identifier[request_seen] ( identifier[request] ):
ide... | def enqueue_request(self, request):
"""
Pushes a request from the spider into the proper throttled queue
"""
if not request.dont_filter and self.dupefilter.request_seen(request):
self.logger.debug('Request not added back to redis')
return # depends on [control=['if'], data=[]]
... |
def on_receive_request_vote_response(self, data):
"""Receives response for vote request.
If the vote was granted then check if we got majority and may become Leader
"""
if data.get('vote_granted'):
self.vote_count += 1
if self.state.is_majority(self.vote_count):... | def function[on_receive_request_vote_response, parameter[self, data]]:
constant[Receives response for vote request.
If the vote was granted then check if we got majority and may become Leader
]
if call[name[data].get, parameter[constant[vote_granted]]] begin[:]
<ast.AugAssign obj... | keyword[def] identifier[on_receive_request_vote_response] ( identifier[self] , identifier[data] ):
literal[string]
keyword[if] identifier[data] . identifier[get] ( literal[string] ):
identifier[self] . identifier[vote_count] += literal[int]
keyword[if] identifier[self... | def on_receive_request_vote_response(self, data):
"""Receives response for vote request.
If the vote was granted then check if we got majority and may become Leader
"""
if data.get('vote_granted'):
self.vote_count += 1
if self.state.is_majority(self.vote_count):
self.... |
def make_config_get(conf_path):
"""Return a function to get configuration options for a specific project
Args:
conf_path (path-like): path to project's conf file (i.e. foo.conf
module)
"""
project_root = _get_project_root_from_conf_path(conf_path)
config = load_config_in_dir(pro... | def function[make_config_get, parameter[conf_path]]:
constant[Return a function to get configuration options for a specific project
Args:
conf_path (path-like): path to project's conf file (i.e. foo.conf
module)
]
variable[project_root] assign[=] call[name[_get_project_root_... | keyword[def] identifier[make_config_get] ( identifier[conf_path] ):
literal[string]
identifier[project_root] = identifier[_get_project_root_from_conf_path] ( identifier[conf_path] )
identifier[config] = identifier[load_config_in_dir] ( identifier[project_root] )
keyword[return] identifier[partia... | def make_config_get(conf_path):
"""Return a function to get configuration options for a specific project
Args:
conf_path (path-like): path to project's conf file (i.e. foo.conf
module)
"""
project_root = _get_project_root_from_conf_path(conf_path)
config = load_config_in_dir(pro... |
def is_population_germline(rec):
"""Identify a germline calls based on annoations with ExAC or other population databases.
"""
min_count = 50
for k in population_keys:
if k in rec.info:
val = rec.info.get(k)
if "," in val:
val = val.split(",")[0]
... | def function[is_population_germline, parameter[rec]]:
constant[Identify a germline calls based on annoations with ExAC or other population databases.
]
variable[min_count] assign[=] constant[50]
for taget[name[k]] in starred[name[population_keys]] begin[:]
if compare[name[k] ... | keyword[def] identifier[is_population_germline] ( identifier[rec] ):
literal[string]
identifier[min_count] = literal[int]
keyword[for] identifier[k] keyword[in] identifier[population_keys] :
keyword[if] identifier[k] keyword[in] identifier[rec] . identifier[info] :
identif... | def is_population_germline(rec):
"""Identify a germline calls based on annoations with ExAC or other population databases.
"""
min_count = 50
for k in population_keys:
if k in rec.info:
val = rec.info.get(k)
if ',' in val:
val = val.split(',')[0] # depend... |
def generate_ssh_key(self):
"""
Generate a new ssh private and public key
"""
web_command(
command=["ssh-keygen", "-q", "-t", "rsa", "-N", "", "-C",
"datacats generated {0}@{1}".format(
getuser(), gethostname()),
... | def function[generate_ssh_key, parameter[self]]:
constant[
Generate a new ssh private and public key
]
call[name[web_command], parameter[]] | keyword[def] identifier[generate_ssh_key] ( identifier[self] ):
literal[string]
identifier[web_command] (
identifier[command] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ,
literal[string] . identifi... | def generate_ssh_key(self):
"""
Generate a new ssh private and public key
"""
web_command(command=['ssh-keygen', '-q', '-t', 'rsa', '-N', '', '-C', 'datacats generated {0}@{1}'.format(getuser(), gethostname()), '-f', '/output/id_rsa'], rw={self.profiledir: '/output'}) |
def dquadmon_from_lambda(lambdav):
r"""Return the quadrupole moment of a neutron star given its lambda
We use the relations defined here. https://arxiv.org/pdf/1302.4499.pdf.
Note that the convention we use is that:
.. math::
\mathrm{dquadmon} = \bar{Q} - 1.
Where :math:`\bar{Q}` (dimens... | def function[dquadmon_from_lambda, parameter[lambdav]]:
constant[Return the quadrupole moment of a neutron star given its lambda
We use the relations defined here. https://arxiv.org/pdf/1302.4499.pdf.
Note that the convention we use is that:
.. math::
\mathrm{dquadmon} = \bar{Q} - 1.
... | keyword[def] identifier[dquadmon_from_lambda] ( identifier[lambdav] ):
literal[string]
identifier[ll] = identifier[numpy] . identifier[log] ( identifier[lambdav] )
identifier[ai] = literal[int]
identifier[bi] = literal[int]
identifier[ci] = literal[int]
identifier[di] =- literal[int]... | def dquadmon_from_lambda(lambdav):
"""Return the quadrupole moment of a neutron star given its lambda
We use the relations defined here. https://arxiv.org/pdf/1302.4499.pdf.
Note that the convention we use is that:
.. math::
\\mathrm{dquadmon} = \\bar{Q} - 1.
Where :math:`\\bar{Q}` (dime... |
def delete_jail(name):
'''
Deletes poudriere jail with `name`
CLI Example:
.. code-block:: bash
salt '*' poudriere.delete_jail 90amd64
'''
if is_jail(name):
cmd = 'poudriere jail -d -j {0}'.format(name)
__salt__['cmd.run'](cmd)
# Make sure jail is gone
... | def function[delete_jail, parameter[name]]:
constant[
Deletes poudriere jail with `name`
CLI Example:
.. code-block:: bash
salt '*' poudriere.delete_jail 90amd64
]
if call[name[is_jail], parameter[name[name]]] begin[:]
variable[cmd] assign[=] call[constant[poud... | keyword[def] identifier[delete_jail] ( identifier[name] ):
literal[string]
keyword[if] identifier[is_jail] ( identifier[name] ):
identifier[cmd] = literal[string] . identifier[format] ( identifier[name] )
identifier[__salt__] [ literal[string] ]( identifier[cmd] )
keyw... | def delete_jail(name):
"""
Deletes poudriere jail with `name`
CLI Example:
.. code-block:: bash
salt '*' poudriere.delete_jail 90amd64
"""
if is_jail(name):
cmd = 'poudriere jail -d -j {0}'.format(name)
__salt__['cmd.run'](cmd)
# Make sure jail is gone
... |
def _getStickersTemplatesDirectory(self, resource_name):
"""Returns the paths for the directory containing the css and pt files
for the stickers deppending on the filter_by_type.
:param resource_name: The name of the resource folder.
:type resource_name: string
:returns: a strin... | def function[_getStickersTemplatesDirectory, parameter[self, resource_name]]:
constant[Returns the paths for the directory containing the css and pt files
for the stickers deppending on the filter_by_type.
:param resource_name: The name of the resource folder.
:type resource_name: strin... | keyword[def] identifier[_getStickersTemplatesDirectory] ( identifier[self] , identifier[resource_name] ):
literal[string]
identifier[templates_dir] = identifier[queryResourceDirectory] ( literal[string] , identifier[resource_name] ). identifier[directory]
keyword[if] identifier[self] . i... | def _getStickersTemplatesDirectory(self, resource_name):
"""Returns the paths for the directory containing the css and pt files
for the stickers deppending on the filter_by_type.
:param resource_name: The name of the resource folder.
:type resource_name: string
:returns: a string as... |
def add_view(self, request, form_url='', extra_context=None):
"""The 'add' admin view for this model."""
model = self.model
opts = model._meta
if not self.has_add_permission(request):
raise PermissionDenied
ModelForm = self.get_form(request)
formsets = []
... | def function[add_view, parameter[self, request, form_url, extra_context]]:
constant[The 'add' admin view for this model.]
variable[model] assign[=] name[self].model
variable[opts] assign[=] name[model]._meta
if <ast.UnaryOp object at 0x7da1b06866e0> begin[:]
<ast.Raise object at ... | keyword[def] identifier[add_view] ( identifier[self] , identifier[request] , identifier[form_url] = literal[string] , identifier[extra_context] = keyword[None] ):
literal[string]
identifier[model] = identifier[self] . identifier[model]
identifier[opts] = identifier[model] . identifier[_me... | def add_view(self, request, form_url='', extra_context=None):
"""The 'add' admin view for this model."""
model = self.model
opts = model._meta
if not self.has_add_permission(request):
raise PermissionDenied # depends on [control=['if'], data=[]]
ModelForm = self.get_form(request)
formse... |
def hash_file(self, path, saltenv='base'):
'''
Return the hash of a file, to get the hash of a file in the pillar_roots
prepend the path with salt://<file on server> otherwise, prepend the
file with / for a local file.
'''
ret = {}
fnd = self.__get_file_path(path,... | def function[hash_file, parameter[self, path, saltenv]]:
constant[
Return the hash of a file, to get the hash of a file in the pillar_roots
prepend the path with salt://<file on server> otherwise, prepend the
file with / for a local file.
]
variable[ret] assign[=] diction... | keyword[def] identifier[hash_file] ( identifier[self] , identifier[path] , identifier[saltenv] = literal[string] ):
literal[string]
identifier[ret] ={}
identifier[fnd] = identifier[self] . identifier[__get_file_path] ( identifier[path] , identifier[saltenv] )
keyword[if] identifi... | def hash_file(self, path, saltenv='base'):
"""
Return the hash of a file, to get the hash of a file in the pillar_roots
prepend the path with salt://<file on server> otherwise, prepend the
file with / for a local file.
"""
ret = {}
fnd = self.__get_file_path(path, saltenv)
... |
def lastId(self) -> BaseReference:
""" Last child's id of current TextualNode
"""
if self.childIds is not None:
if len(self.childIds) > 0:
return self.childIds[-1]
return None
else:
raise NotImplementedError | def function[lastId, parameter[self]]:
constant[ Last child's id of current TextualNode
]
if compare[name[self].childIds is_not constant[None]] begin[:]
if compare[call[name[len], parameter[name[self].childIds]] greater[>] constant[0]] begin[:]
return[call[name[self].... | keyword[def] identifier[lastId] ( identifier[self] )-> identifier[BaseReference] :
literal[string]
keyword[if] identifier[self] . identifier[childIds] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[len] ( identifier[self] . identifier[childIds] )> literal[int] :
... | def lastId(self) -> BaseReference:
""" Last child's id of current TextualNode
"""
if self.childIds is not None:
if len(self.childIds) > 0:
return self.childIds[-1] # depends on [control=['if'], data=[]]
return None # depends on [control=['if'], data=[]]
else:
ra... |
def bind_search(self, username, password):
"""
Bind to BIND_DN/BIND_AUTH then search for user to perform lookup.
"""
log.debug("Performing bind/search")
ctx = {'username':username, 'password':password}
user = self.config['BIND_DN'] % ctx
bind_auth = self.confi... | def function[bind_search, parameter[self, username, password]]:
constant[
Bind to BIND_DN/BIND_AUTH then search for user to perform lookup.
]
call[name[log].debug, parameter[constant[Performing bind/search]]]
variable[ctx] assign[=] dictionary[[<ast.Constant object at 0x7da1b0445... | keyword[def] identifier[bind_search] ( identifier[self] , identifier[username] , identifier[password] ):
literal[string]
identifier[log] . identifier[debug] ( literal[string] )
identifier[ctx] ={ literal[string] : identifier[username] , literal[string] : identifier[password] }
... | def bind_search(self, username, password):
"""
Bind to BIND_DN/BIND_AUTH then search for user to perform lookup.
"""
log.debug('Performing bind/search')
ctx = {'username': username, 'password': password}
user = self.config['BIND_DN'] % ctx
bind_auth = self.config['BIND_AUTH']
try... |
def __get_values(self):
"""
Gets values in this cell range as a tuple.
This is much more effective than reading cell values one by one.
"""
array = self._get_target().getDataArray()
return tuple(itertools.chain.from_iterable(array)) | def function[__get_values, parameter[self]]:
constant[
Gets values in this cell range as a tuple.
This is much more effective than reading cell values one by one.
]
variable[array] assign[=] call[call[name[self]._get_target, parameter[]].getDataArray, parameter[]]
return[cal... | keyword[def] identifier[__get_values] ( identifier[self] ):
literal[string]
identifier[array] = identifier[self] . identifier[_get_target] (). identifier[getDataArray] ()
keyword[return] identifier[tuple] ( identifier[itertools] . identifier[chain] . identifier[from_iterable] ( identifier... | def __get_values(self):
"""
Gets values in this cell range as a tuple.
This is much more effective than reading cell values one by one.
"""
array = self._get_target().getDataArray()
return tuple(itertools.chain.from_iterable(array)) |
async def enable_analog_reporting(self, command):
"""
Enable Firmata reporting for an analog pin.
:param command: {"method": "enable_analog_reporting", "params": [PIN]}
:returns: {"method": "analog_message_reply", "params": [PIN, ANALOG_DATA_VALUE]}
"""
pin = int(command... | <ast.AsyncFunctionDef object at 0x7da18eb56890> | keyword[async] keyword[def] identifier[enable_analog_reporting] ( identifier[self] , identifier[command] ):
literal[string]
identifier[pin] = identifier[int] ( identifier[command] [ literal[int] ])
keyword[await] identifier[self] . identifier[core] . identifier[enable_analog_reporting] (... | async def enable_analog_reporting(self, command):
"""
Enable Firmata reporting for an analog pin.
:param command: {"method": "enable_analog_reporting", "params": [PIN]}
:returns: {"method": "analog_message_reply", "params": [PIN, ANALOG_DATA_VALUE]}
"""
pin = int(command[0])
... |
def canWrite(variable):
"""
mention if an element can be written.
:param variable: the element to evaluate.
:type variable: Lifepo4weredEnum
:return: true when write access is available, otherwise false
:rtype: bool
:raises ValueError: if parameter value is not a member of Lifepo4weredEnum
... | def function[canWrite, parameter[variable]]:
constant[
mention if an element can be written.
:param variable: the element to evaluate.
:type variable: Lifepo4weredEnum
:return: true when write access is available, otherwise false
:rtype: bool
:raises ValueError: if parameter value is no... | keyword[def] identifier[canWrite] ( identifier[variable] ):
literal[string]
keyword[if] identifier[variable] keyword[not] keyword[in] identifier[variablesEnum] :
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[return] identifier[lifepo4weredSO] . identifier[access_lif... | def canWrite(variable):
"""
mention if an element can be written.
:param variable: the element to evaluate.
:type variable: Lifepo4weredEnum
:return: true when write access is available, otherwise false
:rtype: bool
:raises ValueError: if parameter value is not a member of Lifepo4weredEnum
... |
def comparable(self):
"""str: comparable representation of the path specification."""
sub_comparable_string = 'location: {0:s}'.format(self.location)
return self._GetComparable(sub_comparable_string=sub_comparable_string) | def function[comparable, parameter[self]]:
constant[str: comparable representation of the path specification.]
variable[sub_comparable_string] assign[=] call[constant[location: {0:s}].format, parameter[name[self].location]]
return[call[name[self]._GetComparable, parameter[]]] | keyword[def] identifier[comparable] ( identifier[self] ):
literal[string]
identifier[sub_comparable_string] = literal[string] . identifier[format] ( identifier[self] . identifier[location] )
keyword[return] identifier[self] . identifier[_GetComparable] ( identifier[sub_comparable_string] = identifier... | def comparable(self):
"""str: comparable representation of the path specification."""
sub_comparable_string = 'location: {0:s}'.format(self.location)
return self._GetComparable(sub_comparable_string=sub_comparable_string) |
def _set_mcast(self, v, load=False):
"""
Setter method for mcast, mapped from YANG variable /fabric/route/mcast (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mcast is considered as a private
method. Backends looking to populate this variable should
... | def function[_set_mcast, parameter[self, v, load]]:
constant[
Setter method for mcast, mapped from YANG variable /fabric/route/mcast (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mcast is considered as a private
method. Backends looking to populate ... | keyword[def] identifier[_set_mcast] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
identifi... | def _set_mcast(self, v, load=False):
"""
Setter method for mcast, mapped from YANG variable /fabric/route/mcast (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mcast is considered as a private
method. Backends looking to populate this variable should
... |
def parse_config():
"""Parse the configuration and create required services.
Note:
Either takes the configuration from the environment (a variable
named ``FLASH_CONFIG``) or a file at the module root (named
``config.json``). Either way, it will attempt to parse it as
JSON, expecting the... | def function[parse_config, parameter[]]:
constant[Parse the configuration and create required services.
Note:
Either takes the configuration from the environment (a variable
named ``FLASH_CONFIG``) or a file at the module root (named
``config.json``). Either way, it will attempt to parse ... | keyword[def] identifier[parse_config] ():
literal[string]
identifier[env] = identifier[getenv] ( literal[string] )
keyword[if] identifier[env] :
identifier[logger] . identifier[info] ( literal[string] )
identifier[data] = identifier[json] . identifier[loads] ( identifier[env] )
... | def parse_config():
"""Parse the configuration and create required services.
Note:
Either takes the configuration from the environment (a variable
named ``FLASH_CONFIG``) or a file at the module root (named
``config.json``). Either way, it will attempt to parse it as
JSON, expecting the... |
def patch_refresh_from_db(model):
"""
Django >= 1.10: patch refreshing deferred fields. Crucial for only/defer to work.
"""
if not hasattr(model, 'refresh_from_db'):
return
old_refresh_from_db = model.refresh_from_db
def new_refresh_from_db(self, using=None, fields=None):
if fie... | def function[patch_refresh_from_db, parameter[model]]:
constant[
Django >= 1.10: patch refreshing deferred fields. Crucial for only/defer to work.
]
if <ast.UnaryOp object at 0x7da18bc72f50> begin[:]
return[None]
variable[old_refresh_from_db] assign[=] name[model].refresh_from_db... | keyword[def] identifier[patch_refresh_from_db] ( identifier[model] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[model] , literal[string] ):
keyword[return]
identifier[old_refresh_from_db] = identifier[model] . identifier[refresh_from_db]
keyword[def] ... | def patch_refresh_from_db(model):
"""
Django >= 1.10: patch refreshing deferred fields. Crucial for only/defer to work.
"""
if not hasattr(model, 'refresh_from_db'):
return # depends on [control=['if'], data=[]]
old_refresh_from_db = model.refresh_from_db
def new_refresh_from_db(self, ... |
def get_data_home(data_home=None):
"""
Return the path of the revrand data dir.
This folder is used by some large dataset loaders to avoid
downloading the data several times.
By default the data dir is set to a folder named 'revrand_data'
in the user home folder.
Alternatively, it can be ... | def function[get_data_home, parameter[data_home]]:
constant[
Return the path of the revrand data dir.
This folder is used by some large dataset loaders to avoid
downloading the data several times.
By default the data dir is set to a folder named 'revrand_data'
in the user home folder.
... | keyword[def] identifier[get_data_home] ( identifier[data_home] = keyword[None] ):
literal[string]
identifier[data_home_default] = identifier[Path] ( identifier[__file__] ). identifier[ancestor] ( literal[int] ). identifier[child] ( literal[string] ,
literal[string] )
keyword[if] identifier[data... | def get_data_home(data_home=None):
"""
Return the path of the revrand data dir.
This folder is used by some large dataset loaders to avoid
downloading the data several times.
By default the data dir is set to a folder named 'revrand_data'
in the user home folder.
Alternatively, it can be ... |
def pub(topic_name, json_msg, repeat_rate=None, host=jps.env.get_master_host(), pub_port=jps.DEFAULT_PUB_PORT):
'''publishes the data to the topic
:param topic_name: name of the topic
:param json_msg: data to be published
:param repeat_rate: if None, publishes once. if not None, it is used as [Hz].
... | def function[pub, parameter[topic_name, json_msg, repeat_rate, host, pub_port]]:
constant[publishes the data to the topic
:param topic_name: name of the topic
:param json_msg: data to be published
:param repeat_rate: if None, publishes once. if not None, it is used as [Hz].
]
variable[p... | keyword[def] identifier[pub] ( identifier[topic_name] , identifier[json_msg] , identifier[repeat_rate] = keyword[None] , identifier[host] = identifier[jps] . identifier[env] . identifier[get_master_host] (), identifier[pub_port] = identifier[jps] . identifier[DEFAULT_PUB_PORT] ):
literal[string]
identifier... | def pub(topic_name, json_msg, repeat_rate=None, host=jps.env.get_master_host(), pub_port=jps.DEFAULT_PUB_PORT):
"""publishes the data to the topic
:param topic_name: name of the topic
:param json_msg: data to be published
:param repeat_rate: if None, publishes once. if not None, it is used as [Hz].
... |
def create_auth_manifest(**kwargs):
"""
Creates a basic authentication manifest for logging in, logging out and
registering new accounts.
"""
class AuthProgram(Program):
pre_input_middleware = [AuthenticationMiddleware]
def register(username, password, password2):
"""
De... | def function[create_auth_manifest, parameter[]]:
constant[
Creates a basic authentication manifest for logging in, logging out and
registering new accounts.
]
class class[AuthProgram, parameter[]] begin[:]
variable[pre_input_middleware] assign[=] list[[<ast.Name object at 0x7... | keyword[def] identifier[create_auth_manifest] (** identifier[kwargs] ):
literal[string]
keyword[class] identifier[AuthProgram] ( identifier[Program] ):
identifier[pre_input_middleware] =[ identifier[AuthenticationMiddleware] ]
keyword[def] identifier[register] ( identifier[username] , iden... | def create_auth_manifest(**kwargs):
"""
Creates a basic authentication manifest for logging in, logging out and
registering new accounts.
"""
class AuthProgram(Program):
pre_input_middleware = [AuthenticationMiddleware]
def register(username, password, password2):
"""
D... |
def _convert_to_degress(self, value):
"""Helper function to convert the GPS coordinates stored in the EXIF to degress in float format"""
d0 = value[0][0]
d1 = value[0][1]
d = float(d0) / float(d1)
m0 = value[1][0]
m1 = value[1][1]
m = float(m0) / float(m1)
... | def function[_convert_to_degress, parameter[self, value]]:
constant[Helper function to convert the GPS coordinates stored in the EXIF to degress in float format]
variable[d0] assign[=] call[call[name[value]][constant[0]]][constant[0]]
variable[d1] assign[=] call[call[name[value]][constant[0]]][c... | keyword[def] identifier[_convert_to_degress] ( identifier[self] , identifier[value] ):
literal[string]
identifier[d0] = identifier[value] [ literal[int] ][ literal[int] ]
identifier[d1] = identifier[value] [ literal[int] ][ literal[int] ]
identifier[d] = identifier[float] ( identi... | def _convert_to_degress(self, value):
"""Helper function to convert the GPS coordinates stored in the EXIF to degress in float format"""
d0 = value[0][0]
d1 = value[0][1]
d = float(d0) / float(d1)
m0 = value[1][0]
m1 = value[1][1]
m = float(m0) / float(m1)
s0 = value[2][0]
s1 = value... |
def split_cloud(cloud: str) -> [str]: # type: ignore
"""
Transforms a cloud string into a list of strings: [Type, Height (, Optional Modifier)]
"""
split = []
cloud = sanitize_cloud(cloud)
if cloud.startswith('VV'):
split.append(cloud[:2])
cloud = cloud[2:]
while len(cloud) ... | def function[split_cloud, parameter[cloud]]:
constant[
Transforms a cloud string into a list of strings: [Type, Height (, Optional Modifier)]
]
variable[split] assign[=] list[[]]
variable[cloud] assign[=] call[name[sanitize_cloud], parameter[name[cloud]]]
if call[name[cloud].star... | keyword[def] identifier[split_cloud] ( identifier[cloud] : identifier[str] )->[ identifier[str] ]:
literal[string]
identifier[split] =[]
identifier[cloud] = identifier[sanitize_cloud] ( identifier[cloud] )
keyword[if] identifier[cloud] . identifier[startswith] ( literal[string] ):
ident... | def split_cloud(cloud: str) -> [str]: # type: ignore
'\n Transforms a cloud string into a list of strings: [Type, Height (, Optional Modifier)]\n '
split = []
cloud = sanitize_cloud(cloud)
if cloud.startswith('VV'):
split.append(cloud[:2])
cloud = cloud[2:] # depends on [control=... |
def ensure_dtype(func, argname, arg):
"""
Argument preprocessor that converts the input into a numpy dtype.
Examples
--------
>>> import numpy as np
>>> from zipline.utils.preprocess import preprocess
>>> @preprocess(dtype=ensure_dtype)
... def foo(dtype):
... return dtype
.... | def function[ensure_dtype, parameter[func, argname, arg]]:
constant[
Argument preprocessor that converts the input into a numpy dtype.
Examples
--------
>>> import numpy as np
>>> from zipline.utils.preprocess import preprocess
>>> @preprocess(dtype=ensure_dtype)
... def foo(dtype):... | keyword[def] identifier[ensure_dtype] ( identifier[func] , identifier[argname] , identifier[arg] ):
literal[string]
keyword[try] :
keyword[return] identifier[dtype] ( identifier[arg] )
keyword[except] identifier[TypeError] :
keyword[raise] identifier[TypeError] (
literal[... | def ensure_dtype(func, argname, arg):
"""
Argument preprocessor that converts the input into a numpy dtype.
Examples
--------
>>> import numpy as np
>>> from zipline.utils.preprocess import preprocess
>>> @preprocess(dtype=ensure_dtype)
... def foo(dtype):
... return dtype
.... |
def __split_nonleaf_node(self, node):
"""!
@brief Performs splitting of the specified non-leaf node.
@param[in] node (non_leaf_node): Non-leaf node that should be splitted.
@return (list) New pair of non-leaf nodes [non_leaf_node1, non_leaf_node2].
... | def function[__split_nonleaf_node, parameter[self, node]]:
constant[!
@brief Performs splitting of the specified non-leaf node.
@param[in] node (non_leaf_node): Non-leaf node that should be splitted.
@return (list) New pair of non-leaf nodes [non_leaf_node1, non_leaf_no... | keyword[def] identifier[__split_nonleaf_node] ( identifier[self] , identifier[node] ):
literal[string]
[ identifier[farthest_node1] , identifier[farthest_node2] ]= identifier[node] . identifier[get_farthest_successors] ( identifier[self] . identifier[__type_measurement] );
... | def __split_nonleaf_node(self, node):
"""!
@brief Performs splitting of the specified non-leaf node.
@param[in] node (non_leaf_node): Non-leaf node that should be splitted.
@return (list) New pair of non-leaf nodes [non_leaf_node1, non_leaf_node2].
"""
... |
def relaxed_value_for_var(value, var):
"""
Returns a relaxed (possibly reshaped/upcast-ed) version of value,
to be loaded to the given variable.
Args:
value (ndarray): an numpy array to be loaded to var
var (tf.Variable):
Returns:
ndarray: a ... | def function[relaxed_value_for_var, parameter[value, var]]:
constant[
Returns a relaxed (possibly reshaped/upcast-ed) version of value,
to be loaded to the given variable.
Args:
value (ndarray): an numpy array to be loaded to var
var (tf.Variable):
Retur... | keyword[def] identifier[relaxed_value_for_var] ( identifier[value] , identifier[var] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[var] , identifier[tf] . identifier[Variable] )
identifier[name] = identifier[var] . identifier[op] . identifier[name]
... | def relaxed_value_for_var(value, var):
"""
Returns a relaxed (possibly reshaped/upcast-ed) version of value,
to be loaded to the given variable.
Args:
value (ndarray): an numpy array to be loaded to var
var (tf.Variable):
Returns:
ndarray: a poss... |
def plot_kde(self,
ax=None,
amax=None,
amin=None,
label=None,
return_fig=False):
"""
Plot a KDE for the curve. Very nice summary of KDEs:
https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/
... | def function[plot_kde, parameter[self, ax, amax, amin, label, return_fig]]:
constant[
Plot a KDE for the curve. Very nice summary of KDEs:
https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/
Args:
ax (axis): Optional matplotlib (MPL) axis to plot into. Retur... | keyword[def] identifier[plot_kde] ( identifier[self] ,
identifier[ax] = keyword[None] ,
identifier[amax] = keyword[None] ,
identifier[amin] = keyword[None] ,
identifier[label] = keyword[None] ,
identifier[return_fig] = keyword[False] ):
literal[string]
keyword[from] identifier[scipy] . identi... | def plot_kde(self, ax=None, amax=None, amin=None, label=None, return_fig=False):
"""
Plot a KDE for the curve. Very nice summary of KDEs:
https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/
Args:
ax (axis): Optional matplotlib (MPL) axis to plot into. Returned.
... |
def store(self, database, validate=True, role=None):
"""Store the document in the given database.
:param database: the `Database` object source for storing the document.
:return: an updated instance of `Document` / self.
"""
if validate:
self.validate()
self.... | def function[store, parameter[self, database, validate, role]]:
constant[Store the document in the given database.
:param database: the `Database` object source for storing the document.
:return: an updated instance of `Document` / self.
]
if name[validate] begin[:]
... | keyword[def] identifier[store] ( identifier[self] , identifier[database] , identifier[validate] = keyword[True] , identifier[role] = keyword[None] ):
literal[string]
keyword[if] identifier[validate] :
identifier[self] . identifier[validate] ()
identifier[self] . identifier[_i... | def store(self, database, validate=True, role=None):
"""Store the document in the given database.
:param database: the `Database` object source for storing the document.
:return: an updated instance of `Document` / self.
"""
if validate:
self.validate() # depends on [control=['... |
def record2marcxml(record):
"""Convert a JSON record to a MARCXML string.
Deduces which set of rules to use by parsing the ``$schema`` key, as
it unequivocally determines which kind of record we have.
Args:
record(dict): a JSON record.
Returns:
str: a MARCXML string converted from... | def function[record2marcxml, parameter[record]]:
constant[Convert a JSON record to a MARCXML string.
Deduces which set of rules to use by parsing the ``$schema`` key, as
it unequivocally determines which kind of record we have.
Args:
record(dict): a JSON record.
Returns:
str: ... | keyword[def] identifier[record2marcxml] ( identifier[record] ):
literal[string]
identifier[schema_name] = identifier[_get_schema_name] ( identifier[record] )
keyword[if] identifier[schema_name] == literal[string] :
identifier[marcjson] = identifier[hep2marc] . identifier[do] ( identifier[re... | def record2marcxml(record):
"""Convert a JSON record to a MARCXML string.
Deduces which set of rules to use by parsing the ``$schema`` key, as
it unequivocally determines which kind of record we have.
Args:
record(dict): a JSON record.
Returns:
str: a MARCXML string converted from... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.