code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def periods(dts, phi=0.0):
"""For an ensemble of oscillators, return the set of periods lengths of
all successive oscillations of all oscillators.
An individual oscillation is defined to start and end when the phase
passes phi (by default zero) after completing a full cycle.
If the timeseries of... | def function[periods, parameter[dts, phi]]:
constant[For an ensemble of oscillators, return the set of periods lengths of
all successive oscillations of all oscillators.
An individual oscillation is defined to start and end when the phase
passes phi (by default zero) after completing a full cycle... | keyword[def] identifier[periods] ( identifier[dts] , identifier[phi] = literal[int] ):
literal[string]
identifier[vperiods] = identifier[distob] . identifier[vectorize] ( identifier[analyses1] . identifier[periods] )
identifier[all_periods] = identifier[vperiods] ( identifier[dts] , identifier[phi] )
... | def periods(dts, phi=0.0):
"""For an ensemble of oscillators, return the set of periods lengths of
all successive oscillations of all oscillators.
An individual oscillation is defined to start and end when the phase
passes phi (by default zero) after completing a full cycle.
If the timeseries of... |
def ser_a_trous(C0, filter, scale):
"""
The following is a serial implementation of the a trous algorithm. Accepts the following parameters:
INPUTS:
filter (no default): The filter-bank which is applied to the components of the transform.
C0 (no default): The current array on whic... | def function[ser_a_trous, parameter[C0, filter, scale]]:
constant[
The following is a serial implementation of the a trous algorithm. Accepts the following parameters:
INPUTS:
filter (no default): The filter-bank which is applied to the components of the transform.
C0 (no defaul... | keyword[def] identifier[ser_a_trous] ( identifier[C0] , identifier[filter] , identifier[scale] ):
literal[string]
identifier[tmp] = identifier[filter] [ literal[int] ]* identifier[C0]
identifier[tmp] [( literal[int] **( identifier[scale] + literal[int] )):,:]+= identifier[filter] [ literal[int] ]* i... | def ser_a_trous(C0, filter, scale):
"""
The following is a serial implementation of the a trous algorithm. Accepts the following parameters:
INPUTS:
filter (no default): The filter-bank which is applied to the components of the transform.
C0 (no default): The current array on whic... |
def cache_entry(self):
"""
Returns a CacheEntry instance for File.
"""
if self.storage_path is None:
raise ValueError('This file is temporary and so a lal '
'cache entry cannot be made')
file_url = urlparse.urlunparse(['file', 'localhost'... | def function[cache_entry, parameter[self]]:
constant[
Returns a CacheEntry instance for File.
]
if compare[name[self].storage_path is constant[None]] begin[:]
<ast.Raise object at 0x7da18dc99b40>
variable[file_url] assign[=] call[name[urlparse].urlunparse, parameter[list[... | keyword[def] identifier[cache_entry] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[storage_path] keyword[is] keyword[None] :
keyword[raise] identifier[ValueError] ( literal[string]
literal[string] )
identifier[file_url] = id... | def cache_entry(self):
"""
Returns a CacheEntry instance for File.
"""
if self.storage_path is None:
raise ValueError('This file is temporary and so a lal cache entry cannot be made') # depends on [control=['if'], data=[]]
file_url = urlparse.urlunparse(['file', 'localhost', self.st... |
def get_daemon_stats(self, details=False):
"""Increase the stats provided by the Daemon base class
:return: stats dictionary
:rtype: dict
"""
# Call the base Daemon one
res = super(Alignak, self).get_daemon_stats(details=details)
res.update({'name': self.name, '... | def function[get_daemon_stats, parameter[self, details]]:
constant[Increase the stats provided by the Daemon base class
:return: stats dictionary
:rtype: dict
]
variable[res] assign[=] call[call[name[super], parameter[name[Alignak], name[self]]].get_daemon_stats, parameter[]]
... | keyword[def] identifier[get_daemon_stats] ( identifier[self] , identifier[details] = keyword[False] ):
literal[string]
identifier[res] = identifier[super] ( identifier[Alignak] , identifier[self] ). identifier[get_daemon_stats] ( identifier[details] = identifier[details] )
identi... | def get_daemon_stats(self, details=False):
"""Increase the stats provided by the Daemon base class
:return: stats dictionary
:rtype: dict
"""
# Call the base Daemon one
res = super(Alignak, self).get_daemon_stats(details=details)
res.update({'name': self.name, 'type': self.type,... |
def _prepare_output(partitions, verbose):
"""Returns dict with 'raw' and 'message' keys filled."""
out = {}
partitions_count = len(partitions)
out['raw'] = {
'offline_count': partitions_count,
}
if partitions_count == 0:
out['message'] = 'No offline partitions.'
else:
... | def function[_prepare_output, parameter[partitions, verbose]]:
constant[Returns dict with 'raw' and 'message' keys filled.]
variable[out] assign[=] dictionary[[], []]
variable[partitions_count] assign[=] call[name[len], parameter[name[partitions]]]
call[name[out]][constant[raw]] assign[=... | keyword[def] identifier[_prepare_output] ( identifier[partitions] , identifier[verbose] ):
literal[string]
identifier[out] ={}
identifier[partitions_count] = identifier[len] ( identifier[partitions] )
identifier[out] [ literal[string] ]={
literal[string] : identifier[partitions_count] ,
... | def _prepare_output(partitions, verbose):
"""Returns dict with 'raw' and 'message' keys filled."""
out = {}
partitions_count = len(partitions)
out['raw'] = {'offline_count': partitions_count}
if partitions_count == 0:
out['message'] = 'No offline partitions.' # depends on [control=['if'], d... |
def connect(host, port=None, **kwargs):
'''
Test connectivity to a host using a particular
port from the minion.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' network.connect archlinux.org 80
salt '*' network.connect archlinux.org 80 timeout=3
... | def function[connect, parameter[host, port]]:
constant[
Test connectivity to a host using a particular
port from the minion.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' network.connect archlinux.org 80
salt '*' network.connect archlinux.org 80 t... | keyword[def] identifier[connect] ( identifier[host] , identifier[port] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[ret] ={ literal[string] : keyword[None] ,
literal[string] : literal[string] }
keyword[if] keyword[not] identifier[host] :
identifier[ret] [ lite... | def connect(host, port=None, **kwargs):
"""
Test connectivity to a host using a particular
port from the minion.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' network.connect archlinux.org 80
salt '*' network.connect archlinux.org 80 timeout=3
... |
def operate(self, point):
"""
Apply the operation on a point.
Args:
point: Cartesian coordinate.
Returns:
Coordinates of point after operation.
"""
affine_point = np.array([point[0], point[1], point[2], 1])
return np.dot(self.affine_matri... | def function[operate, parameter[self, point]]:
constant[
Apply the operation on a point.
Args:
point: Cartesian coordinate.
Returns:
Coordinates of point after operation.
]
variable[affine_point] assign[=] call[name[np].array, parameter[list[[<as... | keyword[def] identifier[operate] ( identifier[self] , identifier[point] ):
literal[string]
identifier[affine_point] = identifier[np] . identifier[array] ([ identifier[point] [ literal[int] ], identifier[point] [ literal[int] ], identifier[point] [ literal[int] ], literal[int] ])
keyword[re... | def operate(self, point):
"""
Apply the operation on a point.
Args:
point: Cartesian coordinate.
Returns:
Coordinates of point after operation.
"""
affine_point = np.array([point[0], point[1], point[2], 1])
return np.dot(self.affine_matrix, affine_po... |
def render(self, bindings):
"""Renders a string from a path template using the provided bindings.
Args:
bindings (dict): A dictionary of var names to binding strings.
Returns:
str: The rendered instantiation of this path template.
Raises:
Validation... | def function[render, parameter[self, bindings]]:
constant[Renders a string from a path template using the provided bindings.
Args:
bindings (dict): A dictionary of var names to binding strings.
Returns:
str: The rendered instantiation of this path template.
Rai... | keyword[def] identifier[render] ( identifier[self] , identifier[bindings] ):
literal[string]
identifier[out] =[]
identifier[binding] = keyword[False]
keyword[for] identifier[segment] keyword[in] identifier[self] . identifier[segments] :
keyword[if] identifier[seg... | def render(self, bindings):
"""Renders a string from a path template using the provided bindings.
Args:
bindings (dict): A dictionary of var names to binding strings.
Returns:
str: The rendered instantiation of this path template.
Raises:
ValidationErro... |
def _reverse_to_source(self, target, group1):
"""
Args:
target (dict): A table containing the reverse transitions for each state
group1 (list): A group of states
Return:
Set: A set of states for which there is a transition with the states of the group
... | def function[_reverse_to_source, parameter[self, target, group1]]:
constant[
Args:
target (dict): A table containing the reverse transitions for each state
group1 (list): A group of states
Return:
Set: A set of states for which there is a transition with the s... | keyword[def] identifier[_reverse_to_source] ( identifier[self] , identifier[target] , identifier[group1] ):
literal[string]
identifier[new_group] =[]
keyword[for] identifier[dst] keyword[in] identifier[group1] :
identifier[new_group] += identifier[target] [ identifier[dst] ... | def _reverse_to_source(self, target, group1):
"""
Args:
target (dict): A table containing the reverse transitions for each state
group1 (list): A group of states
Return:
Set: A set of states for which there is a transition with the states of the group
"""
... |
def mirtrace_rna_categories(self):
""" Generate the miRTrace RNA Categories"""
# Specify the order of the different possible categories
keys = OrderedDict()
keys['reads_mirna'] = { 'color': '#33a02c', 'name': 'miRNA' }
keys['reads_rrna'] = { 'color': '#ff7f00', 'n... | def function[mirtrace_rna_categories, parameter[self]]:
constant[ Generate the miRTrace RNA Categories]
variable[keys] assign[=] call[name[OrderedDict], parameter[]]
call[name[keys]][constant[reads_mirna]] assign[=] dictionary[[<ast.Constant object at 0x7da20e9b07f0>, <ast.Constant object at 0x7... | keyword[def] identifier[mirtrace_rna_categories] ( identifier[self] ):
literal[string]
identifier[keys] = identifier[OrderedDict] ()
identifier[keys] [ literal[string] ]={ literal[string] : literal[string] , literal[string] : literal[string] }
identifier[keys] [ literal[... | def mirtrace_rna_categories(self):
""" Generate the miRTrace RNA Categories"""
# Specify the order of the different possible categories
keys = OrderedDict()
keys['reads_mirna'] = {'color': '#33a02c', 'name': 'miRNA'}
keys['reads_rrna'] = {'color': '#ff7f00', 'name': 'rRNA'}
keys['reads_trna'] = ... |
def filter_by_meta(data, df, join_meta=False, **kwargs):
"""Filter by and join meta columns from an IamDataFrame to a pd.DataFrame
Parameters
----------
data: pd.DataFrame instance
DataFrame to which meta columns are to be joined,
index or columns must include `['model', 'scenario']`
... | def function[filter_by_meta, parameter[data, df, join_meta]]:
constant[Filter by and join meta columns from an IamDataFrame to a pd.DataFrame
Parameters
----------
data: pd.DataFrame instance
DataFrame to which meta columns are to be joined,
index or columns must include `['model', ... | keyword[def] identifier[filter_by_meta] ( identifier[data] , identifier[df] , identifier[join_meta] = keyword[False] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[set] ( identifier[META_IDX] ). identifier[issubset] ( identifier[data] . identifier[index] . identifier[names]... | def filter_by_meta(data, df, join_meta=False, **kwargs):
"""Filter by and join meta columns from an IamDataFrame to a pd.DataFrame
Parameters
----------
data: pd.DataFrame instance
DataFrame to which meta columns are to be joined,
index or columns must include `['model', 'scenario']`
... |
def resolution(self, index):
"""Resolution with a given index.
Parameters
----------
index : int
Resolution index.
Global if this is the ``aionationstates.wa`` object, local
if this is ``aionationstates.ga`` or ``aionationstates.sc``.
Return... | def function[resolution, parameter[self, index]]:
constant[Resolution with a given index.
Parameters
----------
index : int
Resolution index.
Global if this is the ``aionationstates.wa`` object, local
if this is ``aionationstates.ga`` or ``aionations... | keyword[def] identifier[resolution] ( identifier[self] , identifier[index] ):
literal[string]
@ identifier[api_query] ( literal[string] , identifier[id] = identifier[str] ( identifier[index] ))
keyword[async] keyword[def] identifier[result] ( identifier[_] , identifier[root] ):
... | def resolution(self, index):
"""Resolution with a given index.
Parameters
----------
index : int
Resolution index.
Global if this is the ``aionationstates.wa`` object, local
if this is ``aionationstates.ga`` or ``aionationstates.sc``.
Returns
... |
def read_xml(cls, url, features, timestamp, game_number):
"""
read xml object
:param url: contents url
:param features: markup provider
:param timestamp: game day
:param game_number: game number
:return: pitchpx.game.game.Game object
"""
soup = Mlb... | def function[read_xml, parameter[cls, url, features, timestamp, game_number]]:
constant[
read xml object
:param url: contents url
:param features: markup provider
:param timestamp: game day
:param game_number: game number
:return: pitchpx.game.game.Game object
... | keyword[def] identifier[read_xml] ( identifier[cls] , identifier[url] , identifier[features] , identifier[timestamp] , identifier[game_number] ):
literal[string]
identifier[soup] = identifier[MlbamUtil] . identifier[find_xml] ( literal[string] . identifier[join] ([ identifier[url] , identifier[cls]... | def read_xml(cls, url, features, timestamp, game_number):
"""
read xml object
:param url: contents url
:param features: markup provider
:param timestamp: game day
:param game_number: game number
:return: pitchpx.game.game.Game object
"""
soup = MlbamUtil.f... |
def copy_bootstrap(bootstrap_target: Path) -> None:
"""Copy bootstrap code from shiv into the pyz.
This function is excluded from type checking due to the conditional import.
:param bootstrap_target: The temporary directory where we are staging pyz contents.
"""
for bootstrap_file in importlib_re... | def function[copy_bootstrap, parameter[bootstrap_target]]:
constant[Copy bootstrap code from shiv into the pyz.
This function is excluded from type checking due to the conditional import.
:param bootstrap_target: The temporary directory where we are staging pyz contents.
]
for taget[name[b... | keyword[def] identifier[copy_bootstrap] ( identifier[bootstrap_target] : identifier[Path] )-> keyword[None] :
literal[string]
keyword[for] identifier[bootstrap_file] keyword[in] identifier[importlib_resources] . identifier[contents] ( identifier[bootstrap] ):
keyword[if] identifier[importlib_... | def copy_bootstrap(bootstrap_target: Path) -> None:
"""Copy bootstrap code from shiv into the pyz.
This function is excluded from type checking due to the conditional import.
:param bootstrap_target: The temporary directory where we are staging pyz contents.
"""
for bootstrap_file in importlib_res... |
def replace_all_post_order(expression: Expression, rules: Iterable[ReplacementRule]) \
-> Union[Expression, Sequence[Expression]]:
"""Replace all occurrences of the patterns according to the replacement rules.
A replacement rule consists of a *pattern*, that is matched against any subexpression
of ... | def function[replace_all_post_order, parameter[expression, rules]]:
constant[Replace all occurrences of the patterns according to the replacement rules.
A replacement rule consists of a *pattern*, that is matched against any subexpression
of the expression. If a match is found, the *replacement* callba... | keyword[def] identifier[replace_all_post_order] ( identifier[expression] : identifier[Expression] , identifier[rules] : identifier[Iterable] [ identifier[ReplacementRule] ])-> identifier[Union] [ identifier[Expression] , identifier[Sequence] [ identifier[Expression] ]]:
literal[string]
keyword[return] ide... | def replace_all_post_order(expression: Expression, rules: Iterable[ReplacementRule]) -> Union[Expression, Sequence[Expression]]:
"""Replace all occurrences of the patterns according to the replacement rules.
A replacement rule consists of a *pattern*, that is matched against any subexpression
of the expres... |
def zremrangebyrank(self, key, start, stop):
"""Remove all members in a sorted set within the given indexes.
:raises TypeError: if start is not int
:raises TypeError: if stop is not int
"""
if not isinstance(start, int):
raise TypeError("start argument must be int")
... | def function[zremrangebyrank, parameter[self, key, start, stop]]:
constant[Remove all members in a sorted set within the given indexes.
:raises TypeError: if start is not int
:raises TypeError: if stop is not int
]
if <ast.UnaryOp object at 0x7da1b235b550> begin[:]
<ast.... | keyword[def] identifier[zremrangebyrank] ( identifier[self] , identifier[key] , identifier[start] , identifier[stop] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[start] , identifier[int] ):
keyword[raise] identifier[TypeError] ( literal[string] )
... | def zremrangebyrank(self, key, start, stop):
"""Remove all members in a sorted set within the given indexes.
:raises TypeError: if start is not int
:raises TypeError: if stop is not int
"""
if not isinstance(start, int):
raise TypeError('start argument must be int') # depends o... |
def create_runscript(self, default="/bin/bash", force=False):
'''create_entrypoint is intended to create a singularity runscript
based on a Docker entrypoint or command. We first use the Docker
ENTRYPOINT, if defined. If not, we use the CMD. If neither is found,
we use function default.
... | def function[create_runscript, parameter[self, default, force]]:
constant[create_entrypoint is intended to create a singularity runscript
based on a Docker entrypoint or command. We first use the Docker
ENTRYPOINT, if defined. If not, we use the CMD. If neither is found,
we use function def... | keyword[def] identifier[create_runscript] ( identifier[self] , identifier[default] = literal[string] , identifier[force] = keyword[False] ):
literal[string]
identifier[entrypoint] = identifier[default]
keyword[if] identifier[force] keyword[is] keyword[False] :
keyword[if] identifie... | def create_runscript(self, default='/bin/bash', force=False):
"""create_entrypoint is intended to create a singularity runscript
based on a Docker entrypoint or command. We first use the Docker
ENTRYPOINT, if defined. If not, we use the CMD. If neither is found,
we use function default.
... |
def get_substances(identifier, namespace='sid', as_dataframe=False, **kwargs):
"""Retrieve the specified substance records from PubChem.
:param identifier: The substance identifier to use as a search query.
:param namespace: (optional) The identifier type, one of sid, name or sourceid/<source name>.
:p... | def function[get_substances, parameter[identifier, namespace, as_dataframe]]:
constant[Retrieve the specified substance records from PubChem.
:param identifier: The substance identifier to use as a search query.
:param namespace: (optional) The identifier type, one of sid, name or sourceid/<source name... | keyword[def] identifier[get_substances] ( identifier[identifier] , identifier[namespace] = literal[string] , identifier[as_dataframe] = keyword[False] ,** identifier[kwargs] ):
literal[string]
identifier[results] = identifier[get_json] ( identifier[identifier] , identifier[namespace] , literal[string] ,** ... | def get_substances(identifier, namespace='sid', as_dataframe=False, **kwargs):
"""Retrieve the specified substance records from PubChem.
:param identifier: The substance identifier to use as a search query.
:param namespace: (optional) The identifier type, one of sid, name or sourceid/<source name>.
:p... |
def get_request_url(environ):
# type: (Dict[str, str]) -> str
"""Return the absolute URL without query string for the given WSGI
environment."""
return "%s://%s/%s" % (
environ.get("wsgi.url_scheme"),
get_host(environ),
wsgi_decoding_dance(environ.get("PATH_INFO") or "").lstrip("... | def function[get_request_url, parameter[environ]]:
constant[Return the absolute URL without query string for the given WSGI
environment.]
return[binary_operation[constant[%s://%s/%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Call object at 0x7da1b19cebf0>, <ast.Call object at 0x7da1b19cce20>, <ast.... | keyword[def] identifier[get_request_url] ( identifier[environ] ):
literal[string]
keyword[return] literal[string] %(
identifier[environ] . identifier[get] ( literal[string] ),
identifier[get_host] ( identifier[environ] ),
identifier[wsgi_decoding_dance] ( identifier[environ] . identifier[g... | def get_request_url(environ):
# type: (Dict[str, str]) -> str
'Return the absolute URL without query string for the given WSGI\n environment.'
return '%s://%s/%s' % (environ.get('wsgi.url_scheme'), get_host(environ), wsgi_decoding_dance(environ.get('PATH_INFO') or '').lstrip('/')) |
def is_touched(self, position):
"""Hit detection method.
Indicates if this key has been hit by a touch / click event at the given position.
:param position: Event position.
:returns: True is the given position collide this key, False otherwise.
"""
return positi... | def function[is_touched, parameter[self, position]]:
constant[Hit detection method.
Indicates if this key has been hit by a touch / click event at the given position.
:param position: Event position.
:returns: True is the given position collide this key, False otherwise.
... | keyword[def] identifier[is_touched] ( identifier[self] , identifier[position] ):
literal[string]
keyword[return] identifier[position] [ literal[int] ]>= identifier[self] . identifier[position] [ literal[int] ] keyword[and] identifier[position] [ literal[int] ]<= identifier[self] . identifier[posi... | def is_touched(self, position):
"""Hit detection method.
Indicates if this key has been hit by a touch / click event at the given position.
:param position: Event position.
:returns: True is the given position collide this key, False otherwise.
"""
return position[0] >=... |
def as_dict(self):
"""
Returns the model as a dict
"""
if not self._is_valid:
self.validate()
from .converters import to_dict
return to_dict(self) | def function[as_dict, parameter[self]]:
constant[
Returns the model as a dict
]
if <ast.UnaryOp object at 0x7da1b04c9240> begin[:]
call[name[self].validate, parameter[]]
from relative_module[converters] import module[to_dict]
return[call[name[to_dict], parameter[n... | keyword[def] identifier[as_dict] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_is_valid] :
identifier[self] . identifier[validate] ()
keyword[from] . identifier[converters] keyword[import] identifier[to_dict]
keywo... | def as_dict(self):
"""
Returns the model as a dict
"""
if not self._is_valid:
self.validate() # depends on [control=['if'], data=[]]
from .converters import to_dict
return to_dict(self) |
def get_clusters_from_fasta_filepath(
fasta_filepath,
original_fasta_path,
percent_ID=0.97,
max_accepts=1,
max_rejects=8,
stepwords=8,
word_length=8,
optimal=False,
exact=False,
suppress_sort=False,
output_dir=None,
enable_r... | def function[get_clusters_from_fasta_filepath, parameter[fasta_filepath, original_fasta_path, percent_ID, max_accepts, max_rejects, stepwords, word_length, optimal, exact, suppress_sort, output_dir, enable_rev_strand_matching, subject_fasta_filepath, suppress_new_clusters, return_cluster_maps, stable_sort, tmp_dir, sav... | keyword[def] identifier[get_clusters_from_fasta_filepath] (
identifier[fasta_filepath] ,
identifier[original_fasta_path] ,
identifier[percent_ID] = literal[int] ,
identifier[max_accepts] = literal[int] ,
identifier[max_rejects] = literal[int] ,
identifier[stepwords] = literal[int] ,
identifier[word_length] = l... | def get_clusters_from_fasta_filepath(fasta_filepath, original_fasta_path, percent_ID=0.97, max_accepts=1, max_rejects=8, stepwords=8, word_length=8, optimal=False, exact=False, suppress_sort=False, output_dir=None, enable_rev_strand_matching=False, subject_fasta_filepath=None, suppress_new_clusters=False, return_cluste... |
def get_authorizations(self):
"""
:calls: `GET /authorizations <http://developer.github.com/v3/oauth>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Authorization.Authorization`
"""
return github.PaginatedList.PaginatedList(
github.Authorizati... | def function[get_authorizations, parameter[self]]:
constant[
:calls: `GET /authorizations <http://developer.github.com/v3/oauth>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Authorization.Authorization`
]
return[call[name[github].PaginatedList.PaginatedList... | keyword[def] identifier[get_authorizations] ( identifier[self] ):
literal[string]
keyword[return] identifier[github] . identifier[PaginatedList] . identifier[PaginatedList] (
identifier[github] . identifier[Authorization] . identifier[Authorization] ,
identifier[self] . identifie... | def get_authorizations(self):
"""
:calls: `GET /authorizations <http://developer.github.com/v3/oauth>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Authorization.Authorization`
"""
return github.PaginatedList.PaginatedList(github.Authorization.Authorization, sel... |
def report( self, params, meta, res ):
"""Return a properly-structured dict of results. The default returns a dict with
results keyed by :attr:`Experiment.RESULTS`, the data point in the parameter space
keyed by :attr:`Experiment.PARAMETERS`, and timing and other metadata keyed
by :attr:... | def function[report, parameter[self, params, meta, res]]:
constant[Return a properly-structured dict of results. The default returns a dict with
results keyed by :attr:`Experiment.RESULTS`, the data point in the parameter space
keyed by :attr:`Experiment.PARAMETERS`, and timing and other metadat... | keyword[def] identifier[report] ( identifier[self] , identifier[params] , identifier[meta] , identifier[res] ):
literal[string]
identifier[rc] = identifier[dict] ()
identifier[rc] [ identifier[self] . identifier[PARAMETERS] ]= identifier[params] . identifier[copy] ()
identifier[rc... | def report(self, params, meta, res):
"""Return a properly-structured dict of results. The default returns a dict with
results keyed by :attr:`Experiment.RESULTS`, the data point in the parameter space
keyed by :attr:`Experiment.PARAMETERS`, and timing and other metadata keyed
by :attr:`Exper... |
def get_purge_files(root, output, output_schema, descriptor, descriptor_schema):
"""Get files to purge."""
def remove_file(fn, paths):
"""From paths remove fn and dirs before fn in dir tree."""
while fn:
for i in range(len(paths) - 1, -1, -1):
if fn == paths[i]:
... | def function[get_purge_files, parameter[root, output, output_schema, descriptor, descriptor_schema]]:
constant[Get files to purge.]
def function[remove_file, parameter[fn, paths]]:
constant[From paths remove fn and dirs before fn in dir tree.]
while name[fn] begin[:]
... | keyword[def] identifier[get_purge_files] ( identifier[root] , identifier[output] , identifier[output_schema] , identifier[descriptor] , identifier[descriptor_schema] ):
literal[string]
keyword[def] identifier[remove_file] ( identifier[fn] , identifier[paths] ):
literal[string]
keyword[w... | def get_purge_files(root, output, output_schema, descriptor, descriptor_schema):
"""Get files to purge."""
def remove_file(fn, paths):
"""From paths remove fn and dirs before fn in dir tree."""
while fn:
for i in range(len(paths) - 1, -1, -1):
if fn == paths[i]:
... |
def main(argv=None, directory=None):
"""
Main entry point for the tool, used by setup.py
Returns a value that can be passed into exit() specifying
the exit code.
1 is an error
0 is successful run
"""
logging.basicConfig(format='%(message)s')
argv = argv or sys.argv
arg_dict = pa... | def function[main, parameter[argv, directory]]:
constant[
Main entry point for the tool, used by setup.py
Returns a value that can be passed into exit() specifying
the exit code.
1 is an error
0 is successful run
]
call[name[logging].basicConfig, parameter[]]
variable[arg... | keyword[def] identifier[main] ( identifier[argv] = keyword[None] , identifier[directory] = keyword[None] ):
literal[string]
identifier[logging] . identifier[basicConfig] ( identifier[format] = literal[string] )
identifier[argv] = identifier[argv] keyword[or] identifier[sys] . identifier[argv]
... | def main(argv=None, directory=None):
"""
Main entry point for the tool, used by setup.py
Returns a value that can be passed into exit() specifying
the exit code.
1 is an error
0 is successful run
"""
logging.basicConfig(format='%(message)s')
argv = argv or sys.argv
arg_dict = par... |
def do_ls(self, line):
"""ls [-a] [-l] [FILE|DIRECTORY|PATTERN]...
PATTERN supports * ? [seq] [!seq] Unix filename matching
List directory contents.
"""
args = self.line_to_args(line)
if len(args.filenames) == 0:
args.filenames = ['.']
for idx, fn i... | def function[do_ls, parameter[self, line]]:
constant[ls [-a] [-l] [FILE|DIRECTORY|PATTERN]...
PATTERN supports * ? [seq] [!seq] Unix filename matching
List directory contents.
]
variable[args] assign[=] call[name[self].line_to_args, parameter[name[line]]]
if compare[ca... | keyword[def] identifier[do_ls] ( identifier[self] , identifier[line] ):
literal[string]
identifier[args] = identifier[self] . identifier[line_to_args] ( identifier[line] )
keyword[if] identifier[len] ( identifier[args] . identifier[filenames] )== literal[int] :
identifier[arg... | def do_ls(self, line):
"""ls [-a] [-l] [FILE|DIRECTORY|PATTERN]...
PATTERN supports * ? [seq] [!seq] Unix filename matching
List directory contents.
"""
args = self.line_to_args(line)
if len(args.filenames) == 0:
args.filenames = ['.'] # depends on [control=['if'], data=[... |
def discands(record):
"""Display the candidates contained in a candidate record list"""
import pyraf, pyfits
pyraf.iraf.tv()
display = pyraf.iraf.tv.display
width=128
cands = record['cands']
exps= record['fileId']
### load some header info from the mophead file
headers=... | def function[discands, parameter[record]]:
constant[Display the candidates contained in a candidate record list]
import module[pyraf], module[pyfits]
call[name[pyraf].iraf.tv, parameter[]]
variable[display] assign[=] name[pyraf].iraf.tv.display
variable[width] assign[=] constant[128]... | keyword[def] identifier[discands] ( identifier[record] ):
literal[string]
keyword[import] identifier[pyraf] , identifier[pyfits]
identifier[pyraf] . identifier[iraf] . identifier[tv] ()
identifier[display] = identifier[pyraf] . identifier[iraf] . identifier[tv] . identifier[display]
ide... | def discands(record):
"""Display the candidates contained in a candidate record list"""
import pyraf, pyfits
pyraf.iraf.tv()
display = pyraf.iraf.tv.display
width = 128
cands = record['cands']
exps = record['fileId']
### load some header info from the mophead file
headers = {}
fo... |
def from_xarray(da, crs=None, apply_transform=False, nan_nodata=False, **kwargs):
"""
Returns an RGB or Image element given an xarray DataArray
loaded using xr.open_rasterio.
If a crs attribute is present on the loaded data it will
attempt to decode it into a cartopy projection otherwise it
wil... | def function[from_xarray, parameter[da, crs, apply_transform, nan_nodata]]:
constant[
Returns an RGB or Image element given an xarray DataArray
loaded using xr.open_rasterio.
If a crs attribute is present on the loaded data it will
attempt to decode it into a cartopy projection otherwise it
... | keyword[def] identifier[from_xarray] ( identifier[da] , identifier[crs] = keyword[None] , identifier[apply_transform] = keyword[False] , identifier[nan_nodata] = keyword[False] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[crs] :
identifier[kwargs] [ literal[string] ]= identifi... | def from_xarray(da, crs=None, apply_transform=False, nan_nodata=False, **kwargs):
"""
Returns an RGB or Image element given an xarray DataArray
loaded using xr.open_rasterio.
If a crs attribute is present on the loaded data it will
attempt to decode it into a cartopy projection otherwise it
wil... |
def reset(self):
"""
Clears all entries.
:return: None
"""
for i in range(len(self.values)):
self.values[i].delete(0, tk.END)
if self.defaults[i] is not None:
self.values[i].insert(0, self.defaults[i]) | def function[reset, parameter[self]]:
constant[
Clears all entries.
:return: None
]
for taget[name[i]] in starred[call[name[range], parameter[call[name[len], parameter[name[self].values]]]]] begin[:]
call[call[name[self].values][name[i]].delete, parameter[constan... | keyword[def] identifier[reset] ( identifier[self] ):
literal[string]
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[len] ( identifier[self] . identifier[values] )):
identifier[self] . identifier[values] [ identifier[i] ]. identifier[delete] ( literal[int] , id... | def reset(self):
"""
Clears all entries.
:return: None
"""
for i in range(len(self.values)):
self.values[i].delete(0, tk.END)
if self.defaults[i] is not None:
self.values[i].insert(0, self.defaults[i]) # depends on [control=['if'], data=[]] # depends on [co... |
def _convert_list_to_json(array):
""" Converts array to a json string """
return json.dumps(array, skipkeys=False, allow_nan=False, indent=None, separators=(",", ":")) | def function[_convert_list_to_json, parameter[array]]:
constant[ Converts array to a json string ]
return[call[name[json].dumps, parameter[name[array]]]] | keyword[def] identifier[_convert_list_to_json] ( identifier[array] ):
literal[string]
keyword[return] identifier[json] . identifier[dumps] ( identifier[array] , identifier[skipkeys] = keyword[False] , identifier[allow_nan] = keyword[False] , identifier[indent] = keyword[None] , identifier[separators] =( l... | def _convert_list_to_json(array):
""" Converts array to a json string """
return json.dumps(array, skipkeys=False, allow_nan=False, indent=None, separators=(',', ':')) |
def verify_user_alias(user, token):
"""
Marks a user's contact point as verified depending on accepted token type.
"""
if token.to_alias_type == 'EMAIL':
if token.to_alias == getattr(user, api_settings.PASSWORDLESS_USER_EMAIL_FIELD_NAME):
setattr(user, api_settings.PASSWORDLESS_USER_... | def function[verify_user_alias, parameter[user, token]]:
constant[
Marks a user's contact point as verified depending on accepted token type.
]
if compare[name[token].to_alias_type equal[==] constant[EMAIL]] begin[:]
if compare[name[token].to_alias equal[==] call[name[getattr], p... | keyword[def] identifier[verify_user_alias] ( identifier[user] , identifier[token] ):
literal[string]
keyword[if] identifier[token] . identifier[to_alias_type] == literal[string] :
keyword[if] identifier[token] . identifier[to_alias] == identifier[getattr] ( identifier[user] , identifier[api_sett... | def verify_user_alias(user, token):
"""
Marks a user's contact point as verified depending on accepted token type.
"""
if token.to_alias_type == 'EMAIL':
if token.to_alias == getattr(user, api_settings.PASSWORDLESS_USER_EMAIL_FIELD_NAME):
setattr(user, api_settings.PASSWORDLESS_USER_... |
def _set_rock_ridge(self, rr):
# type: (str) -> None
'''
An internal method to set the Rock Ridge version of the ISO given the
Rock Ridge version of the previous entry.
Parameters:
rr - The version of rr from the last directory record.
Returns:
Nothing.... | def function[_set_rock_ridge, parameter[self, rr]]:
constant[
An internal method to set the Rock Ridge version of the ISO given the
Rock Ridge version of the previous entry.
Parameters:
rr - The version of rr from the last directory record.
Returns:
Nothing.
... | keyword[def] identifier[_set_rock_ridge] ( identifier[self] , identifier[rr] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[rock_ridge] :
identifier[self] . identifier[rock_ridge] = identifier[rr]
keyw... | def _set_rock_ridge(self, rr):
# type: (str) -> None
'\n An internal method to set the Rock Ridge version of the ISO given the\n Rock Ridge version of the previous entry.\n\n Parameters:\n rr - The version of rr from the last directory record.\n Returns:\n Nothing.\n ... |
def new_values(self):
'''Returns the new values from the diff'''
def get_new_values_and_key(item):
values = item.new_values
if item.past_dict:
values.update({self._key: item.past_dict[self._key]})
else:
# This is a new item as it has no... | def function[new_values, parameter[self]]:
constant[Returns the new values from the diff]
def function[get_new_values_and_key, parameter[item]]:
variable[values] assign[=] name[item].new_values
if name[item].past_dict begin[:]
call[name[values].upd... | keyword[def] identifier[new_values] ( identifier[self] ):
literal[string]
keyword[def] identifier[get_new_values_and_key] ( identifier[item] ):
identifier[values] = identifier[item] . identifier[new_values]
keyword[if] identifier[item] . identifier[past_dict] :
... | def new_values(self):
"""Returns the new values from the diff"""
def get_new_values_and_key(item):
values = item.new_values
if item.past_dict:
values.update({self._key: item.past_dict[self._key]}) # depends on [control=['if'], data=[]]
else:
# This is a new item... |
def remove_hooks(target, **hooks):
"""
Remove the given hooks from the given target.
:param target: The object from which to remove hooks. If all hooks are removed from a given method, the
HookedMethod object will be removed and replaced with the original function.
... | def function[remove_hooks, parameter[target]]:
constant[
Remove the given hooks from the given target.
:param target: The object from which to remove hooks. If all hooks are removed from a given method, the
HookedMethod object will be removed and replaced with the origi... | keyword[def] identifier[remove_hooks] ( identifier[target] ,** identifier[hooks] ):
literal[string]
keyword[for] identifier[name] , identifier[hook] keyword[in] identifier[hooks] . identifier[items] ():
identifier[hooked] = identifier[getattr] ( identifier[target] , identifier[name]... | def remove_hooks(target, **hooks):
"""
Remove the given hooks from the given target.
:param target: The object from which to remove hooks. If all hooks are removed from a given method, the
HookedMethod object will be removed and replaced with the original function.
... |
def get_all_names_page(offset, count, include_expired=False, hostport=None, proxy=None):
"""
get a page of all the names
Returns the list of names on success
Returns {'error': ...} on error
"""
assert proxy or hostport, 'Need proxy or hostport'
if proxy is None:
proxy = connect_hostp... | def function[get_all_names_page, parameter[offset, count, include_expired, hostport, proxy]]:
constant[
get a page of all the names
Returns the list of names on success
Returns {'error': ...} on error
]
assert[<ast.BoolOp object at 0x7da18bc71870>]
if compare[name[proxy] is constant[... | keyword[def] identifier[get_all_names_page] ( identifier[offset] , identifier[count] , identifier[include_expired] = keyword[False] , identifier[hostport] = keyword[None] , identifier[proxy] = keyword[None] ):
literal[string]
keyword[assert] identifier[proxy] keyword[or] identifier[hostport] , literal[s... | def get_all_names_page(offset, count, include_expired=False, hostport=None, proxy=None):
"""
get a page of all the names
Returns the list of names on success
Returns {'error': ...} on error
"""
assert proxy or hostport, 'Need proxy or hostport'
if proxy is None:
proxy = connect_hostp... |
def from_directory(input_dir):
"""
Read in a set of FEFF input files from a directory, which is
useful when existing FEFF input needs some adjustment.
"""
sub_d = {}
for fname, ftype in [("HEADER", Header), ("PARAMETERS", Tags)]:
fullzpath = zpath(os.path.join... | def function[from_directory, parameter[input_dir]]:
constant[
Read in a set of FEFF input files from a directory, which is
useful when existing FEFF input needs some adjustment.
]
variable[sub_d] assign[=] dictionary[[], []]
for taget[tuple[[<ast.Name object at 0x7da20c99... | keyword[def] identifier[from_directory] ( identifier[input_dir] ):
literal[string]
identifier[sub_d] ={}
keyword[for] identifier[fname] , identifier[ftype] keyword[in] [( literal[string] , identifier[Header] ),( literal[string] , identifier[Tags] )]:
identifier[fullzpath] = ... | def from_directory(input_dir):
"""
Read in a set of FEFF input files from a directory, which is
useful when existing FEFF input needs some adjustment.
"""
sub_d = {}
for (fname, ftype) in [('HEADER', Header), ('PARAMETERS', Tags)]:
fullzpath = zpath(os.path.join(input_dir, fn... |
def _get_cn_cert():
"""Get the public TLS/SSL X.509 certificate from the root CN of the DataONE
environment. The certificate is used for validating the signature of the JWTs.
If certificate retrieval fails, a new attempt to retrieve the certificate
is performed after the cache expires (settings.CACHES.... | def function[_get_cn_cert, parameter[]]:
constant[Get the public TLS/SSL X.509 certificate from the root CN of the DataONE
environment. The certificate is used for validating the signature of the JWTs.
If certificate retrieval fails, a new attempt to retrieve the certificate
is performed after the ... | keyword[def] identifier[_get_cn_cert] ():
literal[string]
keyword[try] :
identifier[cert_obj] = identifier[django] . identifier[core] . identifier[cache] . identifier[cache] . identifier[cn_cert_obj]
identifier[d1_common] . identifier[cert] . identifier[x509] . identifier[log_cert_info] ... | def _get_cn_cert():
"""Get the public TLS/SSL X.509 certificate from the root CN of the DataONE
environment. The certificate is used for validating the signature of the JWTs.
If certificate retrieval fails, a new attempt to retrieve the certificate
is performed after the cache expires (settings.CACHES.... |
def _head_temp_file(self, temp_file, num_lines):
""" Returns a list of the first num_lines lines from a temp file. """
if not isinstance(num_lines, int):
raise DagobahError('num_lines must be an integer')
temp_file.seek(0)
result, curr_line = [], 0
for line in temp_fi... | def function[_head_temp_file, parameter[self, temp_file, num_lines]]:
constant[ Returns a list of the first num_lines lines from a temp file. ]
if <ast.UnaryOp object at 0x7da1b0be1ed0> begin[:]
<ast.Raise object at 0x7da1b0be0df0>
call[name[temp_file].seek, parameter[constant[0]]]
... | keyword[def] identifier[_head_temp_file] ( identifier[self] , identifier[temp_file] , identifier[num_lines] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[num_lines] , identifier[int] ):
keyword[raise] identifier[DagobahError] ( literal[string] )
... | def _head_temp_file(self, temp_file, num_lines):
""" Returns a list of the first num_lines lines from a temp file. """
if not isinstance(num_lines, int):
raise DagobahError('num_lines must be an integer') # depends on [control=['if'], data=[]]
temp_file.seek(0)
(result, curr_line) = ([], 0)
... |
def get_lyrics_letssingit(song_name):
'''
Scrapes the lyrics of a song since spotify does not provide lyrics
takes song title as arguement
'''
lyrics = ""
url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \
quote(song_name.encode('utf-8'))
html =... | def function[get_lyrics_letssingit, parameter[song_name]]:
constant[
Scrapes the lyrics of a song since spotify does not provide lyrics
takes song title as arguement
]
variable[lyrics] assign[=] constant[]
variable[url] assign[=] binary_operation[constant[http://search.letssingit.com... | keyword[def] identifier[get_lyrics_letssingit] ( identifier[song_name] ):
literal[string]
identifier[lyrics] = literal[string]
identifier[url] = literal[string] + identifier[quote] ( identifier[song_name] . identifier[encode] ( literal[string] ))
identifier[html] = identifier[urlopen] ( identif... | def get_lyrics_letssingit(song_name):
"""
Scrapes the lyrics of a song since spotify does not provide lyrics
takes song title as arguement
"""
lyrics = ''
url = 'http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=' + quote(song_name.encode('utf-8'))
html = urlopen(ur... |
def updateDataset(self):
"""Updates the dataset."""
self.__updateDataItem()
self.__countNbRecords()
self.__columns = self.__parseColumns() | def function[updateDataset, parameter[self]]:
constant[Updates the dataset.]
call[name[self].__updateDataItem, parameter[]]
call[name[self].__countNbRecords, parameter[]]
name[self].__columns assign[=] call[name[self].__parseColumns, parameter[]] | keyword[def] identifier[updateDataset] ( identifier[self] ):
literal[string]
identifier[self] . identifier[__updateDataItem] ()
identifier[self] . identifier[__countNbRecords] ()
identifier[self] . identifier[__columns] = identifier[self] . identifier[__parseColumns] () | def updateDataset(self):
"""Updates the dataset."""
self.__updateDataItem()
self.__countNbRecords()
self.__columns = self.__parseColumns() |
def read_wavefront(fname_obj):
"""Returns mesh dictionary along with their material dictionary from a wavefront (.obj and/or .mtl) file."""
fname_mtl = ''
geoms = read_objfile(fname_obj)
for line in open(fname_obj):
if line:
split_line = line.strip().split(' ', 1)
if len(... | def function[read_wavefront, parameter[fname_obj]]:
constant[Returns mesh dictionary along with their material dictionary from a wavefront (.obj and/or .mtl) file.]
variable[fname_mtl] assign[=] constant[]
variable[geoms] assign[=] call[name[read_objfile], parameter[name[fname_obj]]]
for... | keyword[def] identifier[read_wavefront] ( identifier[fname_obj] ):
literal[string]
identifier[fname_mtl] = literal[string]
identifier[geoms] = identifier[read_objfile] ( identifier[fname_obj] )
keyword[for] identifier[line] keyword[in] identifier[open] ( identifier[fname_obj] ):
keyw... | def read_wavefront(fname_obj):
"""Returns mesh dictionary along with their material dictionary from a wavefront (.obj and/or .mtl) file."""
fname_mtl = ''
geoms = read_objfile(fname_obj)
for line in open(fname_obj):
if line:
split_line = line.strip().split(' ', 1)
if len(... |
def gets(self, conn, key, default=None):
"""Gets a single value from the server together with the cas token.
:param key: ``bytes``, is the key for the item being fetched
:param default: default value if there is no value.
:return: ``bytes``, ``bytes tuple with the value and the cas
... | def function[gets, parameter[self, conn, key, default]]:
constant[Gets a single value from the server together with the cas token.
:param key: ``bytes``, is the key for the item being fetched
:param default: default value if there is no value.
:return: ``bytes``, ``bytes tuple with the ... | keyword[def] identifier[gets] ( identifier[self] , identifier[conn] , identifier[key] , identifier[default] = keyword[None] ):
literal[string]
identifier[values] , identifier[cas_tokens] = keyword[yield] keyword[from] identifier[self] . identifier[_multi_get] (
identifier[conn] , identif... | def gets(self, conn, key, default=None):
"""Gets a single value from the server together with the cas token.
:param key: ``bytes``, is the key for the item being fetched
:param default: default value if there is no value.
:return: ``bytes``, ``bytes tuple with the value and the cas
... |
def _parse(self, stream, context, path):
"""Parse until the end of objects data."""
num_players = context._._._.replay.num_players
start = stream.tell()
# Have to read everything to be able to use find()
read_bytes = stream.read()
# Try to find the first marker, a portion... | def function[_parse, parameter[self, stream, context, path]]:
constant[Parse until the end of objects data.]
variable[num_players] assign[=] name[context]._._._.replay.num_players
variable[start] assign[=] call[name[stream].tell, parameter[]]
variable[read_bytes] assign[=] call[name[stre... | keyword[def] identifier[_parse] ( identifier[self] , identifier[stream] , identifier[context] , identifier[path] ):
literal[string]
identifier[num_players] = identifier[context] . identifier[_] . identifier[_] . identifier[_] . identifier[replay] . identifier[num_players]
identifier[start... | def _parse(self, stream, context, path):
"""Parse until the end of objects data."""
num_players = context._._._.replay.num_players
start = stream.tell()
# Have to read everything to be able to use find()
read_bytes = stream.read()
# Try to find the first marker, a portion of the next player stru... |
def create_connections(self, connection_map):
'''Create agent connections from a given connection map.
:param dict connection_map:
A map of connections to be created. Dictionary where keys are
agent addresses and values are lists of (addr, attitude)-tuples
suitable f... | def function[create_connections, parameter[self, connection_map]]:
constant[Create agent connections from a given connection map.
:param dict connection_map:
A map of connections to be created. Dictionary where keys are
agent addresses and values are lists of (addr, attitude)-tu... | keyword[def] identifier[create_connections] ( identifier[self] , identifier[connection_map] ):
literal[string]
identifier[agents] = identifier[self] . identifier[get_agents] ( identifier[addr] = keyword[False] )
identifier[rets] =[]
keyword[for] identifier[a] keyword[in] identi... | def create_connections(self, connection_map):
"""Create agent connections from a given connection map.
:param dict connection_map:
A map of connections to be created. Dictionary where keys are
agent addresses and values are lists of (addr, attitude)-tuples
suitable for
... |
def new_line(self, tokens, line_end, line_start):
"""a new line has been encountered, process it if necessary"""
if _last_token_on_line_is(tokens, line_end, ";"):
self.add_message("unnecessary-semicolon", line=tokens.start_line(line_end))
line_num = tokens.start_line(line_start)
... | def function[new_line, parameter[self, tokens, line_end, line_start]]:
constant[a new line has been encountered, process it if necessary]
if call[name[_last_token_on_line_is], parameter[name[tokens], name[line_end], constant[;]]] begin[:]
call[name[self].add_message, parameter[constant[u... | keyword[def] identifier[new_line] ( identifier[self] , identifier[tokens] , identifier[line_end] , identifier[line_start] ):
literal[string]
keyword[if] identifier[_last_token_on_line_is] ( identifier[tokens] , identifier[line_end] , literal[string] ):
identifier[self] . identifier[ad... | def new_line(self, tokens, line_end, line_start):
"""a new line has been encountered, process it if necessary"""
if _last_token_on_line_is(tokens, line_end, ';'):
self.add_message('unnecessary-semicolon', line=tokens.start_line(line_end)) # depends on [control=['if'], data=[]]
line_num = tokens.sta... |
def cmd_rally(self, args):
'''rally point commands'''
#TODO: add_land arg
if len(args) < 1:
self.print_usage()
return
elif args[0] == "add":
self.cmd_rally_add(args[1:])
elif args[0] == "move":
self.cmd_rally_move(args[1:])
... | def function[cmd_rally, parameter[self, args]]:
constant[rally point commands]
if compare[call[name[len], parameter[name[args]]] less[<] constant[1]] begin[:]
call[name[self].print_usage, parameter[]]
return[None] | keyword[def] identifier[cmd_rally] ( identifier[self] , identifier[args] ):
literal[string]
keyword[if] identifier[len] ( identifier[args] )< literal[int] :
identifier[self] . identifier[print_usage] ()
keyword[return]
keyword[elif] identifier[args] [... | def cmd_rally(self, args):
"""rally point commands"""
#TODO: add_land arg
if len(args) < 1:
self.print_usage()
return # depends on [control=['if'], data=[]]
elif args[0] == 'add':
self.cmd_rally_add(args[1:]) # depends on [control=['if'], data=[]]
elif args[0] == 'move':
... |
def reset_creation_info(self):
"""
Resets builder state to allow building new creation info."""
# FIXME: this state does not make sense
self.created_date_set = False
self.creation_comment_set = False
self.lics_list_ver_set = False | def function[reset_creation_info, parameter[self]]:
constant[
Resets builder state to allow building new creation info.]
name[self].created_date_set assign[=] constant[False]
name[self].creation_comment_set assign[=] constant[False]
name[self].lics_list_ver_set assign[=] constant... | keyword[def] identifier[reset_creation_info] ( identifier[self] ):
literal[string]
identifier[self] . identifier[created_date_set] = keyword[False]
identifier[self] . identifier[creation_comment_set] = keyword[False]
identifier[self] . identifier[lics_list_ver_set] = ke... | def reset_creation_info(self):
"""
Resets builder state to allow building new creation info."""
# FIXME: this state does not make sense
self.created_date_set = False
self.creation_comment_set = False
self.lics_list_ver_set = False |
def update(zone, name, ttl, rdtype, data, nameserver='127.0.0.1', timeout=5,
replace=False, port=53, **kwargs):
'''
Add, replace, or update a DNS record.
nameserver must be an IP address and the minion running this module
must have update privileges on that server.
If replace is true, fir... | def function[update, parameter[zone, name, ttl, rdtype, data, nameserver, timeout, replace, port]]:
constant[
Add, replace, or update a DNS record.
nameserver must be an IP address and the minion running this module
must have update privileges on that server.
If replace is true, first deletes al... | keyword[def] identifier[update] ( identifier[zone] , identifier[name] , identifier[ttl] , identifier[rdtype] , identifier[data] , identifier[nameserver] = literal[string] , identifier[timeout] = literal[int] ,
identifier[replace] = keyword[False] , identifier[port] = literal[int] ,** identifier[kwargs] ):
liter... | def update(zone, name, ttl, rdtype, data, nameserver='127.0.0.1', timeout=5, replace=False, port=53, **kwargs):
"""
Add, replace, or update a DNS record.
nameserver must be an IP address and the minion running this module
must have update privileges on that server.
If replace is true, first deletes ... |
def format_output(groups, flag):
"""return formatted string for instance"""
out = []
line_format = '{0}\t{1}\t{2}\t{3}\t{4}\t{5}'
for g in groups['AutoScalingGroups']:
out.append(line_format.format(
g['AutoScalingGroupName'],
g['LaunchConfigurationName'],
'des... | def function[format_output, parameter[groups, flag]]:
constant[return formatted string for instance]
variable[out] assign[=] list[[]]
variable[line_format] assign[=] constant[{0} {1} {2} {3} {4} {5}]
for taget[name[g]] in starred[call[name[groups]][constant[AutoScalingGroups]]] begin[:]
... | keyword[def] identifier[format_output] ( identifier[groups] , identifier[flag] ):
literal[string]
identifier[out] =[]
identifier[line_format] = literal[string]
keyword[for] identifier[g] keyword[in] identifier[groups] [ literal[string] ]:
identifier[out] . identifier[append] ( identi... | def format_output(groups, flag):
"""return formatted string for instance"""
out = []
line_format = '{0}\t{1}\t{2}\t{3}\t{4}\t{5}'
for g in groups['AutoScalingGroups']:
out.append(line_format.format(g['AutoScalingGroupName'], g['LaunchConfigurationName'], 'desired:' + str(g['DesiredCapacity']), '... |
def from_export(cls, endpoint):
# type: (ExportEndpoint) -> EndpointDescription
"""
Converts an ExportEndpoint bean to an EndpointDescription
:param endpoint: An ExportEndpoint bean
:return: An EndpointDescription bean
"""
assert isinstance(endpoint, ExportEndpoi... | def function[from_export, parameter[cls, endpoint]]:
constant[
Converts an ExportEndpoint bean to an EndpointDescription
:param endpoint: An ExportEndpoint bean
:return: An EndpointDescription bean
]
assert[call[name[isinstance], parameter[name[endpoint], name[ExportEndpoint... | keyword[def] identifier[from_export] ( identifier[cls] , identifier[endpoint] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[endpoint] , identifier[ExportEndpoint] )
identifier[properties] = identifier[endpoint] . identifier[get_properties] ()
... | def from_export(cls, endpoint):
# type: (ExportEndpoint) -> EndpointDescription
'\n Converts an ExportEndpoint bean to an EndpointDescription\n\n :param endpoint: An ExportEndpoint bean\n :return: An EndpointDescription bean\n '
assert isinstance(endpoint, ExportEndpoint)
# S... |
def apply_transformations(collection, transformations, select=None):
''' Apply all transformations to the variables in the collection.
Args:
transformations (list): List of transformations to apply.
select (list): Optional list of names of variables to retain after all
transformatio... | def function[apply_transformations, parameter[collection, transformations, select]]:
constant[ Apply all transformations to the variables in the collection.
Args:
transformations (list): List of transformations to apply.
select (list): Optional list of names of variables to retain after all... | keyword[def] identifier[apply_transformations] ( identifier[collection] , identifier[transformations] , identifier[select] = keyword[None] ):
literal[string]
keyword[for] identifier[t] keyword[in] identifier[transformations] :
identifier[kwargs] = identifier[dict] ( identifier[t] )
ide... | def apply_transformations(collection, transformations, select=None):
""" Apply all transformations to the variables in the collection.
Args:
transformations (list): List of transformations to apply.
select (list): Optional list of names of variables to retain after all
transformatio... |
def handler_for_name(fq_name):
"""Resolves and instantiates handler by fully qualified name.
First resolves the name using for_name call. Then if it resolves to a class,
instantiates a class, if it resolves to a method - instantiates the class and
binds method to the instance.
Args:
fq_name: fully quali... | def function[handler_for_name, parameter[fq_name]]:
constant[Resolves and instantiates handler by fully qualified name.
First resolves the name using for_name call. Then if it resolves to a class,
instantiates a class, if it resolves to a method - instantiates the class and
binds method to the instance.
... | keyword[def] identifier[handler_for_name] ( identifier[fq_name] ):
literal[string]
identifier[resolved_name] = identifier[for_name] ( identifier[fq_name] )
keyword[if] identifier[isinstance] ( identifier[resolved_name] ,( identifier[type] , identifier[types] . identifier[ClassType] )):
keyword[retu... | def handler_for_name(fq_name):
"""Resolves and instantiates handler by fully qualified name.
First resolves the name using for_name call. Then if it resolves to a class,
instantiates a class, if it resolves to a method - instantiates the class and
binds method to the instance.
Args:
fq_name: fully qua... |
def get_module_environment(env=None, function=None):
'''
Get module optional environment.
To setup an environment option for a particular module,
add either pillar or config at the minion as follows:
system-environment:
modules:
pkg:
_:
LC_ALL: en_GB.UTF-8
... | def function[get_module_environment, parameter[env, function]]:
constant[
Get module optional environment.
To setup an environment option for a particular module,
add either pillar or config at the minion as follows:
system-environment:
modules:
pkg:
_:
LC_A... | keyword[def] identifier[get_module_environment] ( identifier[env] = keyword[None] , identifier[function] = keyword[None] ):
literal[string]
identifier[result] ={}
keyword[if] keyword[not] identifier[env] :
identifier[env] ={}
keyword[for] identifier[env_src] keyword[in] [ identifier[... | def get_module_environment(env=None, function=None):
"""
Get module optional environment.
To setup an environment option for a particular module,
add either pillar or config at the minion as follows:
system-environment:
modules:
pkg:
_:
LC_ALL: en_GB.UTF-8
... |
def find_city(self, city, state=None, best_match=True, min_similarity=70):
"""
Fuzzy search correct city.
:param city: city name.
:param state: search city in specified state.
:param best_match: bool, when True, only the best matched city
will return. otherwise, will... | def function[find_city, parameter[self, city, state, best_match, min_similarity]]:
constant[
Fuzzy search correct city.
:param city: city name.
:param state: search city in specified state.
:param best_match: bool, when True, only the best matched city
will return. o... | keyword[def] identifier[find_city] ( identifier[self] , identifier[city] , identifier[state] = keyword[None] , identifier[best_match] = keyword[True] , identifier[min_similarity] = literal[int] ):
literal[string]
keyword[if] identifier[state] :
identifier[state_sort] = identi... | def find_city(self, city, state=None, best_match=True, min_similarity=70):
"""
Fuzzy search correct city.
:param city: city name.
:param state: search city in specified state.
:param best_match: bool, when True, only the best matched city
will return. otherwise, will ret... |
def get(self, hostport):
"""Get a Peer for the given destination.
A new Peer is added to the peer heap and returned if one does
not already exist for the given host-port. Otherwise, the
existing Peer is returned.
"""
assert hostport, "hostport is required"
assert... | def function[get, parameter[self, hostport]]:
constant[Get a Peer for the given destination.
A new Peer is added to the peer heap and returned if one does
not already exist for the given host-port. Otherwise, the
existing Peer is returned.
]
assert[name[hostport]]
assert... | keyword[def] identifier[get] ( identifier[self] , identifier[hostport] ):
literal[string]
keyword[assert] identifier[hostport] , literal[string]
keyword[assert] identifier[isinstance] ( identifier[hostport] , identifier[basestring] ), literal[string]
keyword[if] identifier[h... | def get(self, hostport):
"""Get a Peer for the given destination.
A new Peer is added to the peer heap and returned if one does
not already exist for the given host-port. Otherwise, the
existing Peer is returned.
"""
assert hostport, 'hostport is required'
assert isinstance(... |
def _make_clusters(self, matrix, num_clusters_per_roi, metric):
"""clusters a given matrix by into specified number of clusters according to given metric"""
from scipy.cluster.hierarchy import fclusterdata
# maxclust needed to ensure t is interpreted as # clusters in heirarchical clustering
... | def function[_make_clusters, parameter[self, matrix, num_clusters_per_roi, metric]]:
constant[clusters a given matrix by into specified number of clusters according to given metric]
from relative_module[scipy.cluster.hierarchy] import module[fclusterdata]
variable[group_ids] assign[=] call[name[fclu... | keyword[def] identifier[_make_clusters] ( identifier[self] , identifier[matrix] , identifier[num_clusters_per_roi] , identifier[metric] ):
literal[string]
keyword[from] identifier[scipy] . identifier[cluster] . identifier[hierarchy] keyword[import] identifier[fclusterdata]
i... | def _make_clusters(self, matrix, num_clusters_per_roi, metric):
"""clusters a given matrix by into specified number of clusters according to given metric"""
from scipy.cluster.hierarchy import fclusterdata
# maxclust needed to ensure t is interpreted as # clusters in heirarchical clustering
group_ids = ... |
def _next_token(sql):
""" This is a basic tokenizer for our limited purposes.
It splits a SQL statement up into a series of segments, where a segment is one of:
- identifiers
- left or right parentheses
- multi-line comments
- single line comments
- white-space sequences
- string literals
- consecutiv... | def function[_next_token, parameter[sql]]:
constant[ This is a basic tokenizer for our limited purposes.
It splits a SQL statement up into a series of segments, where a segment is one of:
- identifiers
- left or right parentheses
- multi-line comments
- single line comments
- white-space sequences
... | keyword[def] identifier[_next_token] ( identifier[sql] ):
literal[string]
identifier[i] = literal[int]
keyword[def] identifier[start_multi_line_comment] ( identifier[s] , identifier[i] ):
keyword[return] identifier[s] [ identifier[i] ]== literal[string] keyword[and] ident... | def _next_token(sql):
""" This is a basic tokenizer for our limited purposes.
It splits a SQL statement up into a series of segments, where a segment is one of:
- identifiers
- left or right parentheses
- multi-line comments
- single line comments
- white-space sequences
- string literals
- consecut... |
def interpolate(self, method='linear', axis=0, limit=None, inplace=False,
limit_direction='forward', limit_area=None,
downcast=None, **kwargs):
"""
Interpolate values according to different methods.
.. versionadded:: 0.18.1
"""
result = se... | def function[interpolate, parameter[self, method, axis, limit, inplace, limit_direction, limit_area, downcast]]:
constant[
Interpolate values according to different methods.
.. versionadded:: 0.18.1
]
variable[result] assign[=] call[name[self]._upsample, parameter[constant[None]... | keyword[def] identifier[interpolate] ( identifier[self] , identifier[method] = literal[string] , identifier[axis] = literal[int] , identifier[limit] = keyword[None] , identifier[inplace] = keyword[False] ,
identifier[limit_direction] = literal[string] , identifier[limit_area] = keyword[None] ,
identifier[downcast] ... | def interpolate(self, method='linear', axis=0, limit=None, inplace=False, limit_direction='forward', limit_area=None, downcast=None, **kwargs):
"""
Interpolate values according to different methods.
.. versionadded:: 0.18.1
"""
result = self._upsample(None)
return result.interpolate... |
def generate_view_data(self):
"""Generate the views."""
self.view_data['version'] = '{} {}'.format('Glances', __version__)
self.view_data['psutil_version'] = ' with psutil {}'.format(psutil_version)
try:
self.view_data['configuration_file'] = 'Configuration file: {}'.format(... | def function[generate_view_data, parameter[self]]:
constant[Generate the views.]
call[name[self].view_data][constant[version]] assign[=] call[constant[{} {}].format, parameter[constant[Glances], name[__version__]]]
call[name[self].view_data][constant[psutil_version]] assign[=] call[constant[ wit... | keyword[def] identifier[generate_view_data] ( identifier[self] ):
literal[string]
identifier[self] . identifier[view_data] [ literal[string] ]= literal[string] . identifier[format] ( literal[string] , identifier[__version__] )
identifier[self] . identifier[view_data] [ literal[string] ]= l... | def generate_view_data(self):
"""Generate the views."""
self.view_data['version'] = '{} {}'.format('Glances', __version__)
self.view_data['psutil_version'] = ' with psutil {}'.format(psutil_version)
try:
self.view_data['configuration_file'] = 'Configuration file: {}'.format(self.config.loaded_co... |
def _hm_send_msg(self, message):
"""This is the only interface to the serial connection."""
try:
serial_message = message
self.conn.write(serial_message) # Write a string
except serial.SerialTimeoutException:
serror = "Write timeout error: \n"
... | def function[_hm_send_msg, parameter[self, message]]:
constant[This is the only interface to the serial connection.]
<ast.Try object at 0x7da18eb54c70>
variable[byteread] assign[=] call[name[self].conn.read, parameter[constant[159]]]
variable[datal] assign[=] call[name[list], parameter[name[... | keyword[def] identifier[_hm_send_msg] ( identifier[self] , identifier[message] ):
literal[string]
keyword[try] :
identifier[serial_message] = identifier[message]
identifier[self] . identifier[conn] . identifier[write] ( identifier[serial_message] )
keyword[e... | def _hm_send_msg(self, message):
"""This is the only interface to the serial connection."""
try:
serial_message = message
self.conn.write(serial_message) # Write a string # depends on [control=['try'], data=[]]
except serial.SerialTimeoutException:
serror = 'Write timeout error: \n... |
def filter_instance(self, inst, plist):
"""Remove properties from an instance that aren't in the PropertyList
inst -- The pywbem.CIMInstance
plist -- The property List, or None. The list items must be all
lowercase.
"""
if plist is not None:
for pname ... | def function[filter_instance, parameter[self, inst, plist]]:
constant[Remove properties from an instance that aren't in the PropertyList
inst -- The pywbem.CIMInstance
plist -- The property List, or None. The list items must be all
lowercase.
]
if compare[name[plis... | keyword[def] identifier[filter_instance] ( identifier[self] , identifier[inst] , identifier[plist] ):
literal[string]
keyword[if] identifier[plist] keyword[is] keyword[not] keyword[None] :
keyword[for] identifier[pname] keyword[in] identifier[inst] . identifier[properties] . id... | def filter_instance(self, inst, plist):
"""Remove properties from an instance that aren't in the PropertyList
inst -- The pywbem.CIMInstance
plist -- The property List, or None. The list items must be all
lowercase.
"""
if plist is not None:
for pname in inst.prope... |
def relpath(self, path, start=None):
"""We mostly rely on the native implementation and adapt the
path separator."""
if not path:
raise ValueError("no path specified")
path = make_string_path(path)
if start is not None:
start = make_string_path(start)
... | def function[relpath, parameter[self, path, start]]:
constant[We mostly rely on the native implementation and adapt the
path separator.]
if <ast.UnaryOp object at 0x7da2047ea740> begin[:]
<ast.Raise object at 0x7da2047ea770>
variable[path] assign[=] call[name[make_string_path], p... | keyword[def] identifier[relpath] ( identifier[self] , identifier[path] , identifier[start] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[path] :
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[path] = identifier[make_string_path... | def relpath(self, path, start=None):
"""We mostly rely on the native implementation and adapt the
path separator."""
if not path:
raise ValueError('no path specified') # depends on [control=['if'], data=[]]
path = make_string_path(path)
if start is not None:
start = make_string_... |
def reg_on_abort(self, callable_object, *args, **kwargs):
""" Register a function/method to be called when execution is aborted"""
persistent = kwargs.pop('persistent', False)
event = self._create_event(callable_object, 'abort', persistent, *args, **kwargs)
self.abort_callbacks.append(ev... | def function[reg_on_abort, parameter[self, callable_object]]:
constant[ Register a function/method to be called when execution is aborted]
variable[persistent] assign[=] call[name[kwargs].pop, parameter[constant[persistent], constant[False]]]
variable[event] assign[=] call[name[self]._create_eve... | keyword[def] identifier[reg_on_abort] ( identifier[self] , identifier[callable_object] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[persistent] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[False] )
identifier[event] = identifier[self] . ide... | def reg_on_abort(self, callable_object, *args, **kwargs):
""" Register a function/method to be called when execution is aborted"""
persistent = kwargs.pop('persistent', False)
event = self._create_event(callable_object, 'abort', persistent, *args, **kwargs)
self.abort_callbacks.append(event)
return ... |
def cluster_sample5():
"Start with wrong number of clusters."
start_centers = [[0.0, 1.0], [0.0, 0.0]]
template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_SIMPLE5, criterion = splitting_type.BAYESIAN_INFORMATION_CRITERION)
template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_SIMPLE5, criter... | def function[cluster_sample5, parameter[]]:
constant[Start with wrong number of clusters.]
variable[start_centers] assign[=] list[[<ast.List object at 0x7da18ede4ac0>, <ast.List object at 0x7da1b01d9420>]]
call[name[template_clustering], parameter[name[start_centers], name[SIMPLE_SAMPLES].SAMPLE... | keyword[def] identifier[cluster_sample5] ():
literal[string]
identifier[start_centers] =[[ literal[int] , literal[int] ],[ literal[int] , literal[int] ]]
identifier[template_clustering] ( identifier[start_centers] , identifier[SIMPLE_SAMPLES] . identifier[SAMPLE_SIMPLE5] , identifier[criterion] = i... | def cluster_sample5():
"""Start with wrong number of clusters."""
start_centers = [[0.0, 1.0], [0.0, 0.0]]
template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_SIMPLE5, criterion=splitting_type.BAYESIAN_INFORMATION_CRITERION)
template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_SIMPLE5, criterio... |
def _get_vqa_v2_image_feature_dataset(
directory, feature_url, feature_filename="mscoco_feat.tar.gz"):
"""Extract the VQA V2 feature data set to directory unless it's there."""
feature_file = generator_utils.maybe_download_from_drive(
directory, feature_filename, feature_url)
with tarfile.open(feature_f... | def function[_get_vqa_v2_image_feature_dataset, parameter[directory, feature_url, feature_filename]]:
constant[Extract the VQA V2 feature data set to directory unless it's there.]
variable[feature_file] assign[=] call[name[generator_utils].maybe_download_from_drive, parameter[name[directory], name[featu... | keyword[def] identifier[_get_vqa_v2_image_feature_dataset] (
identifier[directory] , identifier[feature_url] , identifier[feature_filename] = literal[string] ):
literal[string]
identifier[feature_file] = identifier[generator_utils] . identifier[maybe_download_from_drive] (
identifier[directory] , identifie... | def _get_vqa_v2_image_feature_dataset(directory, feature_url, feature_filename='mscoco_feat.tar.gz'):
"""Extract the VQA V2 feature data set to directory unless it's there."""
feature_file = generator_utils.maybe_download_from_drive(directory, feature_filename, feature_url)
with tarfile.open(feature_file, '... |
def tweet_list_handler(request, tweet_list_builder, msg_prefix=""):
""" This is a generic function to handle any intent that reads out a list of tweets"""
# tweet_list_builder is a function that takes a unique identifier and returns a list of things to say
tweets = tweet_list_builder(request.access_token()... | def function[tweet_list_handler, parameter[request, tweet_list_builder, msg_prefix]]:
constant[ This is a generic function to handle any intent that reads out a list of tweets]
variable[tweets] assign[=] call[name[tweet_list_builder], parameter[call[name[request].access_token, parameter[]]]]
cal... | keyword[def] identifier[tweet_list_handler] ( identifier[request] , identifier[tweet_list_builder] , identifier[msg_prefix] = literal[string] ):
literal[string]
identifier[tweets] = identifier[tweet_list_builder] ( identifier[request] . identifier[access_token] ())
identifier[print] ( identifier... | def tweet_list_handler(request, tweet_list_builder, msg_prefix=''):
""" This is a generic function to handle any intent that reads out a list of tweets"""
# tweet_list_builder is a function that takes a unique identifier and returns a list of things to say
tweets = tweet_list_builder(request.access_token())... |
def or_(cls, *queries):
"""
根据传入的 Query 对象,构造一个新的 OR 查询。
:param queries: 需要构造的子查询列表
:rtype: Query
"""
if len(queries) < 2:
raise ValueError('or_ need two queries at least')
if not all(x._query_class._class_name == queries[0]._query_class._class_name f... | def function[or_, parameter[cls]]:
constant[
根据传入的 Query 对象,构造一个新的 OR 查询。
:param queries: 需要构造的子查询列表
:rtype: Query
]
if compare[call[name[len], parameter[name[queries]]] less[<] constant[2]] begin[:]
<ast.Raise object at 0x7da1b0ef9c30>
if <ast.UnaryOp ob... | keyword[def] identifier[or_] ( identifier[cls] ,* identifier[queries] ):
literal[string]
keyword[if] identifier[len] ( identifier[queries] )< literal[int] :
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[if] keyword[not] identifier[all] ( identifier[x] .... | def or_(cls, *queries):
"""
根据传入的 Query 对象,构造一个新的 OR 查询。
:param queries: 需要构造的子查询列表
:rtype: Query
"""
if len(queries) < 2:
raise ValueError('or_ need two queries at least') # depends on [control=['if'], data=[]]
if not all((x._query_class._class_name == queries[0]._... |
def stop_conditions(self, G, E, I, known_winners, stats):
"""
Determines if G, E state can be ended early
:param G: networkx DiGraph of the current representation of "locked in" edges in RP
:param E: networkx DiGraph of the remaining edges not yet considered
:param I: list of all... | def function[stop_conditions, parameter[self, G, E, I, known_winners, stats]]:
constant[
Determines if G, E state can be ended early
:param G: networkx DiGraph of the current representation of "locked in" edges in RP
:param E: networkx DiGraph of the remaining edges not yet considered
... | keyword[def] identifier[stop_conditions] ( identifier[self] , identifier[G] , identifier[E] , identifier[I] , identifier[known_winners] , identifier[stats] ):
literal[string]
identifier[in_deg] = identifier[G] . identifier[in_degree] ( identifier[I] )
identifier[possible_winners] =[ ident... | def stop_conditions(self, G, E, I, known_winners, stats):
"""
Determines if G, E state can be ended early
:param G: networkx DiGraph of the current representation of "locked in" edges in RP
:param E: networkx DiGraph of the remaining edges not yet considered
:param I: list of all nod... |
def identifiers(self, identifiers):
"""
:type identifiers: subject_abcs.IdentifierCollection
"""
if (isinstance(identifiers, subject_abcs.IdentifierCollection) or
identifiers is None):
self._identifiers = identifiers
else:
raise ValueError... | def function[identifiers, parameter[self, identifiers]]:
constant[
:type identifiers: subject_abcs.IdentifierCollection
]
if <ast.BoolOp object at 0x7da20c76c1c0> begin[:]
name[self]._identifiers assign[=] name[identifiers] | keyword[def] identifier[identifiers] ( identifier[self] , identifier[identifiers] ):
literal[string]
keyword[if] ( identifier[isinstance] ( identifier[identifiers] , identifier[subject_abcs] . identifier[IdentifierCollection] ) keyword[or]
identifier[identifiers] keyword[is] keyword[Non... | def identifiers(self, identifiers):
"""
:type identifiers: subject_abcs.IdentifierCollection
"""
if isinstance(identifiers, subject_abcs.IdentifierCollection) or identifiers is None:
self._identifiers = identifiers # depends on [control=['if'], data=[]]
else:
raise ValueErr... |
def join(self, network):
"""
Join a zerotier network
:param network: network id to join
:return:
"""
args = {'network': network}
self._network_chk.check(args)
response = self._client.raw('zerotier.join', args)
result = response.get()
if r... | def function[join, parameter[self, network]]:
constant[
Join a zerotier network
:param network: network id to join
:return:
]
variable[args] assign[=] dictionary[[<ast.Constant object at 0x7da1b04c88e0>], [<ast.Name object at 0x7da1b04c95d0>]]
call[name[self]._ne... | keyword[def] identifier[join] ( identifier[self] , identifier[network] ):
literal[string]
identifier[args] ={ literal[string] : identifier[network] }
identifier[self] . identifier[_network_chk] . identifier[check] ( identifier[args] )
identifier[response] = identifier[self] . iden... | def join(self, network):
"""
Join a zerotier network
:param network: network id to join
:return:
"""
args = {'network': network}
self._network_chk.check(args)
response = self._client.raw('zerotier.join', args)
result = response.get()
if result.state != 'SUCCESS':... |
def set_pubsub_channels(self, request, channels):
"""
Initialize the channels used for publishing and subscribing messages through the message queue.
"""
facility = request.path_info.replace(settings.WEBSOCKET_URL, '', 1)
# initialize publishers
audience = {
... | def function[set_pubsub_channels, parameter[self, request, channels]]:
constant[
Initialize the channels used for publishing and subscribing messages through the message queue.
]
variable[facility] assign[=] call[name[request].path_info.replace, parameter[name[settings].WEBSOCKET_URL, co... | keyword[def] identifier[set_pubsub_channels] ( identifier[self] , identifier[request] , identifier[channels] ):
literal[string]
identifier[facility] = identifier[request] . identifier[path_info] . identifier[replace] ( identifier[settings] . identifier[WEBSOCKET_URL] , literal[string] , literal[int... | def set_pubsub_channels(self, request, channels):
"""
Initialize the channels used for publishing and subscribing messages through the message queue.
"""
facility = request.path_info.replace(settings.WEBSOCKET_URL, '', 1)
# initialize publishers
audience = {'users': 'publish-user' in cha... |
def showBeamlines(self):
""" show all defined beamlines
"""
cnt = 0
blidlist = []
for k in self.all_elements:
try:
if 'beamline' in self.all_elements.get(k):
cnt += 1
blidlist.append(k)
except:
... | def function[showBeamlines, parameter[self]]:
constant[ show all defined beamlines
]
variable[cnt] assign[=] constant[0]
variable[blidlist] assign[=] list[[]]
for taget[name[k]] in starred[name[self].all_elements] begin[:]
<ast.Try object at 0x7da1b09bf0a0>
variab... | keyword[def] identifier[showBeamlines] ( identifier[self] ):
literal[string]
identifier[cnt] = literal[int]
identifier[blidlist] =[]
keyword[for] identifier[k] keyword[in] identifier[self] . identifier[all_elements] :
keyword[try] :
keyword[if] l... | def showBeamlines(self):
""" show all defined beamlines
"""
cnt = 0
blidlist = []
for k in self.all_elements:
try:
if 'beamline' in self.all_elements.get(k):
cnt += 1
blidlist.append(k) # depends on [control=['if'], data=[]] # depends on [con... |
def patch_worker_run_task():
"""
Patches the ``luigi.worker.Worker._run_task`` method to store the worker id and the id of its
first task in the task. This information is required by the sandboxing mechanism
"""
_run_task = luigi.worker.Worker._run_task
def run_task(self, task_id):
task... | def function[patch_worker_run_task, parameter[]]:
constant[
Patches the ``luigi.worker.Worker._run_task`` method to store the worker id and the id of its
first task in the task. This information is required by the sandboxing mechanism
]
variable[_run_task] assign[=] name[luigi].worker.Worker... | keyword[def] identifier[patch_worker_run_task] ():
literal[string]
identifier[_run_task] = identifier[luigi] . identifier[worker] . identifier[Worker] . identifier[_run_task]
keyword[def] identifier[run_task] ( identifier[self] , identifier[task_id] ):
identifier[task] = identifier[self] .... | def patch_worker_run_task():
"""
Patches the ``luigi.worker.Worker._run_task`` method to store the worker id and the id of its
first task in the task. This information is required by the sandboxing mechanism
"""
_run_task = luigi.worker.Worker._run_task
def run_task(self, task_id):
task... |
def _words_by_distinctiveness_score(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n=None,
least_to_most=False):
"""Return words in `vocab` ordered by distinctiveness score."""
p_t = get_marginal_topic_distrib(doc_topic_distrib, doc_lengths)
distinct = get_wor... | def function[_words_by_distinctiveness_score, parameter[vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n, least_to_most]]:
constant[Return words in `vocab` ordered by distinctiveness score.]
variable[p_t] assign[=] call[name[get_marginal_topic_distrib], parameter[name[doc_topic_distrib], nam... | keyword[def] identifier[_words_by_distinctiveness_score] ( identifier[vocab] , identifier[topic_word_distrib] , identifier[doc_topic_distrib] , identifier[doc_lengths] , identifier[n] = keyword[None] ,
identifier[least_to_most] = keyword[False] ):
literal[string]
identifier[p_t] = identifier[get_marginal_... | def _words_by_distinctiveness_score(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n=None, least_to_most=False):
"""Return words in `vocab` ordered by distinctiveness score."""
p_t = get_marginal_topic_distrib(doc_topic_distrib, doc_lengths)
distinct = get_word_distinctiveness(topic_word_distrib... |
def init(req, model): # pylint: disable=unused-argument
""" Determine the pagination preference by query parameter
Numbers only, >=0, & each query param may only be
specified once.
:return: Paginator object
"""
limit = req.get_param('page[limit]') or goldman.config.PAGE_LIMIT
offset = re... | def function[init, parameter[req, model]]:
constant[ Determine the pagination preference by query parameter
Numbers only, >=0, & each query param may only be
specified once.
:return: Paginator object
]
variable[limit] assign[=] <ast.BoolOp object at 0x7da204960070>
variable[off... | keyword[def] identifier[init] ( identifier[req] , identifier[model] ):
literal[string]
identifier[limit] = identifier[req] . identifier[get_param] ( literal[string] ) keyword[or] identifier[goldman] . identifier[config] . identifier[PAGE_LIMIT]
identifier[offset] = identifier[req] . identifier[get_... | def init(req, model): # pylint: disable=unused-argument
' Determine the pagination preference by query parameter\n\n Numbers only, >=0, & each query param may only be\n specified once.\n\n :return: Paginator object\n '
limit = req.get_param('page[limit]') or goldman.config.PAGE_LIMIT
offset = r... |
def string_escape(string, delimiter='"'):
"""Turns special characters into escape sequences in the provided string.
Supports both byte strings and unicode strings properly. Any other values
will produce None.
Example:
>>> string_escape("a line\t")
"a line\\t"
>>> string_escape(u"some fancy... | def function[string_escape, parameter[string, delimiter]]:
constant[Turns special characters into escape sequences in the provided string.
Supports both byte strings and unicode strings properly. Any other values
will produce None.
Example:
>>> string_escape("a line ")
"a line\t"
>>> s... | keyword[def] identifier[string_escape] ( identifier[string] , identifier[delimiter] = literal[string] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[string] , identifier[str] ):
identifier[escaped] = identifier[string] . identifier[encode] ( literal[string] )
keyword[elif... | def string_escape(string, delimiter='"'):
"""Turns special characters into escape sequences in the provided string.
Supports both byte strings and unicode strings properly. Any other values
will produce None.
Example:
>>> string_escape("a line ")
"a line\\t"
>>> string_escape(u"some fancy ... |
def concurrence(state):
"""Calculate the concurrence.
Args:
state (np.array): a quantum state (1x4 array) or a density matrix (4x4
array)
Returns:
float: concurrence.
Raises:
Exception: if attempted on more than two qubits.
"""
rho = np.array(st... | def function[concurrence, parameter[state]]:
constant[Calculate the concurrence.
Args:
state (np.array): a quantum state (1x4 array) or a density matrix (4x4
array)
Returns:
float: concurrence.
Raises:
Exception: if attempted on more than two qubits... | keyword[def] identifier[concurrence] ( identifier[state] ):
literal[string]
identifier[rho] = identifier[np] . identifier[array] ( identifier[state] )
keyword[if] identifier[rho] . identifier[ndim] == literal[int] :
identifier[rho] = identifier[outer] ( identifier[state] )
keyword[if] ... | def concurrence(state):
"""Calculate the concurrence.
Args:
state (np.array): a quantum state (1x4 array) or a density matrix (4x4
array)
Returns:
float: concurrence.
Raises:
Exception: if attempted on more than two qubits.
"""
rho = np.array(st... |
def _send_offset_commit_request(self, offsets):
"""Commit offsets for the specified list of topics and partitions.
This is a non-blocking call which returns a request future that can be
polled in the case of a synchronous commit or ignored in the
asynchronous case.
Arguments:
... | def function[_send_offset_commit_request, parameter[self, offsets]]:
constant[Commit offsets for the specified list of topics and partitions.
This is a non-blocking call which returns a request future that can be
polled in the case of a synchronous commit or ignored in the
asynchronous ... | keyword[def] identifier[_send_offset_commit_request] ( identifier[self] , identifier[offsets] ):
literal[string]
keyword[assert] identifier[self] . identifier[config] [ literal[string] ]>=( literal[int] , literal[int] , literal[int] ), literal[string]
keyword[assert] identifier[all] ( i... | def _send_offset_commit_request(self, offsets):
"""Commit offsets for the specified list of topics and partitions.
This is a non-blocking call which returns a request future that can be
polled in the case of a synchronous commit or ignored in the
asynchronous case.
Arguments:
... |
def create(self):
"""Launches a new server instance."""
self.server_attrs = self.consul.create_server(
"%s-%s" % (self.stack.name, self.name),
self.disk_image_id,
self.instance_type,
self.ssh_key_name,
tags=self.tags,
... | def function[create, parameter[self]]:
constant[Launches a new server instance.]
name[self].server_attrs assign[=] call[name[self].consul.create_server, parameter[binary_operation[constant[%s-%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da18eb54fa0>, <ast.Attribute object at... | keyword[def] identifier[create] ( identifier[self] ):
literal[string]
identifier[self] . identifier[server_attrs] = identifier[self] . identifier[consul] . identifier[create_server] (
literal[string] %( identifier[self] . identifier[stack] . identifier[name] , identifier[self] . identifier... | def create(self):
"""Launches a new server instance."""
self.server_attrs = self.consul.create_server('%s-%s' % (self.stack.name, self.name), self.disk_image_id, self.instance_type, self.ssh_key_name, tags=self.tags, availability_zone=self.availability_zone, timeout_s=self.launch_timeout_s, security_groups=self... |
def download_software(name, version=None, synch=False, check=False):
'''
Ensures that a software version is downloaded.
name: The name of the module function to execute.
version(str): The software version to check. If this version is not already downloaded, it will attempt to download
the file fro... | def function[download_software, parameter[name, version, synch, check]]:
constant[
Ensures that a software version is downloaded.
name: The name of the module function to execute.
version(str): The software version to check. If this version is not already downloaded, it will attempt to download
... | keyword[def] identifier[download_software] ( identifier[name] , identifier[version] = keyword[None] , identifier[synch] = keyword[False] , identifier[check] = keyword[False] ):
literal[string]
identifier[ret] = identifier[_default_ret] ( identifier[name] )
keyword[if] identifier[check] keyword[is] ... | def download_software(name, version=None, synch=False, check=False):
"""
Ensures that a software version is downloaded.
name: The name of the module function to execute.
version(str): The software version to check. If this version is not already downloaded, it will attempt to download
the file fro... |
def normalize_unicode(text):
"""
Normalize any unicode characters to ascii equivalent
https://docs.python.org/2/library/unicodedata.html#unicodedata.normalize
"""
if isinstance(text, six.text_type):
return unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode('utf8')
else:... | def function[normalize_unicode, parameter[text]]:
constant[
Normalize any unicode characters to ascii equivalent
https://docs.python.org/2/library/unicodedata.html#unicodedata.normalize
]
if call[name[isinstance], parameter[name[text], name[six].text_type]] begin[:]
return[call[call[... | keyword[def] identifier[normalize_unicode] ( identifier[text] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[text] , identifier[six] . identifier[text_type] ):
keyword[return] identifier[unicodedata] . identifier[normalize] ( literal[string] , identifier[text] ). identifier[e... | def normalize_unicode(text):
"""
Normalize any unicode characters to ascii equivalent
https://docs.python.org/2/library/unicodedata.html#unicodedata.normalize
"""
if isinstance(text, six.text_type):
return unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode('utf8') # depend... |
def try_until_succeed(_warning_period, func, *argv, **kwarg):
"""Try a function until it successfully returns.
Print current exception every ``_warning_period`` times try.
**中文文档**
尝试一个函数直到其成功为止。不适用于会出现死循环的函数。
每隔``_warning_period``次失败, 就会打印当前异常和尝试次数。
"""
if (not isinstanc... | def function[try_until_succeed, parameter[_warning_period, func]]:
constant[Try a function until it successfully returns.
Print current exception every ``_warning_period`` times try.
**中文文档**
尝试一个函数直到其成功为止。不适用于会出现死循环的函数。
每隔``_warning_period``次失败, 就会打印当前异常和尝试次数。
]
... | keyword[def] identifier[try_until_succeed] ( identifier[_warning_period] , identifier[func] ,* identifier[argv] ,** identifier[kwarg] ):
literal[string]
keyword[if] ( keyword[not] identifier[isinstance] ( identifier[_warning_period] , identifier[int] )) keyword[or] ( identifier[_warning_period] < literal[... | def try_until_succeed(_warning_period, func, *argv, **kwarg):
"""Try a function until it successfully returns.
Print current exception every ``_warning_period`` times try.
**中文文档**
尝试一个函数直到其成功为止。不适用于会出现死循环的函数。
每隔``_warning_period``次失败, 就会打印当前异常和尝试次数。
"""
if not isinstance... |
def fill4(image, mask=None, iterations=1):
'''Fill 4-connected black pixels
x 1 x x 1 x
1 0 1 -> 1 1 1
x 1 x x 1 x
'''
global fill4_table
if mask is None:
masked_image = image
else:
masked_image = image.astype(bool).copy()
masked_image[~mask] = True
... | def function[fill4, parameter[image, mask, iterations]]:
constant[Fill 4-connected black pixels
x 1 x x 1 x
1 0 1 -> 1 1 1
x 1 x x 1 x
]
<ast.Global object at 0x7da20e9606a0>
if compare[name[mask] is constant[None]] begin[:]
variable[masked_image] assign... | keyword[def] identifier[fill4] ( identifier[image] , identifier[mask] = keyword[None] , identifier[iterations] = literal[int] ):
literal[string]
keyword[global] identifier[fill4_table]
keyword[if] identifier[mask] keyword[is] keyword[None] :
identifier[masked_image] = identifier[image]
... | def fill4(image, mask=None, iterations=1):
"""Fill 4-connected black pixels
x 1 x x 1 x
1 0 1 -> 1 1 1
x 1 x x 1 x
"""
global fill4_table
if mask is None:
masked_image = image # depends on [control=['if'], data=[]]
else:
masked_image = image.astype(bool).co... |
def reload(self, r=None, pr=None, timeout=None, basic_quorum=None,
notfound_ok=None, head_only=False):
"""
Reload the object from Riak. When this operation completes, the
object could contain new metadata and a new value, if the object
was updated in Riak since it was last... | def function[reload, parameter[self, r, pr, timeout, basic_quorum, notfound_ok, head_only]]:
constant[
Reload the object from Riak. When this operation completes, the
object could contain new metadata and a new value, if the object
was updated in Riak since it was last retrieved.
... | keyword[def] identifier[reload] ( identifier[self] , identifier[r] = keyword[None] , identifier[pr] = keyword[None] , identifier[timeout] = keyword[None] , identifier[basic_quorum] = keyword[None] ,
identifier[notfound_ok] = keyword[None] , identifier[head_only] = keyword[False] ):
literal[string]
... | def reload(self, r=None, pr=None, timeout=None, basic_quorum=None, notfound_ok=None, head_only=False):
"""
Reload the object from Riak. When this operation completes, the
object could contain new metadata and a new value, if the object
was updated in Riak since it was last retrieved.
... |
def update_sma(self, step):
"""
Calculate an updated value for the semimajor axis, given the
current value and the step value.
The step value must be managed by the caller to support both
modes: grow outwards and shrink inwards.
Parameters
----------
ste... | def function[update_sma, parameter[self, step]]:
constant[
Calculate an updated value for the semimajor axis, given the
current value and the step value.
The step value must be managed by the caller to support both
modes: grow outwards and shrink inwards.
Parameters
... | keyword[def] identifier[update_sma] ( identifier[self] , identifier[step] ):
literal[string]
keyword[if] identifier[self] . identifier[linear_growth] :
identifier[sma] = identifier[self] . identifier[sma] + identifier[step]
keyword[else] :
identifier[sma] = ide... | def update_sma(self, step):
"""
Calculate an updated value for the semimajor axis, given the
current value and the step value.
The step value must be managed by the caller to support both
modes: grow outwards and shrink inwards.
Parameters
----------
step : ... |
def smart_fit(image, fit_to_width, fit_to_height):
"""
Proportionally fit the image into the specified width and height.
Return the correct width and height.
"""
im_width, im_height = image.size
out_width, out_height = fit_to_width, fit_to_height
if im_width == 0 ... | def function[smart_fit, parameter[image, fit_to_width, fit_to_height]]:
constant[
Proportionally fit the image into the specified width and height.
Return the correct width and height.
]
<ast.Tuple object at 0x7da20c794310> assign[=] name[image].size
<ast.Tuple object at ... | keyword[def] identifier[smart_fit] ( identifier[image] , identifier[fit_to_width] , identifier[fit_to_height] ):
literal[string]
identifier[im_width] , identifier[im_height] = identifier[image] . identifier[size]
identifier[out_width] , identifier[out_height] = identifier[fit_to_width] , ... | def smart_fit(image, fit_to_width, fit_to_height):
"""
Proportionally fit the image into the specified width and height.
Return the correct width and height.
"""
(im_width, im_height) = image.size
(out_width, out_height) = (fit_to_width, fit_to_height)
if im_width == 0 or im_heig... |
def run(self, args=None):
"""
Runs the command passing in the parsed arguments.
:param args: The arguments to run the command with. If ``None`` the arguments
are gathered from the argument parser. This is automatically set when calling
sub commands and in most cases shou... | def function[run, parameter[self, args]]:
constant[
Runs the command passing in the parsed arguments.
:param args: The arguments to run the command with. If ``None`` the arguments
are gathered from the argument parser. This is automatically set when calling
sub commands ... | keyword[def] identifier[run] ( identifier[self] , identifier[args] = keyword[None] ):
literal[string]
identifier[args] = identifier[args] keyword[or] identifier[self] . identifier[parse_args] ()
identifier[sub_command_name] = identifier[getattr] ( identifier[args] , identifier[self] . i... | def run(self, args=None):
"""
Runs the command passing in the parsed arguments.
:param args: The arguments to run the command with. If ``None`` the arguments
are gathered from the argument parser. This is automatically set when calling
sub commands and in most cases should n... |
def get_group_index(labels, shape, sort, xnull):
"""
For the particular label_list, gets the offsets into the hypothetical list
representing the totally ordered cartesian product of all possible label
combinations, *as long as* this space fits within int64 bounds;
otherwise, though group indices ide... | def function[get_group_index, parameter[labels, shape, sort, xnull]]:
constant[
For the particular label_list, gets the offsets into the hypothetical list
representing the totally ordered cartesian product of all possible label
combinations, *as long as* this space fits within int64 bounds;
othe... | keyword[def] identifier[get_group_index] ( identifier[labels] , identifier[shape] , identifier[sort] , identifier[xnull] ):
literal[string]
keyword[def] identifier[_int64_cut_off] ( identifier[shape] ):
identifier[acc] = literal[int]
keyword[for] identifier[i] , identifier[mul] keywor... | def get_group_index(labels, shape, sort, xnull):
"""
For the particular label_list, gets the offsets into the hypothetical list
representing the totally ordered cartesian product of all possible label
combinations, *as long as* this space fits within int64 bounds;
otherwise, though group indices ide... |
def decrypt_ige(cipher_text, key, iv):
"""
Decrypts the given text in 16-bytes blocks by using the
given key and 32-bytes initialization vector.
"""
if cryptg:
return cryptg.decrypt_ige(cipher_text, key, iv)
if libssl.decrypt_ige:
return libssl.dec... | def function[decrypt_ige, parameter[cipher_text, key, iv]]:
constant[
Decrypts the given text in 16-bytes blocks by using the
given key and 32-bytes initialization vector.
]
if name[cryptg] begin[:]
return[call[name[cryptg].decrypt_ige, parameter[name[cipher_text], name[k... | keyword[def] identifier[decrypt_ige] ( identifier[cipher_text] , identifier[key] , identifier[iv] ):
literal[string]
keyword[if] identifier[cryptg] :
keyword[return] identifier[cryptg] . identifier[decrypt_ige] ( identifier[cipher_text] , identifier[key] , identifier[iv] )
k... | def decrypt_ige(cipher_text, key, iv):
"""
Decrypts the given text in 16-bytes blocks by using the
given key and 32-bytes initialization vector.
"""
if cryptg:
return cryptg.decrypt_ige(cipher_text, key, iv) # depends on [control=['if'], data=[]]
if libssl.decrypt_ige:
... |
def doLayout(self, width):
"""
Align words in previous line.
"""
# Calculate dimensions
self.width = width
font_sizes = [0] + [frag.get("fontSize", 0) for frag in self]
self.fontSize = max(font_sizes)
self.height = self.lineHeight = max(frag * self.LINEH... | def function[doLayout, parameter[self, width]]:
constant[
Align words in previous line.
]
name[self].width assign[=] name[width]
variable[font_sizes] assign[=] binary_operation[list[[<ast.Constant object at 0x7da1b12c9570>]] + <ast.ListComp object at 0x7da1b12cb100>]
name... | keyword[def] identifier[doLayout] ( identifier[self] , identifier[width] ):
literal[string]
identifier[self] . identifier[width] = identifier[width]
identifier[font_sizes] =[ literal[int] ]+[ identifier[frag] . identifier[get] ( literal[string] , literal[int] ) keyword[for] id... | def doLayout(self, width):
"""
Align words in previous line.
"""
# Calculate dimensions
self.width = width
font_sizes = [0] + [frag.get('fontSize', 0) for frag in self]
self.fontSize = max(font_sizes)
self.height = self.lineHeight = max((frag * self.LINEHEIGHT for frag in font_si... |
def updated_time_delta(self):
"""Returns the number of seconds ago the issue was updated from current time.
"""
local_timezone = tzlocal()
update_at = datetime.datetime.strptime(self.updated_at, '%Y-%m-%dT%XZ')
update_at_utc = pytz.utc.localize(update_at)
update_at_local ... | def function[updated_time_delta, parameter[self]]:
constant[Returns the number of seconds ago the issue was updated from current time.
]
variable[local_timezone] assign[=] call[name[tzlocal], parameter[]]
variable[update_at] assign[=] call[name[datetime].datetime.strptime, parameter[name... | keyword[def] identifier[updated_time_delta] ( identifier[self] ):
literal[string]
identifier[local_timezone] = identifier[tzlocal] ()
identifier[update_at] = identifier[datetime] . identifier[datetime] . identifier[strptime] ( identifier[self] . identifier[updated_at] , literal[string] )
... | def updated_time_delta(self):
"""Returns the number of seconds ago the issue was updated from current time.
"""
local_timezone = tzlocal()
update_at = datetime.datetime.strptime(self.updated_at, '%Y-%m-%dT%XZ')
update_at_utc = pytz.utc.localize(update_at)
update_at_local = update_at_utc.asti... |
def filter_search(self, search):
"""Filter given search by the filter parameter given in request.
:param search: ElasticSearch query object
"""
builder = QueryBuilder(
self.filtering_fields,
self.filtering_map,
self
)
search, unmatche... | def function[filter_search, parameter[self, search]]:
constant[Filter given search by the filter parameter given in request.
:param search: ElasticSearch query object
]
variable[builder] assign[=] call[name[QueryBuilder], parameter[name[self].filtering_fields, name[self].filtering_map,... | keyword[def] identifier[filter_search] ( identifier[self] , identifier[search] ):
literal[string]
identifier[builder] = identifier[QueryBuilder] (
identifier[self] . identifier[filtering_fields] ,
identifier[self] . identifier[filtering_map] ,
identifier[self]
)
... | def filter_search(self, search):
"""Filter given search by the filter parameter given in request.
:param search: ElasticSearch query object
"""
builder = QueryBuilder(self.filtering_fields, self.filtering_map, self)
(search, unmatched) = builder.build(search, self.get_query_params())
#... |
def set_db_application_prefix(prefix, sep=None):
"""Set the global app prefix and separator."""
global _APPLICATION_PREFIX, _APPLICATION_SEP
_APPLICATION_PREFIX = prefix
if (sep is not None):
_APPLICATION_SEP = sep | def function[set_db_application_prefix, parameter[prefix, sep]]:
constant[Set the global app prefix and separator.]
<ast.Global object at 0x7da207f02620>
variable[_APPLICATION_PREFIX] assign[=] name[prefix]
if compare[name[sep] is_not constant[None]] begin[:]
variable[_APPLIC... | keyword[def] identifier[set_db_application_prefix] ( identifier[prefix] , identifier[sep] = keyword[None] ):
literal[string]
keyword[global] identifier[_APPLICATION_PREFIX] , identifier[_APPLICATION_SEP]
identifier[_APPLICATION_PREFIX] = identifier[prefix]
keyword[if] ( identifier[sep] keywor... | def set_db_application_prefix(prefix, sep=None):
"""Set the global app prefix and separator."""
global _APPLICATION_PREFIX, _APPLICATION_SEP
_APPLICATION_PREFIX = prefix
if sep is not None:
_APPLICATION_SEP = sep # depends on [control=['if'], data=['sep']] |
def format(self, record):
"""
Apply level-specific styling to log records.
:param record: A :class:`~logging.LogRecord` object.
:returns: The result of :func:`logging.Formatter.format()`.
This method injects ANSI escape sequences that are specific to the
level of each l... | def function[format, parameter[self, record]]:
constant[
Apply level-specific styling to log records.
:param record: A :class:`~logging.LogRecord` object.
:returns: The result of :func:`logging.Formatter.format()`.
This method injects ANSI escape sequences that are specific to ... | keyword[def] identifier[format] ( identifier[self] , identifier[record] ):
literal[string]
identifier[style] = identifier[self] . identifier[nn] . identifier[get] ( identifier[self] . identifier[level_styles] , identifier[record] . identifier[levelname] )
... | def format(self, record):
"""
Apply level-specific styling to log records.
:param record: A :class:`~logging.LogRecord` object.
:returns: The result of :func:`logging.Formatter.format()`.
This method injects ANSI escape sequences that are specific to the
level of each log r... |
def hide_tooltip_if_necessary(self, key):
"""Hide calltip when necessary"""
try:
calltip_char = self.get_character(self.calltip_position)
before = self.is_cursor_before(self.calltip_position,
char_offset=1)
other = key ... | def function[hide_tooltip_if_necessary, parameter[self, key]]:
constant[Hide calltip when necessary]
<ast.Try object at 0x7da18bcc9b70> | keyword[def] identifier[hide_tooltip_if_necessary] ( identifier[self] , identifier[key] ):
literal[string]
keyword[try] :
identifier[calltip_char] = identifier[self] . identifier[get_character] ( identifier[self] . identifier[calltip_position] )
identifier[before] = id... | def hide_tooltip_if_necessary(self, key):
"""Hide calltip when necessary"""
try:
calltip_char = self.get_character(self.calltip_position)
before = self.is_cursor_before(self.calltip_position, char_offset=1)
other = key in (Qt.Key_ParenRight, Qt.Key_Period, Qt.Key_Tab)
if calltip_... |
def set_ctype(self, ctype, orig_ctype=None):
"""
Set the selected content type. Will not override the value of
the content type if that has already been determined.
:param ctype: The content type string to set.
:param orig_ctype: The original content type, as found in the
... | def function[set_ctype, parameter[self, ctype, orig_ctype]]:
constant[
Set the selected content type. Will not override the value of
the content type if that has already been determined.
:param ctype: The content type string to set.
:param orig_ctype: The original content type... | keyword[def] identifier[set_ctype] ( identifier[self] , identifier[ctype] , identifier[orig_ctype] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[ctype] keyword[is] keyword[None] :
identifier[self] . identifier[ctype] = identifier[ctype]
... | def set_ctype(self, ctype, orig_ctype=None):
"""
Set the selected content type. Will not override the value of
the content type if that has already been determined.
:param ctype: The content type string to set.
:param orig_ctype: The original content type, as found in the
... |
def commit(self) -> ResponseCommit:
"""Return the current encode state value to tendermint"""
hash = struct.pack('>Q', self.txCount)
return ResponseCommit(data=hash) | def function[commit, parameter[self]]:
constant[Return the current encode state value to tendermint]
variable[hash] assign[=] call[name[struct].pack, parameter[constant[>Q], name[self].txCount]]
return[call[name[ResponseCommit], parameter[]]] | keyword[def] identifier[commit] ( identifier[self] )-> identifier[ResponseCommit] :
literal[string]
identifier[hash] = identifier[struct] . identifier[pack] ( literal[string] , identifier[self] . identifier[txCount] )
keyword[return] identifier[ResponseCommit] ( identifier[data] = identif... | def commit(self) -> ResponseCommit:
"""Return the current encode state value to tendermint"""
hash = struct.pack('>Q', self.txCount)
return ResponseCommit(data=hash) |
def item_afdeling_adapter(obj, request):
"""
Adapter for rendering an object of
:class: `crabpy.gateway.capakey.Afdeling` to json.
"""
return {
'id': obj.id,
'naam': obj.naam,
'gemeente': {
'id': obj.gemeente.id,
'naam': obj.gemeente.naam
},
... | def function[item_afdeling_adapter, parameter[obj, request]]:
constant[
Adapter for rendering an object of
:class: `crabpy.gateway.capakey.Afdeling` to json.
]
return[dictionary[[<ast.Constant object at 0x7da1b0949fc0>, <ast.Constant object at 0x7da1b09485b0>, <ast.Constant object at 0x7da1b0a66... | keyword[def] identifier[item_afdeling_adapter] ( identifier[obj] , identifier[request] ):
literal[string]
keyword[return] {
literal[string] : identifier[obj] . identifier[id] ,
literal[string] : identifier[obj] . identifier[naam] ,
literal[string] :{
literal[string] : identifier[obj] . ... | def item_afdeling_adapter(obj, request):
"""
Adapter for rendering an object of
:class: `crabpy.gateway.capakey.Afdeling` to json.
"""
return {'id': obj.id, 'naam': obj.naam, 'gemeente': {'id': obj.gemeente.id, 'naam': obj.gemeente.naam}, 'centroid': obj.centroid, 'bounding_box': obj.bounding_box} |
def make_thumbnail_name(image_name, extension):
"""Return name of the downloaded thumbnail, based on the extension."""
file_name, _ = os.path.splitext(image_name)
return file_name + '.' + clean_extension(extension) | def function[make_thumbnail_name, parameter[image_name, extension]]:
constant[Return name of the downloaded thumbnail, based on the extension.]
<ast.Tuple object at 0x7da18c4cd240> assign[=] call[name[os].path.splitext, parameter[name[image_name]]]
return[binary_operation[binary_operation[name[file_... | keyword[def] identifier[make_thumbnail_name] ( identifier[image_name] , identifier[extension] ):
literal[string]
identifier[file_name] , identifier[_] = identifier[os] . identifier[path] . identifier[splitext] ( identifier[image_name] )
keyword[return] identifier[file_name] + literal[string] + identi... | def make_thumbnail_name(image_name, extension):
"""Return name of the downloaded thumbnail, based on the extension."""
(file_name, _) = os.path.splitext(image_name)
return file_name + '.' + clean_extension(extension) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.