code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def opt_separator(self) -> bool:
"""Parse an optional separator and return ``True`` if found.
Raises:
EndOfInput: If past the end of input.
"""
start = self.offset
self.dfa([
{ # state 0: whitespace
"": lambda: -1,
" ": la... | def function[opt_separator, parameter[self]]:
constant[Parse an optional separator and return ``True`` if found.
Raises:
EndOfInput: If past the end of input.
]
variable[start] assign[=] name[self].offset
call[name[self].dfa, parameter[list[[<ast.Dict object at 0x7da... | keyword[def] identifier[opt_separator] ( identifier[self] )-> identifier[bool] :
literal[string]
identifier[start] = identifier[self] . identifier[offset]
identifier[self] . identifier[dfa] ([
{
literal[string] : keyword[lambda] :- literal[int] ,
literal[string] ... | def opt_separator(self) -> bool:
"""Parse an optional separator and return ``True`` if found.
Raises:
EndOfInput: If past the end of input.
"""
start = self.offset # state 0: whitespace
# state 1: CR/LF?
# state 2: start comment?
# state 3: line comment
# state 4: b... |
def json_repr(obj, curr_depth=0, max_depth=4):
"""Represent instance of a class as JSON.
Arguments:
obj -- any object
Return:
String that represent JSON-encoded object.
"""
def serialize(obj, curr_depth):
"""Recursively walk object's hierarchy. Limit to max_depth"""
if curr_d... | def function[json_repr, parameter[obj, curr_depth, max_depth]]:
constant[Represent instance of a class as JSON.
Arguments:
obj -- any object
Return:
String that represent JSON-encoded object.
]
def function[serialize, parameter[obj, curr_depth]]:
constant[Recursively ... | keyword[def] identifier[json_repr] ( identifier[obj] , identifier[curr_depth] = literal[int] , identifier[max_depth] = literal[int] ):
literal[string]
keyword[def] identifier[serialize] ( identifier[obj] , identifier[curr_depth] ):
literal[string]
keyword[if] identifier[curr_depth] > i... | def json_repr(obj, curr_depth=0, max_depth=4):
"""Represent instance of a class as JSON.
Arguments:
obj -- any object
Return:
String that represent JSON-encoded object.
"""
def serialize(obj, curr_depth):
"""Recursively walk object's hierarchy. Limit to max_depth"""
if curr_... |
def LCHab_to_Lab(cobj, *args, **kwargs):
"""
Convert from LCH(ab) to Lab.
"""
lab_l = cobj.lch_l
lab_a = math.cos(math.radians(cobj.lch_h)) * cobj.lch_c
lab_b = math.sin(math.radians(cobj.lch_h)) * cobj.lch_c
return LabColor(
lab_l, lab_a, lab_b, illuminant=cobj.illuminant, observer=... | def function[LCHab_to_Lab, parameter[cobj]]:
constant[
Convert from LCH(ab) to Lab.
]
variable[lab_l] assign[=] name[cobj].lch_l
variable[lab_a] assign[=] binary_operation[call[name[math].cos, parameter[call[name[math].radians, parameter[name[cobj].lch_h]]]] * name[cobj].lch_c]
v... | keyword[def] identifier[LCHab_to_Lab] ( identifier[cobj] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[lab_l] = identifier[cobj] . identifier[lch_l]
identifier[lab_a] = identifier[math] . identifier[cos] ( identifier[math] . identifier[radians] ( identifier[cobj] . identifi... | def LCHab_to_Lab(cobj, *args, **kwargs):
"""
Convert from LCH(ab) to Lab.
"""
lab_l = cobj.lch_l
lab_a = math.cos(math.radians(cobj.lch_h)) * cobj.lch_c
lab_b = math.sin(math.radians(cobj.lch_h)) * cobj.lch_c
return LabColor(lab_l, lab_a, lab_b, illuminant=cobj.illuminant, observer=cobj.obse... |
def fix_post_relative_url(rel_url):
"""
Fix post relative url to a standard, uniform format.
Possible input:
- 2016/7/8/my-post
- 2016/07/08/my-post.html
- 2016/8/09/my-post/
- 2016/8/09/my-post/index
- 2016/8/09/my-post/index.htm
- 2016/8/09/my-p... | def function[fix_post_relative_url, parameter[rel_url]]:
constant[
Fix post relative url to a standard, uniform format.
Possible input:
- 2016/7/8/my-post
- 2016/07/08/my-post.html
- 2016/8/09/my-post/
- 2016/8/09/my-post/index
- 2016/8/09/my-post/index.h... | keyword[def] identifier[fix_post_relative_url] ( identifier[rel_url] ):
literal[string]
identifier[m] = identifier[re] . identifier[match] (
literal[string]
literal[string]
literal[string] ,
identifier[rel_url]
)
keyword[if] keyword[not] ide... | def fix_post_relative_url(rel_url):
"""
Fix post relative url to a standard, uniform format.
Possible input:
- 2016/7/8/my-post
- 2016/07/08/my-post.html
- 2016/8/09/my-post/
- 2016/8/09/my-post/index
- 2016/8/09/my-post/index.htm
- 2016/8/09/my-post/... |
def plot_fit_individuals_lens_plane_only(
fit, should_plot_mask=True, extract_array_from_mask=False, zoom_around_mask=False, positions=None,
should_plot_image_plane_pix=False,
should_plot_image=False,
should_plot_noise_map=False,
should_plot_signal_to_noise_map=False,
sho... | def function[plot_fit_individuals_lens_plane_only, parameter[fit, should_plot_mask, extract_array_from_mask, zoom_around_mask, positions, should_plot_image_plane_pix, should_plot_image, should_plot_noise_map, should_plot_signal_to_noise_map, should_plot_model_image, should_plot_residual_map, should_plot_chi_squared_map... | keyword[def] identifier[plot_fit_individuals_lens_plane_only] (
identifier[fit] , identifier[should_plot_mask] = keyword[True] , identifier[extract_array_from_mask] = keyword[False] , identifier[zoom_around_mask] = keyword[False] , identifier[positions] = keyword[None] ,
identifier[should_plot_image_plane_pix] = ke... | def plot_fit_individuals_lens_plane_only(fit, should_plot_mask=True, extract_array_from_mask=False, zoom_around_mask=False, positions=None, should_plot_image_plane_pix=False, should_plot_image=False, should_plot_noise_map=False, should_plot_signal_to_noise_map=False, should_plot_model_image=False, should_plot_residual_... |
def register_url(url, handler, name=None, kwargs=None):
"""insert url into tornado application handlers group
:arg str url: url
:handler object handler: url mapping handler
:name reverse url name
:kwargs dict tornado handler initlize args
"""
if name is None and kwargs is None:
app_... | def function[register_url, parameter[url, handler, name, kwargs]]:
constant[insert url into tornado application handlers group
:arg str url: url
:handler object handler: url mapping handler
:name reverse url name
:kwargs dict tornado handler initlize args
]
if <ast.BoolOp object at ... | keyword[def] identifier[register_url] ( identifier[url] , identifier[handler] , identifier[name] = keyword[None] , identifier[kwargs] = keyword[None] ):
literal[string]
keyword[if] identifier[name] keyword[is] keyword[None] keyword[and] identifier[kwargs] keyword[is] keyword[None] :
identif... | def register_url(url, handler, name=None, kwargs=None):
"""insert url into tornado application handlers group
:arg str url: url
:handler object handler: url mapping handler
:name reverse url name
:kwargs dict tornado handler initlize args
"""
if name is None and kwargs is None:
app_... |
def process_raw(self, raw: dict) -> None:
"""Pre-process raw dict.
Prepare parameters to work with APIItems.
"""
raw_ports = {}
for param in raw:
port_index = REGEX_PORT_INDEX.search(param).group(0)
if port_index not in raw_ports:
raw_po... | def function[process_raw, parameter[self, raw]]:
constant[Pre-process raw dict.
Prepare parameters to work with APIItems.
]
variable[raw_ports] assign[=] dictionary[[], []]
for taget[name[param]] in starred[name[raw]] begin[:]
variable[port_index] assign[=] call[... | keyword[def] identifier[process_raw] ( identifier[self] , identifier[raw] : identifier[dict] )-> keyword[None] :
literal[string]
identifier[raw_ports] ={}
keyword[for] identifier[param] keyword[in] identifier[raw] :
identifier[port_index] = identifier[REGEX_PORT_INDEX] . i... | def process_raw(self, raw: dict) -> None:
"""Pre-process raw dict.
Prepare parameters to work with APIItems.
"""
raw_ports = {}
for param in raw:
port_index = REGEX_PORT_INDEX.search(param).group(0)
if port_index not in raw_ports:
raw_ports[port_index] = {} # de... |
def encrypt(self, plaintext, iv_bytes=None):
"""Given ``plaintext``, returns a ``ciphertext`` encrypted with an authenticated-encryption scheme, using the keys specified in ``__init__``.
Ciphertext expansion is deterministic, the output ciphertext is always 42 bytes longer than the input ``plaintext``.
... | def function[encrypt, parameter[self, plaintext, iv_bytes]]:
constant[Given ``plaintext``, returns a ``ciphertext`` encrypted with an authenticated-encryption scheme, using the keys specified in ``__init__``.
Ciphertext expansion is deterministic, the output ciphertext is always 42 bytes longer than the... | keyword[def] identifier[encrypt] ( identifier[self] , identifier[plaintext] , identifier[iv_bytes] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[plaintext] , identifier[str] ):
keyword[raise] identifier[PlaintextTypeError] ( literal... | def encrypt(self, plaintext, iv_bytes=None):
"""Given ``plaintext``, returns a ``ciphertext`` encrypted with an authenticated-encryption scheme, using the keys specified in ``__init__``.
Ciphertext expansion is deterministic, the output ciphertext is always 42 bytes longer than the input ``plaintext``.
... |
def py_to_glsl(root):
"""Translate Python AST into GLSL code.
root: an ast.FunctionDef object
Return a list of strings, where each string is a line of GLSL
code.
"""
atg = AstToGlsl()
code = atg.visit(root)
return code.lines | def function[py_to_glsl, parameter[root]]:
constant[Translate Python AST into GLSL code.
root: an ast.FunctionDef object
Return a list of strings, where each string is a line of GLSL
code.
]
variable[atg] assign[=] call[name[AstToGlsl], parameter[]]
variable[code] assign[=] cal... | keyword[def] identifier[py_to_glsl] ( identifier[root] ):
literal[string]
identifier[atg] = identifier[AstToGlsl] ()
identifier[code] = identifier[atg] . identifier[visit] ( identifier[root] )
keyword[return] identifier[code] . identifier[lines] | def py_to_glsl(root):
"""Translate Python AST into GLSL code.
root: an ast.FunctionDef object
Return a list of strings, where each string is a line of GLSL
code.
"""
atg = AstToGlsl()
code = atg.visit(root)
return code.lines |
def nearest_subpackage(cls, package, all_packages):
"""Given a package, find its nearest parent in all_packages."""
def shared_prefix(candidate):
zipped = zip(package.split('.'), candidate.split('.'))
matching = itertools.takewhile(lambda pair: pair[0] == pair[1], zipped)
return [pair[0] for p... | def function[nearest_subpackage, parameter[cls, package, all_packages]]:
constant[Given a package, find its nearest parent in all_packages.]
def function[shared_prefix, parameter[candidate]]:
variable[zipped] assign[=] call[name[zip], parameter[call[name[package].split, parameter[constan... | keyword[def] identifier[nearest_subpackage] ( identifier[cls] , identifier[package] , identifier[all_packages] ):
literal[string]
keyword[def] identifier[shared_prefix] ( identifier[candidate] ):
identifier[zipped] = identifier[zip] ( identifier[package] . identifier[split] ( literal[string] ), ide... | def nearest_subpackage(cls, package, all_packages):
"""Given a package, find its nearest parent in all_packages."""
def shared_prefix(candidate):
zipped = zip(package.split('.'), candidate.split('.'))
matching = itertools.takewhile(lambda pair: pair[0] == pair[1], zipped)
return [pair[0... |
def Extract(fileList, fileFormatList, archiveDir, skipUserInput):
"""
Iterate through given file list and extract all files matching the file
format list from each RAR file. After sucessful extraction move RAR files to
archive directory.
Parameters
----------
fileList : list
List of files to atte... | def function[Extract, parameter[fileList, fileFormatList, archiveDir, skipUserInput]]:
constant[
Iterate through given file list and extract all files matching the file
format list from each RAR file. After sucessful extraction move RAR files to
archive directory.
Parameters
----------
fileList :... | keyword[def] identifier[Extract] ( identifier[fileList] , identifier[fileFormatList] , identifier[archiveDir] , identifier[skipUserInput] ):
literal[string]
identifier[goodlogging] . identifier[Log] . identifier[Info] ( literal[string] , literal[string] )
identifier[goodlogging] . identifier[Log] . identifi... | def Extract(fileList, fileFormatList, archiveDir, skipUserInput):
"""
Iterate through given file list and extract all files matching the file
format list from each RAR file. After sucessful extraction move RAR files to
archive directory.
Parameters
----------
fileList : list
List of files to at... |
def assign_user_policies(user, *policies_roles):
"""Assign a sequence of policies to a user (or the anonymous user is
``user`` is ``None``). (Also installed as ``assign_policies``
method on ``User`` model.
"""
clear_user_policies(user)
pset = PermissionSet.objects.by_policies_and_roles(policie... | def function[assign_user_policies, parameter[user]]:
constant[Assign a sequence of policies to a user (or the anonymous user is
``user`` is ``None``). (Also installed as ``assign_policies``
method on ``User`` model.
]
call[name[clear_user_policies], parameter[name[user]]]
variable[... | keyword[def] identifier[assign_user_policies] ( identifier[user] ,* identifier[policies_roles] ):
literal[string]
identifier[clear_user_policies] ( identifier[user] )
identifier[pset] = identifier[PermissionSet] . identifier[objects] . identifier[by_policies_and_roles] ( identifier[policies_roles] )
... | def assign_user_policies(user, *policies_roles):
"""Assign a sequence of policies to a user (or the anonymous user is
``user`` is ``None``). (Also installed as ``assign_policies``
method on ``User`` model.
"""
clear_user_policies(user)
pset = PermissionSet.objects.by_policies_and_roles(policie... |
def kill(self) -> None:
"""Kill ffmpeg job."""
self._proc.kill()
self._loop.run_in_executor(None, self._proc.communicate) | def function[kill, parameter[self]]:
constant[Kill ffmpeg job.]
call[name[self]._proc.kill, parameter[]]
call[name[self]._loop.run_in_executor, parameter[constant[None], name[self]._proc.communicate]] | keyword[def] identifier[kill] ( identifier[self] )-> keyword[None] :
literal[string]
identifier[self] . identifier[_proc] . identifier[kill] ()
identifier[self] . identifier[_loop] . identifier[run_in_executor] ( keyword[None] , identifier[self] . identifier[_proc] . identifier[communicate... | def kill(self) -> None:
"""Kill ffmpeg job."""
self._proc.kill()
self._loop.run_in_executor(None, self._proc.communicate) |
def closestConnectedDistance(target, walls=None,
max_len_border_line=500,
max_n_path=100,
concentrate_every_n_pixel=1):
'''
returns an array with contains the closest distance from every pixel
the next position wher... | def function[closestConnectedDistance, parameter[target, walls, max_len_border_line, max_n_path, concentrate_every_n_pixel]]:
constant[
returns an array with contains the closest distance from every pixel
the next position where target == 1
[walls] binary 2darray - e.g. walls in a labyrinth that ha... | keyword[def] identifier[closestConnectedDistance] ( identifier[target] , identifier[walls] = keyword[None] ,
identifier[max_len_border_line] = literal[int] ,
identifier[max_n_path] = literal[int] ,
identifier[concentrate_every_n_pixel] = literal[int] ):
literal[string]
identifier[c] = identifier[co... | def closestConnectedDistance(target, walls=None, max_len_border_line=500, max_n_path=100, concentrate_every_n_pixel=1):
"""
returns an array with contains the closest distance from every pixel
the next position where target == 1
[walls] binary 2darray - e.g. walls in a labyrinth that have to be surroun... |
def open(self):
"""This is the only way to open a file resource."""
self.__sf = _sftp_open(self.__sftp_session_int,
self.__filepath,
self.access_type_int,
self.__create_mode)
if self.access_type_is_... | def function[open, parameter[self]]:
constant[This is the only way to open a file resource.]
name[self].__sf assign[=] call[name[_sftp_open], parameter[name[self].__sftp_session_int, name[self].__filepath, name[self].access_type_int, name[self].__create_mode]]
if compare[name[self].access_type_i... | keyword[def] identifier[open] ( identifier[self] ):
literal[string]
identifier[self] . identifier[__sf] = identifier[_sftp_open] ( identifier[self] . identifier[__sftp_session_int] ,
identifier[self] . identifier[__filepath] ,
identifier[self] . identifier[access_type_int] ,
... | def open(self):
"""This is the only way to open a file resource."""
self.__sf = _sftp_open(self.__sftp_session_int, self.__filepath, self.access_type_int, self.__create_mode)
if self.access_type_is_append is True:
self.seek(self.filesize) # depends on [control=['if'], data=[]]
return SftpFileOb... |
def ensure_crops(self, *required_crops):
"""
Make sure a crop exists for each crop in required_crops.
Existing crops will not be changed.
If settings.ASSET_CELERY is specified then
the task will be run async
"""
if self._can_crop():
if settings.CELERY... | def function[ensure_crops, parameter[self]]:
constant[
Make sure a crop exists for each crop in required_crops.
Existing crops will not be changed.
If settings.ASSET_CELERY is specified then
the task will be run async
]
if call[name[self]._can_crop, parameter[]] ... | keyword[def] identifier[ensure_crops] ( identifier[self] ,* identifier[required_crops] ):
literal[string]
keyword[if] identifier[self] . identifier[_can_crop] ():
keyword[if] identifier[settings] . identifier[CELERY] keyword[or] identifier[settings] . identifier[USE_CELERY_DECORATO... | def ensure_crops(self, *required_crops):
"""
Make sure a crop exists for each crop in required_crops.
Existing crops will not be changed.
If settings.ASSET_CELERY is specified then
the task will be run async
"""
if self._can_crop():
if settings.CELERY or settings... |
def _write(self, session, openFile, replaceParamFile):
"""
Generic Time Series Write to File Method
"""
# Retrieve all time series
timeSeries = self.timeSeries
# Num TimeSeries
numTS = len(timeSeries)
# Transform into list of dictionaries for pivot tool
... | def function[_write, parameter[self, session, openFile, replaceParamFile]]:
constant[
Generic Time Series Write to File Method
]
variable[timeSeries] assign[=] name[self].timeSeries
variable[numTS] assign[=] call[name[len], parameter[name[timeSeries]]]
variable[valList] a... | keyword[def] identifier[_write] ( identifier[self] , identifier[session] , identifier[openFile] , identifier[replaceParamFile] ):
literal[string]
identifier[timeSeries] = identifier[self] . identifier[timeSeries]
identifier[numTS] = identifier[len] ( identifier[timeSeri... | def _write(self, session, openFile, replaceParamFile):
"""
Generic Time Series Write to File Method
"""
# Retrieve all time series
timeSeries = self.timeSeries
# Num TimeSeries
numTS = len(timeSeries)
# Transform into list of dictionaries for pivot tool
valList = []
for (... |
def get_arguments(self):
"""
Extracts the specific arguments of this CLI
"""
ApiCli.get_arguments(self)
if self.args.hostGroupName is not None:
self.url_parameters = {"name": self.args.hostGroupName} | def function[get_arguments, parameter[self]]:
constant[
Extracts the specific arguments of this CLI
]
call[name[ApiCli].get_arguments, parameter[name[self]]]
if compare[name[self].args.hostGroupName is_not constant[None]] begin[:]
name[self].url_parameters assign[... | keyword[def] identifier[get_arguments] ( identifier[self] ):
literal[string]
identifier[ApiCli] . identifier[get_arguments] ( identifier[self] )
keyword[if] identifier[self] . identifier[args] . identifier[hostGroupName] keyword[is] keyword[not] keyword[None] :
identifier[... | def get_arguments(self):
"""
Extracts the specific arguments of this CLI
"""
ApiCli.get_arguments(self)
if self.args.hostGroupName is not None:
self.url_parameters = {'name': self.args.hostGroupName} # depends on [control=['if'], data=[]] |
def close(self):
"""Send CLOSE command to device."""
close_command = StandardSend(self._address,
COMMAND_LIGHT_OFF_0X13_0X00)
self._send_method(close_command, self._close_message_received) | def function[close, parameter[self]]:
constant[Send CLOSE command to device.]
variable[close_command] assign[=] call[name[StandardSend], parameter[name[self]._address, name[COMMAND_LIGHT_OFF_0X13_0X00]]]
call[name[self]._send_method, parameter[name[close_command], name[self]._close_message_recei... | keyword[def] identifier[close] ( identifier[self] ):
literal[string]
identifier[close_command] = identifier[StandardSend] ( identifier[self] . identifier[_address] ,
identifier[COMMAND_LIGHT_OFF_0X13_0X00] )
identifier[self] . identifier[_send_method] ( identifier[close_command] ,... | def close(self):
"""Send CLOSE command to device."""
close_command = StandardSend(self._address, COMMAND_LIGHT_OFF_0X13_0X00)
self._send_method(close_command, self._close_message_received) |
def _parse_peer_address(self, config):
"""Scans the config block and parses the peer-address value
Args:
config (str): The config block to scan
Returns:
dict: A dict object that is intended to be merged into the
resource dict
"""
match = ... | def function[_parse_peer_address, parameter[self, config]]:
constant[Scans the config block and parses the peer-address value
Args:
config (str): The config block to scan
Returns:
dict: A dict object that is intended to be merged into the
resource dict
... | keyword[def] identifier[_parse_peer_address] ( identifier[self] , identifier[config] ):
literal[string]
identifier[match] = identifier[re] . identifier[search] ( literal[string] , identifier[config] )
identifier[value] = identifier[match] . identifier[group] ( literal[int] ) keyword[if] i... | def _parse_peer_address(self, config):
"""Scans the config block and parses the peer-address value
Args:
config (str): The config block to scan
Returns:
dict: A dict object that is intended to be merged into the
resource dict
"""
match = re.searc... |
def _fully_random_weights(n_features, lam_scale, prng):
"""Generate a symmetric random matrix with zeros along the diagonal."""
weights = np.zeros((n_features, n_features))
n_off_diag = int((n_features ** 2 - n_features) / 2)
weights[np.triu_indices(n_features, k=1)] = 0.1 * lam_scale * prng.randn(
... | def function[_fully_random_weights, parameter[n_features, lam_scale, prng]]:
constant[Generate a symmetric random matrix with zeros along the diagonal.]
variable[weights] assign[=] call[name[np].zeros, parameter[tuple[[<ast.Name object at 0x7da20c794c40>, <ast.Name object at 0x7da20c795630>]]]]
... | keyword[def] identifier[_fully_random_weights] ( identifier[n_features] , identifier[lam_scale] , identifier[prng] ):
literal[string]
identifier[weights] = identifier[np] . identifier[zeros] (( identifier[n_features] , identifier[n_features] ))
identifier[n_off_diag] = identifier[int] (( identifier[n_... | def _fully_random_weights(n_features, lam_scale, prng):
"""Generate a symmetric random matrix with zeros along the diagonal."""
weights = np.zeros((n_features, n_features))
n_off_diag = int((n_features ** 2 - n_features) / 2)
weights[np.triu_indices(n_features, k=1)] = 0.1 * lam_scale * prng.randn(n_off... |
def check_executables():
"""Check if all necessary / recommended executables are installed."""
print("\033[1mCheck executables\033[0m")
required_executables = [utils.get_nntoolkit()]
for executable in required_executables:
path = which(executable)
if path is None:
print("%s .... | def function[check_executables, parameter[]]:
constant[Check if all necessary / recommended executables are installed.]
call[name[print], parameter[constant[[1mCheck executables[0m]]]
variable[required_executables] assign[=] list[[<ast.Call object at 0x7da1b28b8160>]]
for taget[name[ex... | keyword[def] identifier[check_executables] ():
literal[string]
identifier[print] ( literal[string] )
identifier[required_executables] =[ identifier[utils] . identifier[get_nntoolkit] ()]
keyword[for] identifier[executable] keyword[in] identifier[required_executables] :
identifier[path... | def check_executables():
"""Check if all necessary / recommended executables are installed."""
print('\x1b[1mCheck executables\x1b[0m')
required_executables = [utils.get_nntoolkit()]
for executable in required_executables:
path = which(executable)
if path is None:
print('%s .... |
def delete(self, pid, record, key):
"""Handle DELETE deposit file.
Permission required: `update_permission_factory`.
:param pid: Pid object (from url).
:param record: Record object resolved from the pid.
:param key: Unique identifier for the file in the deposit.
"""
... | def function[delete, parameter[self, pid, record, key]]:
constant[Handle DELETE deposit file.
Permission required: `update_permission_factory`.
:param pid: Pid object (from url).
:param record: Record object resolved from the pid.
:param key: Unique identifier for the file in t... | keyword[def] identifier[delete] ( identifier[self] , identifier[pid] , identifier[record] , identifier[key] ):
literal[string]
keyword[try] :
keyword[del] identifier[record] . identifier[files] [ identifier[str] ( identifier[key] )]
identifier[record] . identifier[commit]... | def delete(self, pid, record, key):
"""Handle DELETE deposit file.
Permission required: `update_permission_factory`.
:param pid: Pid object (from url).
:param record: Record object resolved from the pid.
:param key: Unique identifier for the file in the deposit.
"""
try... |
def register_eph_task(self, *args, **kwargs):
"""Register an electron-phonon task."""
kwargs["task_class"] = EphTask
return self.register_task(*args, **kwargs) | def function[register_eph_task, parameter[self]]:
constant[Register an electron-phonon task.]
call[name[kwargs]][constant[task_class]] assign[=] name[EphTask]
return[call[name[self].register_task, parameter[<ast.Starred object at 0x7da1b21861a0>]]] | keyword[def] identifier[register_eph_task] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= identifier[EphTask]
keyword[return] identifier[self] . identifier[register_task] (* identifier[args] ,** identifier[kwargs] ... | def register_eph_task(self, *args, **kwargs):
"""Register an electron-phonon task."""
kwargs['task_class'] = EphTask
return self.register_task(*args, **kwargs) |
def set_limits(self, limits):
"""
Set the limit data to the given list of limits. Limits are
specified as the raw msgpack string representing the limit.
Computes the checksum of the limits; if the checksum is
identical to the current one, no action is taken.
"""
... | def function[set_limits, parameter[self, limits]]:
constant[
Set the limit data to the given list of limits. Limits are
specified as the raw msgpack string representing the limit.
Computes the checksum of the limits; if the checksum is
identical to the current one, no action is ... | keyword[def] identifier[set_limits] ( identifier[self] , identifier[limits] ):
literal[string]
identifier[chksum] = identifier[hashlib] . identifier[md5] ()
keyword[for] identifier[lim] keyword[in] identifier[limits] :
identifier[chksum] . identifier[update] ( ide... | def set_limits(self, limits):
"""
Set the limit data to the given list of limits. Limits are
specified as the raw msgpack string representing the limit.
Computes the checksum of the limits; if the checksum is
identical to the current one, no action is taken.
"""
# First ... |
def update_pipeline(self, pipeline):
'''Updates a pipeline with the provided attributes.
Args:
key required identifier for the pipeline
pipeline StreakPipeline object
return (status code, pipeline_dict)
'''
#req sanity check
payload = None
if type(pipeline) is not StreakPipeline:
return requ... | def function[update_pipeline, parameter[self, pipeline]]:
constant[Updates a pipeline with the provided attributes.
Args:
key required identifier for the pipeline
pipeline StreakPipeline object
return (status code, pipeline_dict)
]
variable[payload] assign[=] constant[None]
if co... | keyword[def] identifier[update_pipeline] ( identifier[self] , identifier[pipeline] ):
literal[string]
identifier[payload] = keyword[None]
keyword[if] identifier[type] ( identifier[pipeline] ) keyword[is] keyword[not] identifier[StreakPipeline] :
keyword[return] identifier[requests] . identifier[... | def update_pipeline(self, pipeline):
"""Updates a pipeline with the provided attributes.
Args:
key required identifier for the pipeline
pipeline StreakPipeline object
return (status code, pipeline_dict)
""" #req sanity check
payload = None
if type(pipeline) is not StreakPipeline:
re... |
def nvmlDeviceGetVbiosVersion(handle):
r"""
/**
* Get VBIOS version of the device.
*
* For all products.
*
* The VBIOS version may change from time to time. It will not exceed 32 characters in length
* (including the NULL terminator). See \ref nvmlConstants::NVML_DEVICE_VBIOS_VERS... | def function[nvmlDeviceGetVbiosVersion, parameter[handle]]:
constant[
/**
* Get VBIOS version of the device.
*
* For all products.
*
* The VBIOS version may change from time to time. It will not exceed 32 characters in length
* (including the NULL terminator). See \ref nvmlCon... | keyword[def] identifier[nvmlDeviceGetVbiosVersion] ( identifier[handle] ):
literal[string]
identifier[c_version] = identifier[create_string_buffer] ( identifier[NVML_DEVICE_VBIOS_VERSION_BUFFER_SIZE] )
identifier[fn] = identifier[_nvmlGetFunctionPointer] ( literal[string] )
identifier[ret] = iden... | def nvmlDeviceGetVbiosVersion(handle):
"""
/**
* Get VBIOS version of the device.
*
* For all products.
*
* The VBIOS version may change from time to time. It will not exceed 32 characters in length
* (including the NULL terminator). See \\ref nvmlConstants::NVML_DEVICE_VBIOS_VERS... |
def last_kstp_from_kper(hds,kper):
""" function to find the last time step (kstp) for a
give stress period (kper) in a modflow head save file.
Parameters
----------
hds : flopy.utils.HeadFile
kper : int
the zero-index stress period number
Returns
-------
kstp : int
... | def function[last_kstp_from_kper, parameter[hds, kper]]:
constant[ function to find the last time step (kstp) for a
give stress period (kper) in a modflow head save file.
Parameters
----------
hds : flopy.utils.HeadFile
kper : int
the zero-index stress period number
Returns
... | keyword[def] identifier[last_kstp_from_kper] ( identifier[hds] , identifier[kper] ):
literal[string]
identifier[kstp] =- literal[int]
keyword[for] identifier[kkstp] , identifier[kkper] keyword[in] identifier[hds] . identifier[kstpkper] :
keyword[if] identifier[kkper] == identifier[k... | def last_kstp_from_kper(hds, kper):
""" function to find the last time step (kstp) for a
give stress period (kper) in a modflow head save file.
Parameters
----------
hds : flopy.utils.HeadFile
kper : int
the zero-index stress period number
Returns
-------
kstp : int
... |
def _DownloadTS05Data(Overwrite=False):
'''
This function will try to download all existing TS05 archives and
extract them in $GEOPACK_PATH/tab.
'''
Year = 1995
Cont = True
OutPath = Globals.DataPath+'tab/'
cmd0 = 'wget -nv --show-progress '
cmd0 += 'http://geo.phys.spbu.ru/~tsyganenko/TS05_data_and_stuff... | def function[_DownloadTS05Data, parameter[Overwrite]]:
constant[
This function will try to download all existing TS05 archives and
extract them in $GEOPACK_PATH/tab.
]
variable[Year] assign[=] constant[1995]
variable[Cont] assign[=] constant[True]
variable[OutPath] assign[=] bina... | keyword[def] identifier[_DownloadTS05Data] ( identifier[Overwrite] = keyword[False] ):
literal[string]
identifier[Year] = literal[int]
identifier[Cont] = keyword[True]
identifier[OutPath] = identifier[Globals] . identifier[DataPath] + literal[string]
identifier[cmd0] = literal[string]
identifier[cmd0... | def _DownloadTS05Data(Overwrite=False):
"""
This function will try to download all existing TS05 archives and
extract them in $GEOPACK_PATH/tab.
"""
Year = 1995
Cont = True
OutPath = Globals.DataPath + 'tab/'
cmd0 = 'wget -nv --show-progress '
cmd0 += 'http://geo.phys.spbu.ru/~tsyganenko... |
def GenerateConfigFile(load_hook, dump_hook, **kwargs) -> ConfigFile:
"""
Generates a ConfigFile object using the specified hooks.
These hooks should be functions, and have one argument.
When a hook is called, the ConfigFile object is passed to it. Use this to load your data from the fd object, or requ... | def function[GenerateConfigFile, parameter[load_hook, dump_hook]]:
constant[
Generates a ConfigFile object using the specified hooks.
These hooks should be functions, and have one argument.
When a hook is called, the ConfigFile object is passed to it. Use this to load your data from the fd object, ... | keyword[def] identifier[GenerateConfigFile] ( identifier[load_hook] , identifier[dump_hook] ,** identifier[kwargs] )-> identifier[ConfigFile] :
literal[string]
keyword[def] identifier[ConfigFileGenerator] ( identifier[filename] , identifier[safe_load] : identifier[bool] = keyword[True] ):
identif... | def GenerateConfigFile(load_hook, dump_hook, **kwargs) -> ConfigFile:
"""
Generates a ConfigFile object using the specified hooks.
These hooks should be functions, and have one argument.
When a hook is called, the ConfigFile object is passed to it. Use this to load your data from the fd object, or requ... |
def computers(self, base_dn, samaccountnames=(), attributes=()):
"""Gathers a list of ADComputer objects
:param str base_dn: The base DN to search within
:param list samaccountnames: A list of computer names for which objects will be
created, defaults to all computers if unspecified... | def function[computers, parameter[self, base_dn, samaccountnames, attributes]]:
constant[Gathers a list of ADComputer objects
:param str base_dn: The base DN to search within
:param list samaccountnames: A list of computer names for which objects will be
created, defaults to all com... | keyword[def] identifier[computers] ( identifier[self] , identifier[base_dn] , identifier[samaccountnames] =(), identifier[attributes] =()):
literal[string]
identifier[ad_computers] =[]
identifier[search_filter] = literal[string]
keyword[if] keyword[not] ident... | def computers(self, base_dn, samaccountnames=(), attributes=()):
"""Gathers a list of ADComputer objects
:param str base_dn: The base DN to search within
:param list samaccountnames: A list of computer names for which objects will be
created, defaults to all computers if unspecified
... |
def remove_multizone(self, group_uuid):
""" Stop managing a group """
group_uuid = str(group_uuid)
group = self._groups.pop(group_uuid, None)
# Inform all group members that they are no longer members
if group is not None:
group['listener']._mz.reset_members() # noqa... | def function[remove_multizone, parameter[self, group_uuid]]:
constant[ Stop managing a group ]
variable[group_uuid] assign[=] call[name[str], parameter[name[group_uuid]]]
variable[group] assign[=] call[name[self]._groups.pop, parameter[name[group_uuid], constant[None]]]
if compare[name[g... | keyword[def] identifier[remove_multizone] ( identifier[self] , identifier[group_uuid] ):
literal[string]
identifier[group_uuid] = identifier[str] ( identifier[group_uuid] )
identifier[group] = identifier[self] . identifier[_groups] . identifier[pop] ( identifier[group_uuid] , keyword[None]... | def remove_multizone(self, group_uuid):
""" Stop managing a group """
group_uuid = str(group_uuid)
group = self._groups.pop(group_uuid, None)
# Inform all group members that they are no longer members
if group is not None:
group['listener']._mz.reset_members() # noqa: E501 pylint: disable=p... |
def fixed_point_quantize(x, sign=True, n=8, delta=2**-4, quantize=True, ste_fine_grained=True, outputs=None):
r"""Fixed Point Quantize
Args:
x (Variable): An input variable.
sign (bool): Indicate the signed number or the unsigned number. Default is true.
n (int): Bit width used. Note th... | def function[fixed_point_quantize, parameter[x, sign, n, delta, quantize, ste_fine_grained, outputs]]:
constant[Fixed Point Quantize
Args:
x (Variable): An input variable.
sign (bool): Indicate the signed number or the unsigned number. Default is true.
n (int): Bit width used. Note ... | keyword[def] identifier[fixed_point_quantize] ( identifier[x] , identifier[sign] = keyword[True] , identifier[n] = literal[int] , identifier[delta] = literal[int] **- literal[int] , identifier[quantize] = keyword[True] , identifier[ste_fine_grained] = keyword[True] , identifier[outputs] = keyword[None] ):
litera... | def fixed_point_quantize(x, sign=True, n=8, delta=2 ** (-4), quantize=True, ste_fine_grained=True, outputs=None):
"""Fixed Point Quantize
Args:
x (Variable): An input variable.
sign (bool): Indicate the signed number or the unsigned number. Default is true.
n (int): Bit width used. Note... |
def rm_blanks(self):
"""
Get rid of parameters that has no value.
"""
_blanks = [k for k in self._dict.keys() if not self._dict[k]]
for key in _blanks:
del self._dict[key] | def function[rm_blanks, parameter[self]]:
constant[
Get rid of parameters that has no value.
]
variable[_blanks] assign[=] <ast.ListComp object at 0x7da20c6c6e60>
for taget[name[key]] in starred[name[_blanks]] begin[:]
<ast.Delete object at 0x7da20c6c50c0> | keyword[def] identifier[rm_blanks] ( identifier[self] ):
literal[string]
identifier[_blanks] =[ identifier[k] keyword[for] identifier[k] keyword[in] identifier[self] . identifier[_dict] . identifier[keys] () keyword[if] keyword[not] identifier[self] . identifier[_dict] [ identifier[k] ]]
... | def rm_blanks(self):
"""
Get rid of parameters that has no value.
"""
_blanks = [k for k in self._dict.keys() if not self._dict[k]]
for key in _blanks:
del self._dict[key] # depends on [control=['for'], data=['key']] |
def _rename_full_name(self, full_name, other_trajectory, used_runs=None, new_run_idx=None):
"""Renames a full name based on the wildcards and a particular run"""
split_name = full_name.split('.')
for idx, name in enumerate(split_name):
if name in other_trajectory._reversed_wildcards:... | def function[_rename_full_name, parameter[self, full_name, other_trajectory, used_runs, new_run_idx]]:
constant[Renames a full name based on the wildcards and a particular run]
variable[split_name] assign[=] call[name[full_name].split, parameter[constant[.]]]
for taget[tuple[[<ast.Name object at... | keyword[def] identifier[_rename_full_name] ( identifier[self] , identifier[full_name] , identifier[other_trajectory] , identifier[used_runs] = keyword[None] , identifier[new_run_idx] = keyword[None] ):
literal[string]
identifier[split_name] = identifier[full_name] . identifier[split] ( literal[stri... | def _rename_full_name(self, full_name, other_trajectory, used_runs=None, new_run_idx=None):
"""Renames a full name based on the wildcards and a particular run"""
split_name = full_name.split('.')
for (idx, name) in enumerate(split_name):
if name in other_trajectory._reversed_wildcards:
(... |
def delete(self, **kwargs):
"""
Used for deleting objects from the facebook graph. Just pass the id of the object to be
deleted. But in case of like, have to pass the cat ("likes") and object id as a like has no id
itself in the facebook graph
... | def function[delete, parameter[self]]:
constant[
Used for deleting objects from the facebook graph. Just pass the id of the object to be
deleted. But in case of like, have to pass the cat ("likes") and object id as a like has no id
itself in the facebook graph
... | keyword[def] identifier[delete] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[kwargs] . identifier[keys] ():
identifier[kwargs] [ literal[string] ]= literal[string]
... | def delete(self, **kwargs):
"""
Used for deleting objects from the facebook graph. Just pass the id of the object to be
deleted. But in case of like, have to pass the cat ("likes") and object id as a like has no id
itself in the facebook graph
"""
... |
def add_isoquant_data(peptides, quantpeptides, quantacc, quantfields):
"""Runs through a peptide table and adds quant data from ANOTHER peptide
table that contains that data."""
for peptide in base_add_isoquant_data(peptides, quantpeptides,
peptabledata.HEADER_PEP... | def function[add_isoquant_data, parameter[peptides, quantpeptides, quantacc, quantfields]]:
constant[Runs through a peptide table and adds quant data from ANOTHER peptide
table that contains that data.]
for taget[name[peptide]] in starred[call[name[base_add_isoquant_data], parameter[name[peptides],... | keyword[def] identifier[add_isoquant_data] ( identifier[peptides] , identifier[quantpeptides] , identifier[quantacc] , identifier[quantfields] ):
literal[string]
keyword[for] identifier[peptide] keyword[in] identifier[base_add_isoquant_data] ( identifier[peptides] , identifier[quantpeptides] ,
iden... | def add_isoquant_data(peptides, quantpeptides, quantacc, quantfields):
"""Runs through a peptide table and adds quant data from ANOTHER peptide
table that contains that data."""
for peptide in base_add_isoquant_data(peptides, quantpeptides, peptabledata.HEADER_PEPTIDE, quantacc, quantfields):
yield... |
def takeTag( self, tag ):
"""
Removes the inputed tag from the system.
:param tag | <str>
:return <XMultiTagItem> || None
"""
for row in range(self.count() - 1):
item = self.item(row)
if ( item and item.text() =... | def function[takeTag, parameter[self, tag]]:
constant[
Removes the inputed tag from the system.
:param tag | <str>
:return <XMultiTagItem> || None
]
for taget[name[row]] in starred[call[name[range], parameter[binary_operation[call[name[self].cou... | keyword[def] identifier[takeTag] ( identifier[self] , identifier[tag] ):
literal[string]
keyword[for] identifier[row] keyword[in] identifier[range] ( identifier[self] . identifier[count] ()- literal[int] ):
identifier[item] = identifier[self] . identifier[item] ( identifier[row] ... | def takeTag(self, tag):
"""
Removes the inputed tag from the system.
:param tag | <str>
:return <XMultiTagItem> || None
"""
for row in range(self.count() - 1):
item = self.item(row)
if item and item.text() == tag:
self.takeIt... |
def go_to_previous_tab(self):
"""
Focus the previous tab.
"""
self.active_tab_index = (self.active_tab_index - 1 +
len(self.tab_pages)) % len(self.tab_pages) | def function[go_to_previous_tab, parameter[self]]:
constant[
Focus the previous tab.
]
name[self].active_tab_index assign[=] binary_operation[binary_operation[binary_operation[name[self].active_tab_index - constant[1]] + call[name[len], parameter[name[self].tab_pages]]] <ast.Mod object a... | keyword[def] identifier[go_to_previous_tab] ( identifier[self] ):
literal[string]
identifier[self] . identifier[active_tab_index] =( identifier[self] . identifier[active_tab_index] - literal[int] +
identifier[len] ( identifier[self] . identifier[tab_pages] ))% identifier[len] ( identifier[... | def go_to_previous_tab(self):
"""
Focus the previous tab.
"""
self.active_tab_index = (self.active_tab_index - 1 + len(self.tab_pages)) % len(self.tab_pages) |
def startup(name):
'''
Start Traffic Server on the local node.
.. code-block:: yaml
startup_ats:
trafficserver.startup
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if __opts__['test']:
ret['comment'] = 'Start... | def function[startup, parameter[name]]:
constant[
Start Traffic Server on the local node.
.. code-block:: yaml
startup_ats:
trafficserver.startup
]
variable[ret] assign[=] dictionary[[<ast.Constant object at 0x7da20c7ca230>, <ast.Constant object at 0x7da20c7c9b40>, <ast.C... | keyword[def] identifier[startup] ( identifier[name] ):
literal[string]
identifier[ret] ={ literal[string] : identifier[name] ,
literal[string] :{},
literal[string] : keyword[None] ,
literal[string] : literal[string] }
keyword[if] identifier[__opts__] [ literal[string] ]:
iden... | def startup(name):
"""
Start Traffic Server on the local node.
.. code-block:: yaml
startup_ats:
trafficserver.startup
"""
ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''}
if __opts__['test']:
ret['comment'] = 'Starting up local node'
return ... |
def otsu (img, bins=64):
r"""
Otsu's method to find the optimal threshold separating an image into fore- and background.
This rather expensive method iterates over a number of thresholds to separate the
images histogram into two parts with a minimal intra-class variance.
An increase in the... | def function[otsu, parameter[img, bins]]:
constant[
Otsu's method to find the optimal threshold separating an image into fore- and background.
This rather expensive method iterates over a number of thresholds to separate the
images histogram into two parts with a minimal intra-class variance.
... | keyword[def] identifier[otsu] ( identifier[img] , identifier[bins] = literal[int] ):
literal[string]
identifier[bins] = identifier[int] ( identifier[bins] )
identifier[img] = identifier[numpy] . identifier[asarray] ( identifier[img] )
keyword[if] identifier[bins] <= literal[int]... | def otsu(img, bins=64):
"""
Otsu's method to find the optimal threshold separating an image into fore- and background.
This rather expensive method iterates over a number of thresholds to separate the
images histogram into two parts with a minimal intra-class variance.
An increase in the n... |
def get_zone_info(cls, area_str, match_type='EXACT', result_type='LIST'):
"""
输入包含省份、城市、地区信息的内容,返回地区编号;
:param:
* area_str: (string) 要查询的区域,省份、城市、地区信息,比如 北京市
* match_type: (string) 查询匹配模式,默认值 'EXACT',表示精确匹配,可选 'FUZZY',表示模糊查询
* result_type: (string) 返回结果数量类型,默... | def function[get_zone_info, parameter[cls, area_str, match_type, result_type]]:
constant[
输入包含省份、城市、地区信息的内容,返回地区编号;
:param:
* area_str: (string) 要查询的区域,省份、城市、地区信息,比如 北京市
* match_type: (string) 查询匹配模式,默认值 'EXACT',表示精确匹配,可选 'FUZZY',表示模糊查询
* result_type: (string... | keyword[def] identifier[get_zone_info] ( identifier[cls] , identifier[area_str] , identifier[match_type] = literal[string] , identifier[result_type] = literal[string] ):
literal[string]
identifier[values] =[]
keyword[if] identifier[match_type] == literal[string] :
identifier... | def get_zone_info(cls, area_str, match_type='EXACT', result_type='LIST'):
"""
输入包含省份、城市、地区信息的内容,返回地区编号;
:param:
* area_str: (string) 要查询的区域,省份、城市、地区信息,比如 北京市
* match_type: (string) 查询匹配模式,默认值 'EXACT',表示精确匹配,可选 'FUZZY',表示模糊查询
* result_type: (string) 返回结果数量类型,默认值 '... |
def docker_inspect(image):
'''Inspects a docker image
Returns: Parsed JSON data
'''
args = ['docker', 'inspect', '--type', 'image', image]
p = Popen(args, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
stdout, stderr = p.communicate()
stdout = stdout.decode('utf-8')
stderr = stder... | def function[docker_inspect, parameter[image]]:
constant[Inspects a docker image
Returns: Parsed JSON data
]
variable[args] assign[=] list[[<ast.Constant object at 0x7da1b0d8b250>, <ast.Constant object at 0x7da1b0d8b910>, <ast.Constant object at 0x7da1b0d88ac0>, <ast.Constant object at 0x7da1b0... | keyword[def] identifier[docker_inspect] ( identifier[image] ):
literal[string]
identifier[args] =[ literal[string] , literal[string] , literal[string] , literal[string] , identifier[image] ]
identifier[p] = identifier[Popen] ( identifier[args] , identifier[stdout] = identifier[subprocess] . identifier... | def docker_inspect(image):
"""Inspects a docker image
Returns: Parsed JSON data
"""
args = ['docker', 'inspect', '--type', 'image', image]
p = Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = p.communicate()
stdout = stdout.decode('utf-8')
stderr = stderr.d... |
def _apply_aeff_corrections(intensity_map, aeff_corrections):
""" Multipy a map by the effective area correction
"""
data = aeff_corrections * intensity_map.data.T
return HpxMap(data.T, intensity_map.hpx) | def function[_apply_aeff_corrections, parameter[intensity_map, aeff_corrections]]:
constant[ Multipy a map by the effective area correction
]
variable[data] assign[=] binary_operation[name[aeff_corrections] * name[intensity_map].data.T]
return[call[name[HpxMap], parameter[name[data].T, name[... | keyword[def] identifier[_apply_aeff_corrections] ( identifier[intensity_map] , identifier[aeff_corrections] ):
literal[string]
identifier[data] = identifier[aeff_corrections] * identifier[intensity_map] . identifier[data] . identifier[T]
keyword[return] identifier[HpxMap] ( identifier[da... | def _apply_aeff_corrections(intensity_map, aeff_corrections):
""" Multipy a map by the effective area correction
"""
data = aeff_corrections * intensity_map.data.T
return HpxMap(data.T, intensity_map.hpx) |
def _patched_run_hook(hook_name, project_dir, context):
"""Used to patch cookiecutter's ``run_hook`` function.
This patched version ensures that the temple.yaml file is created before
any cookiecutter hooks are executed
"""
if hook_name == 'post_gen_project':
with temple.utils.cd(project_di... | def function[_patched_run_hook, parameter[hook_name, project_dir, context]]:
constant[Used to patch cookiecutter's ``run_hook`` function.
This patched version ensures that the temple.yaml file is created before
any cookiecutter hooks are executed
]
if compare[name[hook_name] equal[==] const... | keyword[def] identifier[_patched_run_hook] ( identifier[hook_name] , identifier[project_dir] , identifier[context] ):
literal[string]
keyword[if] identifier[hook_name] == literal[string] :
keyword[with] identifier[temple] . identifier[utils] . identifier[cd] ( identifier[project_dir] ):
... | def _patched_run_hook(hook_name, project_dir, context):
"""Used to patch cookiecutter's ``run_hook`` function.
This patched version ensures that the temple.yaml file is created before
any cookiecutter hooks are executed
"""
if hook_name == 'post_gen_project':
with temple.utils.cd(project_di... |
def connect(self):
"""
make amqp connection and create channels and queue binding
"""
self.connection = pika.BlockingConnection(BLOCKING_MQ_PARAMS)
self.client_queue = ClientQueue()
self.input_channel = self.connection.channel()
self.input_channel.exchange_declar... | def function[connect, parameter[self]]:
constant[
make amqp connection and create channels and queue binding
]
name[self].connection assign[=] call[name[pika].BlockingConnection, parameter[name[BLOCKING_MQ_PARAMS]]]
name[self].client_queue assign[=] call[name[ClientQueue], parame... | keyword[def] identifier[connect] ( identifier[self] ):
literal[string]
identifier[self] . identifier[connection] = identifier[pika] . identifier[BlockingConnection] ( identifier[BLOCKING_MQ_PARAMS] )
identifier[self] . identifier[client_queue] = identifier[ClientQueue] ()
identifi... | def connect(self):
"""
make amqp connection and create channels and queue binding
"""
self.connection = pika.BlockingConnection(BLOCKING_MQ_PARAMS)
self.client_queue = ClientQueue()
self.input_channel = self.connection.channel()
self.input_channel.exchange_declare(exchange=self.INPUT... |
def check_url (aggregate):
"""Helper function waiting for URL queue."""
while True:
try:
aggregate.urlqueue.join(timeout=30)
break
except urlqueue.Timeout:
# Cleanup threads every 30 seconds
aggregate.remove_stopped_threads()
if not any... | def function[check_url, parameter[aggregate]]:
constant[Helper function waiting for URL queue.]
while constant[True] begin[:]
<ast.Try object at 0x7da1b2345f00> | keyword[def] identifier[check_url] ( identifier[aggregate] ):
literal[string]
keyword[while] keyword[True] :
keyword[try] :
identifier[aggregate] . identifier[urlqueue] . identifier[join] ( identifier[timeout] = literal[int] )
keyword[break]
keyword[except] id... | def check_url(aggregate):
"""Helper function waiting for URL queue."""
while True:
try:
aggregate.urlqueue.join(timeout=30)
break # depends on [control=['try'], data=[]]
except urlqueue.Timeout:
# Cleanup threads every 30 seconds
aggregate.remove_... |
def json_qry(dataset, qry_str, params={}):
""" Takes a json query string and returns the results
args:
dataset: RdfDataset to query against
qry_str: query string
params: dictionary of params
"""
# if qry_str.startswith("$.bf_itemOf[rdf_type=bf_Print].='print',\n"):
# pdb... | def function[json_qry, parameter[dataset, qry_str, params]]:
constant[ Takes a json query string and returns the results
args:
dataset: RdfDataset to query against
qry_str: query string
params: dictionary of params
]
if <ast.UnaryOp object at 0x7da20c6a86d0> begin[:]
... | keyword[def] identifier[json_qry] ( identifier[dataset] , identifier[qry_str] , identifier[params] ={}):
literal[string]
keyword[if] keyword[not] literal[string] keyword[in] identifier[qry_str] :
identifier[qry_str] = literal[string] . identifier[join] ([ literal[string] , identifier... | def json_qry(dataset, qry_str, params={}):
""" Takes a json query string and returns the results
args:
dataset: RdfDataset to query against
qry_str: query string
params: dictionary of params
"""
# if qry_str.startswith("$.bf_itemOf[rdf_type=bf_Print].='print',\n"):
# pdb... |
def centerOnDateTime(self, dtime):
"""
Centers the view on a given datetime for the gantt widget.
:param dtime | <QDateTime>
"""
view = self.uiGanttVIEW
scene = view.scene()
point = view.mapToScene(0, 0)
x = scene.datetimeXPos(dtime)... | def function[centerOnDateTime, parameter[self, dtime]]:
constant[
Centers the view on a given datetime for the gantt widget.
:param dtime | <QDateTime>
]
variable[view] assign[=] name[self].uiGanttVIEW
variable[scene] assign[=] call[name[view].scene, paramet... | keyword[def] identifier[centerOnDateTime] ( identifier[self] , identifier[dtime] ):
literal[string]
identifier[view] = identifier[self] . identifier[uiGanttVIEW]
identifier[scene] = identifier[view] . identifier[scene] ()
identifier[point] = identifier[view] . identifier[mapT... | def centerOnDateTime(self, dtime):
"""
Centers the view on a given datetime for the gantt widget.
:param dtime | <QDateTime>
"""
view = self.uiGanttVIEW
scene = view.scene()
point = view.mapToScene(0, 0)
x = scene.datetimeXPos(dtime)
y = point.y()
view.c... |
def get_messages(self,
statuses=DEFAULT_MESSAGE_STATUSES,
order="sent_at desc",
offset=None,
count=None,
content=False):
"""Returns a list of messages your account sent.
Messages are sorted by ``order``, starting at an optional integer... | def function[get_messages, parameter[self, statuses, order, offset, count, content]]:
constant[Returns a list of messages your account sent.
Messages are sorted by ``order``, starting at an optional integer ``offset``, and optionally limited to the first ``count`` items (in sorted order).
... | keyword[def] identifier[get_messages] ( identifier[self] ,
identifier[statuses] = identifier[DEFAULT_MESSAGE_STATUSES] ,
identifier[order] = literal[string] ,
identifier[offset] = keyword[None] ,
identifier[count] = keyword[None] ,
identifier[content] = keyword[False] ):
literal[string]
ident... | def get_messages(self, statuses=DEFAULT_MESSAGE_STATUSES, order='sent_at desc', offset=None, count=None, content=False):
"""Returns a list of messages your account sent.
Messages are sorted by ``order``, starting at an optional integer ``offset``, and optionally limited to the first ``count`` items... |
def image_information_response(self):
"""Parse image information request and create response."""
dr = degraded_request(self.identifier)
if (dr):
self.logger.info("image_information: degraded %s -> %s" %
(self.identifier, dr))
self.degraded = s... | def function[image_information_response, parameter[self]]:
constant[Parse image information request and create response.]
variable[dr] assign[=] call[name[degraded_request], parameter[name[self].identifier]]
if name[dr] begin[:]
call[name[self].logger.info, parameter[binary_opera... | keyword[def] identifier[image_information_response] ( identifier[self] ):
literal[string]
identifier[dr] = identifier[degraded_request] ( identifier[self] . identifier[identifier] )
keyword[if] ( identifier[dr] ):
identifier[self] . identifier[logger] . identifier[info] ( lite... | def image_information_response(self):
"""Parse image information request and create response."""
dr = degraded_request(self.identifier)
if dr:
self.logger.info('image_information: degraded %s -> %s' % (self.identifier, dr))
self.degraded = self.identifier
self.identifier = dr # depe... |
def gcd_float(numbers, tol=1e-8):
"""
Returns the greatest common divisor for a sequence of numbers.
Uses a numerical tolerance, so can be used on floats
Args:
numbers: Sequence of numbers.
tol: Numerical tolerance
Returns:
(int) Greatest common divisor of numbers.
"""
... | def function[gcd_float, parameter[numbers, tol]]:
constant[
Returns the greatest common divisor for a sequence of numbers.
Uses a numerical tolerance, so can be used on floats
Args:
numbers: Sequence of numbers.
tol: Numerical tolerance
Returns:
(int) Greatest common di... | keyword[def] identifier[gcd_float] ( identifier[numbers] , identifier[tol] = literal[int] ):
literal[string]
keyword[def] identifier[pair_gcd_tol] ( identifier[a] , identifier[b] ):
literal[string]
keyword[while] identifier[b] > identifier[tol] :
identifier[a] , identifie... | def gcd_float(numbers, tol=1e-08):
"""
Returns the greatest common divisor for a sequence of numbers.
Uses a numerical tolerance, so can be used on floats
Args:
numbers: Sequence of numbers.
tol: Numerical tolerance
Returns:
(int) Greatest common divisor of numbers.
"""... |
def map_run(self, path=None, **kwargs):
'''
To execute a map
'''
kwarg = {}
if path:
kwarg['map'] = path
kwarg.update(kwargs)
mapper = salt.cloud.Map(self._opts_defaults(**kwarg))
dmap = mapper.map_data()
return salt.utils.data.simple_t... | def function[map_run, parameter[self, path]]:
constant[
To execute a map
]
variable[kwarg] assign[=] dictionary[[], []]
if name[path] begin[:]
call[name[kwarg]][constant[map]] assign[=] name[path]
call[name[kwarg].update, parameter[name[kwargs]]]
v... | keyword[def] identifier[map_run] ( identifier[self] , identifier[path] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[kwarg] ={}
keyword[if] identifier[path] :
identifier[kwarg] [ literal[string] ]= identifier[path]
identifier[kwarg] . identifi... | def map_run(self, path=None, **kwargs):
"""
To execute a map
"""
kwarg = {}
if path:
kwarg['map'] = path # depends on [control=['if'], data=[]]
kwarg.update(kwargs)
mapper = salt.cloud.Map(self._opts_defaults(**kwarg))
dmap = mapper.map_data()
return salt.utils.data.... |
def create_new_sticker_set(self, user_id, name, title, png_sticker, emojis, contains_masks=None, mask_position=None):
"""
Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. Returns True on success.
https://core.telegram.org/bots/api#... | def function[create_new_sticker_set, parameter[self, user_id, name, title, png_sticker, emojis, contains_masks, mask_position]]:
constant[
Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. Returns True on success.
https://core.teleg... | keyword[def] identifier[create_new_sticker_set] ( identifier[self] , identifier[user_id] , identifier[name] , identifier[title] , identifier[png_sticker] , identifier[emojis] , identifier[contains_masks] = keyword[None] , identifier[mask_position] = keyword[None] ):
literal[string]
keyword[from] i... | def create_new_sticker_set(self, user_id, name, title, png_sticker, emojis, contains_masks=None, mask_position=None):
"""
Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. Returns True on success.
https://core.telegram.org/bots/api#crea... |
def get_status(self, response, finished=False):
"""Given the stdout from the command returned by :meth:`cmd_status`,
return one of the status code defined in :mod:`clusterjob.status`"""
for line in response.split("\n"):
if line.strip() in self.status_mapping:
return s... | def function[get_status, parameter[self, response, finished]]:
constant[Given the stdout from the command returned by :meth:`cmd_status`,
return one of the status code defined in :mod:`clusterjob.status`]
for taget[name[line]] in starred[call[name[response].split, parameter[constant[
]]]] begin[... | keyword[def] identifier[get_status] ( identifier[self] , identifier[response] , identifier[finished] = keyword[False] ):
literal[string]
keyword[for] identifier[line] keyword[in] identifier[response] . identifier[split] ( literal[string] ):
keyword[if] identifier[line] . identifier... | def get_status(self, response, finished=False):
"""Given the stdout from the command returned by :meth:`cmd_status`,
return one of the status code defined in :mod:`clusterjob.status`"""
for line in response.split('\n'):
if line.strip() in self.status_mapping:
return self.status_mappi... |
def stop_consuming(self):
"""Stop consuming messages.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
if not self.consumer... | def function[stop_consuming, parameter[self]]:
constant[Stop consuming messages.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
]
... | keyword[def] identifier[stop_consuming] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[consumer_tags] :
keyword[return]
keyword[if] keyword[not] identifier[self] . identifier[is_closed] :
keyword[for] identifier[... | def stop_consuming(self):
"""Stop consuming messages.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
if not self.consumer_tags:
... |
def simple_generate(cls, create, **kwargs):
"""Generate a new instance.
The instance will be either 'built' or 'created'.
Args:
create (bool): whether to 'build' or 'create' the instance.
Returns:
object: the generated instance
"""
strategy = en... | def function[simple_generate, parameter[cls, create]]:
constant[Generate a new instance.
The instance will be either 'built' or 'created'.
Args:
create (bool): whether to 'build' or 'create' the instance.
Returns:
object: the generated instance
]
... | keyword[def] identifier[simple_generate] ( identifier[cls] , identifier[create] ,** identifier[kwargs] ):
literal[string]
identifier[strategy] = identifier[enums] . identifier[CREATE_STRATEGY] keyword[if] identifier[create] keyword[else] identifier[enums] . identifier[BUILD_STRATEGY]
... | def simple_generate(cls, create, **kwargs):
"""Generate a new instance.
The instance will be either 'built' or 'created'.
Args:
create (bool): whether to 'build' or 'create' the instance.
Returns:
object: the generated instance
"""
strategy = enums.CREA... |
def apply_to_structure(self, structure):
"""
Apply the deformation gradient to a structure.
Args:
structure (Structure object): the structure object to
be modified by the deformation
"""
def_struct = structure.copy()
old_latt = def_struct.latt... | def function[apply_to_structure, parameter[self, structure]]:
constant[
Apply the deformation gradient to a structure.
Args:
structure (Structure object): the structure object to
be modified by the deformation
]
variable[def_struct] assign[=] call[nam... | keyword[def] identifier[apply_to_structure] ( identifier[self] , identifier[structure] ):
literal[string]
identifier[def_struct] = identifier[structure] . identifier[copy] ()
identifier[old_latt] = identifier[def_struct] . identifier[lattice] . identifier[matrix]
identifier[new_l... | def apply_to_structure(self, structure):
"""
Apply the deformation gradient to a structure.
Args:
structure (Structure object): the structure object to
be modified by the deformation
"""
def_struct = structure.copy()
old_latt = def_struct.lattice.matrix
... |
def spkw15(handle, body, center, inframe, first, last, segid, epoch, tp, pa, p,
ecc, j2flg, pv, gm, j2, radius):
"""
Write an SPK segment of type 15 given a type 15 data record.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw15_c.html
:param handle: Handle of an SPK file open f... | def function[spkw15, parameter[handle, body, center, inframe, first, last, segid, epoch, tp, pa, p, ecc, j2flg, pv, gm, j2, radius]]:
constant[
Write an SPK segment of type 15 given a type 15 data record.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw15_c.html
:param handle: Handle o... | keyword[def] identifier[spkw15] ( identifier[handle] , identifier[body] , identifier[center] , identifier[inframe] , identifier[first] , identifier[last] , identifier[segid] , identifier[epoch] , identifier[tp] , identifier[pa] , identifier[p] ,
identifier[ecc] , identifier[j2flg] , identifier[pv] , identifier[gm] ,... | def spkw15(handle, body, center, inframe, first, last, segid, epoch, tp, pa, p, ecc, j2flg, pv, gm, j2, radius):
"""
Write an SPK segment of type 15 given a type 15 data record.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw15_c.html
:param handle: Handle of an SPK file open for writing.... |
def rebuild_auth(self, prepared_request, response):
"""
When being redirected we should always strip Authorization
header, since nonce may not be reused as per OAuth spec.
"""
if "Authorization" in prepared_request.headers:
# If we get redirected to a new host, we sho... | def function[rebuild_auth, parameter[self, prepared_request, response]]:
constant[
When being redirected we should always strip Authorization
header, since nonce may not be reused as per OAuth spec.
]
if compare[constant[Authorization] in name[prepared_request].headers] begin[:]
... | keyword[def] identifier[rebuild_auth] ( identifier[self] , identifier[prepared_request] , identifier[response] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[prepared_request] . identifier[headers] :
identifier[prepared_request] . identifier[... | def rebuild_auth(self, prepared_request, response):
"""
When being redirected we should always strip Authorization
header, since nonce may not be reused as per OAuth spec.
"""
if 'Authorization' in prepared_request.headers:
# If we get redirected to a new host, we should strip ou... |
def _is_gs_folder(cls, result):
"""Return ``True`` if GS standalone folder object.
GS will create a 0 byte ``<FOLDER NAME>_$folder$`` key as a
pseudo-directory place holder if there are no files present.
"""
return (cls.is_key(result) and
result.size == 0 and
... | def function[_is_gs_folder, parameter[cls, result]]:
constant[Return ``True`` if GS standalone folder object.
GS will create a 0 byte ``<FOLDER NAME>_$folder$`` key as a
pseudo-directory place holder if there are no files present.
]
return[<ast.BoolOp object at 0x7da18f00f1c0>] | keyword[def] identifier[_is_gs_folder] ( identifier[cls] , identifier[result] ):
literal[string]
keyword[return] ( identifier[cls] . identifier[is_key] ( identifier[result] ) keyword[and]
identifier[result] . identifier[size] == literal[int] keyword[and]
identifier[result] . id... | def _is_gs_folder(cls, result):
"""Return ``True`` if GS standalone folder object.
GS will create a 0 byte ``<FOLDER NAME>_$folder$`` key as a
pseudo-directory place holder if there are no files present.
"""
return cls.is_key(result) and result.size == 0 and result.name.endswith(cls._gs... |
def rotate(obj, angle, **kwargs):
""" Rotates curves, surfaces or volumes about the chosen axis.
Keyword Arguments:
* ``axis``: rotation axis; x, y, z correspond to 0, 1, 2 respectively. *Default: 2*
* ``inplace``: if False, operation applied to a copy of the object. *Default: False*
:para... | def function[rotate, parameter[obj, angle]]:
constant[ Rotates curves, surfaces or volumes about the chosen axis.
Keyword Arguments:
* ``axis``: rotation axis; x, y, z correspond to 0, 1, 2 respectively. *Default: 2*
* ``inplace``: if False, operation applied to a copy of the object. *Defau... | keyword[def] identifier[rotate] ( identifier[obj] , identifier[angle] ,** identifier[kwargs] ):
literal[string]
keyword[def] identifier[rotate_x] ( identifier[ncs] , identifier[opt] , identifier[alpha] ):
identifier[translate_vector] = identifier[linalg] . identifier[vector_generate] ( ident... | def rotate(obj, angle, **kwargs):
""" Rotates curves, surfaces or volumes about the chosen axis.
Keyword Arguments:
* ``axis``: rotation axis; x, y, z correspond to 0, 1, 2 respectively. *Default: 2*
* ``inplace``: if False, operation applied to a copy of the object. *Default: False*
:para... |
def namespace_uri(self, name):
"""
:param string name: the name of an attribute to look up.
:return: the namespace URI associated with the named attribute,
or None.
"""
a_node = self.adapter.get_node_attribute_node(self.impl_element, name)
if a_node is None:
... | def function[namespace_uri, parameter[self, name]]:
constant[
:param string name: the name of an attribute to look up.
:return: the namespace URI associated with the named attribute,
or None.
]
variable[a_node] assign[=] call[name[self].adapter.get_node_attribute_nod... | keyword[def] identifier[namespace_uri] ( identifier[self] , identifier[name] ):
literal[string]
identifier[a_node] = identifier[self] . identifier[adapter] . identifier[get_node_attribute_node] ( identifier[self] . identifier[impl_element] , identifier[name] )
keyword[if] identifier[a_nod... | def namespace_uri(self, name):
"""
:param string name: the name of an attribute to look up.
:return: the namespace URI associated with the named attribute,
or None.
"""
a_node = self.adapter.get_node_attribute_node(self.impl_element, name)
if a_node is None:
retu... |
def addCompletedJob(self, job, wallTime):
"""
Adds the shape of a completed job to the queue, allowing the scalar to use the last N
completed jobs in factoring how many nodes are required in the cluster.
:param toil.job.JobNode job: The memory, core and disk requirements of the completed... | def function[addCompletedJob, parameter[self, job, wallTime]]:
constant[
Adds the shape of a completed job to the queue, allowing the scalar to use the last N
completed jobs in factoring how many nodes are required in the cluster.
:param toil.job.JobNode job: The memory, core and disk re... | keyword[def] identifier[addCompletedJob] ( identifier[self] , identifier[job] , identifier[wallTime] ):
literal[string]
keyword[if] identifier[job] . identifier[jobName] keyword[in] identifier[self] . identifier[jobNameToAvgRuntime] :
identifier[prevAvg] = identifier[self]... | def addCompletedJob(self, job, wallTime):
"""
Adds the shape of a completed job to the queue, allowing the scalar to use the last N
completed jobs in factoring how many nodes are required in the cluster.
:param toil.job.JobNode job: The memory, core and disk requirements of the completed job... |
def plot(self, type="roc", server=False):
"""
Produce the desired metric plot.
:param type: the type of metric plot (currently, only ROC supported).
:param server: if True, generate plot inline using matplotlib's "Agg" backend.
:returns: None
"""
# TODO: add more... | def function[plot, parameter[self, type, server]]:
constant[
Produce the desired metric plot.
:param type: the type of metric plot (currently, only ROC supported).
:param server: if True, generate plot inline using matplotlib's "Agg" backend.
:returns: None
]
cal... | keyword[def] identifier[plot] ( identifier[self] , identifier[type] = literal[string] , identifier[server] = keyword[False] ):
literal[string]
identifier[assert_is_type] ( identifier[type] , literal[string] )
keyword[try] :
identifier[imp] . identifier[find_m... | def plot(self, type='roc', server=False):
"""
Produce the desired metric plot.
:param type: the type of metric plot (currently, only ROC supported).
:param server: if True, generate plot inline using matplotlib's "Agg" backend.
:returns: None
"""
# TODO: add more types (... |
def butter_filter(cutoff, fs, order=5, btype='low'):
'''Create a digital butter fileter with cutoff frequency in Hz
Args
----
cutoff: float
Cutoff frequency where filter should separate signals
fs: float
sampling frequency
btype: str
Type of filter type to create. 'low' ... | def function[butter_filter, parameter[cutoff, fs, order, btype]]:
constant[Create a digital butter fileter with cutoff frequency in Hz
Args
----
cutoff: float
Cutoff frequency where filter should separate signals
fs: float
sampling frequency
btype: str
Type of filter... | keyword[def] identifier[butter_filter] ( identifier[cutoff] , identifier[fs] , identifier[order] = literal[int] , identifier[btype] = literal[string] ):
literal[string]
keyword[import] identifier[scipy] . identifier[signal]
identifier[nyq] = literal[int] * identifier[fs]
identifier[normal_cut... | def butter_filter(cutoff, fs, order=5, btype='low'):
"""Create a digital butter fileter with cutoff frequency in Hz
Args
----
cutoff: float
Cutoff frequency where filter should separate signals
fs: float
sampling frequency
btype: str
Type of filter type to create. 'low' ... |
def rectangle_props(event):
"""
Returns the width, height, left, and bottom of a rectangle artist.
Parameters
-----------
event : PickEvent
The pick event to process
Returns
--------
A dict with keys:
`width` : The width of the rectangle
`height` : The height of... | def function[rectangle_props, parameter[event]]:
constant[
Returns the width, height, left, and bottom of a rectangle artist.
Parameters
-----------
event : PickEvent
The pick event to process
Returns
--------
A dict with keys:
`width` : The width of the rectangle
... | keyword[def] identifier[rectangle_props] ( identifier[event] ):
literal[string]
identifier[artist] = identifier[event] . identifier[artist]
identifier[width] , identifier[height] = identifier[artist] . identifier[get_width] (), identifier[artist] . identifier[get_height] ()
identifier[left] , id... | def rectangle_props(event):
"""
Returns the width, height, left, and bottom of a rectangle artist.
Parameters
-----------
event : PickEvent
The pick event to process
Returns
--------
A dict with keys:
`width` : The width of the rectangle
`height` : The height of... |
def export_public_keys(self, identities):
"""Export SSH public keys from the device."""
public_keys = []
with self.device:
for i in identities:
pubkey = self.device.pubkey(identity=i)
vk = formats.decompress_pubkey(pubkey=pubkey,
... | def function[export_public_keys, parameter[self, identities]]:
constant[Export SSH public keys from the device.]
variable[public_keys] assign[=] list[[]]
with name[self].device begin[:]
for taget[name[i]] in starred[name[identities]] begin[:]
variable[pubk... | keyword[def] identifier[export_public_keys] ( identifier[self] , identifier[identities] ):
literal[string]
identifier[public_keys] =[]
keyword[with] identifier[self] . identifier[device] :
keyword[for] identifier[i] keyword[in] identifier[identities] :
ide... | def export_public_keys(self, identities):
"""Export SSH public keys from the device."""
public_keys = []
with self.device:
for i in identities:
pubkey = self.device.pubkey(identity=i)
vk = formats.decompress_pubkey(pubkey=pubkey, curve_name=i.curve_name)
public_ke... |
def openStream(self, source):
"""Produces a file object from source.
source can be either a file object, local filename or a string.
"""
# Already a file object
if hasattr(source, 'read'):
stream = source
else:
stream = StringIO(source)
... | def function[openStream, parameter[self, source]]:
constant[Produces a file object from source.
source can be either a file object, local filename or a string.
]
if call[name[hasattr], parameter[name[source], constant[read]]] begin[:]
variable[stream] assign[=] name[sou... | keyword[def] identifier[openStream] ( identifier[self] , identifier[source] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[source] , literal[string] ):
identifier[stream] = identifier[source]
keyword[else] :
identifier[stream] = identif... | def openStream(self, source):
"""Produces a file object from source.
source can be either a file object, local filename or a string.
"""
# Already a file object
if hasattr(source, 'read'):
stream = source # depends on [control=['if'], data=[]]
else:
stream = StringIO(s... |
def warn_message(self, message, fh=None, prefix="[warn]:", suffix="..."):
"""
print warn type message,
if file handle is `sys.stdout`, print color message
:param str message: message to print
:param file fh: file handle,default is `sys.stdout`
:param str prefix: message... | def function[warn_message, parameter[self, message, fh, prefix, suffix]]:
constant[
print warn type message,
if file handle is `sys.stdout`, print color message
:param str message: message to print
:param file fh: file handle,default is `sys.stdout`
:param str prefix: m... | keyword[def] identifier[warn_message] ( identifier[self] , identifier[message] , identifier[fh] = keyword[None] , identifier[prefix] = literal[string] , identifier[suffix] = literal[string] ):
literal[string]
identifier[msg] = identifier[prefix] + identifier[message] + identifier[suffix]
... | def warn_message(self, message, fh=None, prefix='[warn]:', suffix='...'):
"""
print warn type message,
if file handle is `sys.stdout`, print color message
:param str message: message to print
:param file fh: file handle,default is `sys.stdout`
:param str prefix: message pre... |
def DecodeMessages(self, response_comms):
"""Extract and verify server message.
Args:
response_comms: A ClientCommunication rdfvalue
Returns:
list of messages and the CN where they came from.
Raises:
DecryptionError: If the message failed to decrypt properly.
"""
# Have ... | def function[DecodeMessages, parameter[self, response_comms]]:
constant[Extract and verify server message.
Args:
response_comms: A ClientCommunication rdfvalue
Returns:
list of messages and the CN where they came from.
Raises:
DecryptionError: If the message failed to decryp... | keyword[def] identifier[DecodeMessages] ( identifier[self] , identifier[response_comms] ):
literal[string]
identifier[cipher_verified] = keyword[False]
keyword[try] :
identifier[cipher] = identifier[self] . identifier[encrypted_cipher_cache] . identifier[Get] ( identifier[response_comms] ... | def DecodeMessages(self, response_comms):
"""Extract and verify server message.
Args:
response_comms: A ClientCommunication rdfvalue
Returns:
list of messages and the CN where they came from.
Raises:
DecryptionError: If the message failed to decrypt properly.
"""
# Have ... |
def _rhat_ufunc(ary):
"""Ufunc for computing effective sample size.
This can be used on an xarray Dataset, using
`xr.apply_ufunc(_neff_ufunc, ..., input_core_dims=(('chain', 'draw'),))
"""
target = np.empty(ary.shape[:-2])
for idx in np.ndindex(target.shape):
target[idx] = _get_split_rh... | def function[_rhat_ufunc, parameter[ary]]:
constant[Ufunc for computing effective sample size.
This can be used on an xarray Dataset, using
`xr.apply_ufunc(_neff_ufunc, ..., input_core_dims=(('chain', 'draw'),))
]
variable[target] assign[=] call[name[np].empty, parameter[call[name[ary].shap... | keyword[def] identifier[_rhat_ufunc] ( identifier[ary] ):
literal[string]
identifier[target] = identifier[np] . identifier[empty] ( identifier[ary] . identifier[shape] [:- literal[int] ])
keyword[for] identifier[idx] keyword[in] identifier[np] . identifier[ndindex] ( identifier[target] . identifier... | def _rhat_ufunc(ary):
"""Ufunc for computing effective sample size.
This can be used on an xarray Dataset, using
`xr.apply_ufunc(_neff_ufunc, ..., input_core_dims=(('chain', 'draw'),))
"""
target = np.empty(ary.shape[:-2])
for idx in np.ndindex(target.shape):
target[idx] = _get_split_rh... |
def _build_package_finder(options, index_urls, session):
"""
Create a package finder appropriate to this list command.
"""
return PackageFinder(
find_links=options.get('find_links'),
index_urls=index_urls,
allow_all_prereleases=options.get('pre'),
... | def function[_build_package_finder, parameter[options, index_urls, session]]:
constant[
Create a package finder appropriate to this list command.
]
return[call[name[PackageFinder], parameter[]]] | keyword[def] identifier[_build_package_finder] ( identifier[options] , identifier[index_urls] , identifier[session] ):
literal[string]
keyword[return] identifier[PackageFinder] (
identifier[find_links] = identifier[options] . identifier[get] ( literal[string] ),
identifier[index_... | def _build_package_finder(options, index_urls, session):
"""
Create a package finder appropriate to this list command.
"""
return PackageFinder(find_links=options.get('find_links'), index_urls=index_urls, allow_all_prereleases=options.get('pre'), trusted_hosts=options.get('trusted_hosts'), sessi... |
def _apply_columns(self, func):
"""
Get new SparseDataFrame applying func to each columns
"""
new_data = {col: func(series)
for col, series in self.items()}
return self._constructor(
data=new_data, index=self.index, columns=self.columns,
... | def function[_apply_columns, parameter[self, func]]:
constant[
Get new SparseDataFrame applying func to each columns
]
variable[new_data] assign[=] <ast.DictComp object at 0x7da18fe92140>
return[call[call[name[self]._constructor, parameter[]].__finalize__, parameter[name[self]]]] | keyword[def] identifier[_apply_columns] ( identifier[self] , identifier[func] ):
literal[string]
identifier[new_data] ={ identifier[col] : identifier[func] ( identifier[series] )
keyword[for] identifier[col] , identifier[series] keyword[in] identifier[self] . identifier[items] ()}
... | def _apply_columns(self, func):
"""
Get new SparseDataFrame applying func to each columns
"""
new_data = {col: func(series) for (col, series) in self.items()}
return self._constructor(data=new_data, index=self.index, columns=self.columns, default_fill_value=self.default_fill_value).__finaliz... |
def parse_JSON(self, JSON_string):
"""
Parses an *COIndex* instance out of raw JSON data. Only certain
properties of the data are used: if these properties are not found or
cannot be parsed, an error is issued.
:param JSON_string: a raw JSON string
:type JSON_string: str... | def function[parse_JSON, parameter[self, JSON_string]]:
constant[
Parses an *COIndex* instance out of raw JSON data. Only certain
properties of the data are used: if these properties are not found or
cannot be parsed, an error is issued.
:param JSON_string: a raw JSON string
... | keyword[def] identifier[parse_JSON] ( identifier[self] , identifier[JSON_string] ):
literal[string]
keyword[if] identifier[JSON_string] keyword[is] keyword[None] :
keyword[raise] identifier[parse_response_error] . identifier[ParseResponseError] ( literal[string] )
identifi... | def parse_JSON(self, JSON_string):
"""
Parses an *COIndex* instance out of raw JSON data. Only certain
properties of the data are used: if these properties are not found or
cannot be parsed, an error is issued.
:param JSON_string: a raw JSON string
:type JSON_string: str
... |
def delay_for(
self,
wait: typing.Union[int, float],
identifier: typing.Any,
) -> bool:
"""Defer the execution of a function for some number of seconds.
Args:
wait (typing.Union[int, float]): A numeric value that represents
the number ... | def function[delay_for, parameter[self, wait, identifier]]:
constant[Defer the execution of a function for some number of seconds.
Args:
wait (typing.Union[int, float]): A numeric value that represents
the number of seconds that must pass before the callback
... | keyword[def] identifier[delay_for] (
identifier[self] ,
identifier[wait] : identifier[typing] . identifier[Union] [ identifier[int] , identifier[float] ],
identifier[identifier] : identifier[typing] . identifier[Any] ,
)-> identifier[bool] :
literal[string]
keyword[raise] identifier[NotImplemen... | def delay_for(self, wait: typing.Union[int, float], identifier: typing.Any) -> bool:
"""Defer the execution of a function for some number of seconds.
Args:
wait (typing.Union[int, float]): A numeric value that represents
the number of seconds that must pass before the callback
... |
def _verify(self, path_prefix=None):
"""Verifies that this schema's doc spec is valid and makes sense."""
for field, spec in self.doc_spec.iteritems():
path = self._append_path(path_prefix, field)
# Standard dict-based spec
if isinstance(spec, dict):
... | def function[_verify, parameter[self, path_prefix]]:
constant[Verifies that this schema's doc spec is valid and makes sense.]
for taget[tuple[[<ast.Name object at 0x7da1b11c26b0>, <ast.Name object at 0x7da1b11c0340>]]] in starred[call[name[self].doc_spec.iteritems, parameter[]]] begin[:]
... | keyword[def] identifier[_verify] ( identifier[self] , identifier[path_prefix] = keyword[None] ):
literal[string]
keyword[for] identifier[field] , identifier[spec] keyword[in] identifier[self] . identifier[doc_spec] . identifier[iteritems] ():
identifier[path] = identifier[self] . id... | def _verify(self, path_prefix=None):
"""Verifies that this schema's doc spec is valid and makes sense."""
for (field, spec) in self.doc_spec.iteritems():
path = self._append_path(path_prefix, field)
# Standard dict-based spec
if isinstance(spec, dict):
self._verify_field_spec... |
def eval(self, valuation=None, trace=None):
"""
This method should be always called by subclasses
:param valuation
:param trace
:return: Arguments evaluation
"""
args2 = []
for a in self.args:
if isinstance(a, Function) or isinstance(a, IPredic... | def function[eval, parameter[self, valuation, trace]]:
constant[
This method should be always called by subclasses
:param valuation
:param trace
:return: Arguments evaluation
]
variable[args2] assign[=] list[[]]
for taget[name[a]] in starred[name[self].arg... | keyword[def] identifier[eval] ( identifier[self] , identifier[valuation] = keyword[None] , identifier[trace] = keyword[None] ):
literal[string]
identifier[args2] =[]
keyword[for] identifier[a] keyword[in] identifier[self] . identifier[args] :
keyword[if] identifier[isinsta... | def eval(self, valuation=None, trace=None):
"""
This method should be always called by subclasses
:param valuation
:param trace
:return: Arguments evaluation
"""
args2 = []
for a in self.args:
if isinstance(a, Function) or isinstance(a, IPredicate):
... |
def replace_read(self):
"""
Replaces all READ (type - 3) states to a PUSH (type - 1) and a POP (type - 2).
The actual state is replaced with the PUSH, and a new POP is created.
"""
for statenum in self.statediag:
state = self.statediag[statenum]
if state.t... | def function[replace_read, parameter[self]]:
constant[
Replaces all READ (type - 3) states to a PUSH (type - 1) and a POP (type - 2).
The actual state is replaced with the PUSH, and a new POP is created.
]
for taget[name[statenum]] in starred[name[self].statediag] begin[:]
... | keyword[def] identifier[replace_read] ( identifier[self] ):
literal[string]
keyword[for] identifier[statenum] keyword[in] identifier[self] . identifier[statediag] :
identifier[state] = identifier[self] . identifier[statediag] [ identifier[statenum] ]
keyword[if] identi... | def replace_read(self):
"""
Replaces all READ (type - 3) states to a PUSH (type - 1) and a POP (type - 2).
The actual state is replaced with the PUSH, and a new POP is created.
"""
for statenum in self.statediag:
state = self.statediag[statenum]
if state.type == 3: # REA... |
def get_maintenance_window(self, id, **kwargs): # noqa: E501
"""Get a specific maintenance window # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_maintena... | def function[get_maintenance_window, parameter[self, id]]:
constant[Get a specific maintenance window # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_maint... | keyword[def] identifier[get_maintenance_window] ( identifier[self] , identifier[id] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] identifi... | def get_maintenance_window(self, id, **kwargs): # noqa: E501
'Get a specific maintenance window # noqa: E501\n\n # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.get_maintenan... |
def getUserPassword(host='www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca'):
""""Getting the username/password for host from .netrc filie """
if os.access(os.path.join(os.environ.get('HOME','/'),".netrc"),os.R_OK):
auth=netrc.netrc().authenticators(host)
else:
auth=False
if not auth:
sys.st... | def function[getUserPassword, parameter[host]]:
constant["Getting the username/password for host from .netrc filie ]
if call[name[os].access, parameter[call[name[os].path.join, parameter[call[name[os].environ.get, parameter[constant[HOME], constant[/]]], constant[.netrc]]], name[os].R_OK]] begin[:]
... | keyword[def] identifier[getUserPassword] ( identifier[host] = literal[string] ):
literal[string]
keyword[if] identifier[os] . identifier[access] ( identifier[os] . identifier[path] . identifier[join] ( identifier[os] . identifier[environ] . identifier[get] ( literal[string] , literal[string] ), literal[st... | def getUserPassword(host='www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca'):
""""Getting the username/password for host from .netrc filie """
if os.access(os.path.join(os.environ.get('HOME', '/'), '.netrc'), os.R_OK):
auth = netrc.netrc().authenticators(host) # depends on [control=['if'], data=[]]
else:
... |
def save_lines(lines, filename):
"""
Save an array of lines to a file.
Args:
lines: An array of strings that will be saved as individual lines.
filename: Path to the output file.
"""
with open(filename, 'w', encoding='utf-8') as f:
f.write('\n'.join(lines)) | def function[save_lines, parameter[lines, filename]]:
constant[
Save an array of lines to a file.
Args:
lines: An array of strings that will be saved as individual lines.
filename: Path to the output file.
]
with call[name[open], parameter[name[filename], constant[w]]] begin... | keyword[def] identifier[save_lines] ( identifier[lines] , identifier[filename] ):
literal[string]
keyword[with] identifier[open] ( identifier[filename] , literal[string] , identifier[encoding] = literal[string] ) keyword[as] identifier[f] :
identifier[f] . identifier[write] ( literal[string] . ... | def save_lines(lines, filename):
"""
Save an array of lines to a file.
Args:
lines: An array of strings that will be saved as individual lines.
filename: Path to the output file.
"""
with open(filename, 'w', encoding='utf-8') as f:
f.write('\n'.join(lines)) # depends on [co... |
def add_task_db(self, task):
'''向数据库中写入一个新的任务记录'''
sql = 'INSERT INTO tasks VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)'
req = self.cursor.execute(sql, task)
self.check_commit() | def function[add_task_db, parameter[self, task]]:
constant[向数据库中写入一个新的任务记录]
variable[sql] assign[=] constant[INSERT INTO tasks VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)]
variable[req] assign[=] call[name[self].cursor.execute, parameter[name[sql], name[task]]]
call[name[self].check_commit, para... | keyword[def] identifier[add_task_db] ( identifier[self] , identifier[task] ):
literal[string]
identifier[sql] = literal[string]
identifier[req] = identifier[self] . identifier[cursor] . identifier[execute] ( identifier[sql] , identifier[task] )
identifier[self] . identifier[check... | def add_task_db(self, task):
"""向数据库中写入一个新的任务记录"""
sql = 'INSERT INTO tasks VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)'
req = self.cursor.execute(sql, task)
self.check_commit() |
def similarity_by_path(sense1: "wn.Synset", sense2: "wn.Synset", option: str = "path") -> float:
"""
Returns maximum path similarity between two senses.
:param sense1: A synset.
:param sense2: A synset.
:param option: String, one of ('path', 'wup', 'lch').
:return: A float, similarity measureme... | def function[similarity_by_path, parameter[sense1, sense2, option]]:
constant[
Returns maximum path similarity between two senses.
:param sense1: A synset.
:param sense2: A synset.
:param option: String, one of ('path', 'wup', 'lch').
:return: A float, similarity measurement.
]
... | keyword[def] identifier[similarity_by_path] ( identifier[sense1] : literal[string] , identifier[sense2] : literal[string] , identifier[option] : identifier[str] = literal[string] )-> identifier[float] :
literal[string]
keyword[if] identifier[option] . identifier[lower] () keyword[in] [ literal[string] , l... | def similarity_by_path(sense1: 'wn.Synset', sense2: 'wn.Synset', option: str='path') -> float:
"""
Returns maximum path similarity between two senses.
:param sense1: A synset.
:param sense2: A synset.
:param option: String, one of ('path', 'wup', 'lch').
:return: A float, similarity measurement... |
def matching_selectors(self, partial_selector):
"""Retrieves all selectors matching `partial_selector`.
For instance, if "one.a.b" and "two.a.b" are stored in a `SelectorMap`, both
`matching_selectors('b')` and `matching_selectors('a.b')` will return them.
In the event that `partial_selector` exactly ... | def function[matching_selectors, parameter[self, partial_selector]]:
constant[Retrieves all selectors matching `partial_selector`.
For instance, if "one.a.b" and "two.a.b" are stored in a `SelectorMap`, both
`matching_selectors('b')` and `matching_selectors('a.b')` will return them.
In the event t... | keyword[def] identifier[matching_selectors] ( identifier[self] , identifier[partial_selector] ):
literal[string]
keyword[if] identifier[partial_selector] keyword[in] identifier[self] . identifier[_selector_map] :
keyword[return] [ identifier[partial_selector] ]
identifier[selector_component... | def matching_selectors(self, partial_selector):
"""Retrieves all selectors matching `partial_selector`.
For instance, if "one.a.b" and "two.a.b" are stored in a `SelectorMap`, both
`matching_selectors('b')` and `matching_selectors('a.b')` will return them.
In the event that `partial_selector` exactly ... |
def remove_app(name, site):
'''
Remove an IIS application.
:param str name: The application name.
:param str site: The IIS site name.
Usage:
.. code-block:: yaml
site0-v1-app-remove:
win_iis.remove_app:
- name: v1
- site: site0
'''
... | def function[remove_app, parameter[name, site]]:
constant[
Remove an IIS application.
:param str name: The application name.
:param str site: The IIS site name.
Usage:
.. code-block:: yaml
site0-v1-app-remove:
win_iis.remove_app:
- name: v1
... | keyword[def] identifier[remove_app] ( identifier[name] , identifier[site] ):
literal[string]
identifier[ret] ={ literal[string] : identifier[name] ,
literal[string] :{},
literal[string] : identifier[str] (),
literal[string] : keyword[None] }
identifier[current_apps] = identifier[__salt... | def remove_app(name, site):
"""
Remove an IIS application.
:param str name: The application name.
:param str site: The IIS site name.
Usage:
.. code-block:: yaml
site0-v1-app-remove:
win_iis.remove_app:
- name: v1
- site: site0
"""
... |
def make_ita(noise, acf=None):
"""
Create the matrix ita of the noise where the noise may be a masked array
where ita(x,y) is the correlation between pixel pairs that have the same separation as x and y.
Parameters
----------
noise : 2d-array
The noise image
acf : 2d-array
... | def function[make_ita, parameter[noise, acf]]:
constant[
Create the matrix ita of the noise where the noise may be a masked array
where ita(x,y) is the correlation between pixel pairs that have the same separation as x and y.
Parameters
----------
noise : 2d-array
The noise image
... | keyword[def] identifier[make_ita] ( identifier[noise] , identifier[acf] = keyword[None] ):
literal[string]
keyword[if] identifier[acf] keyword[is] keyword[None] :
identifier[acf] = identifier[nan_acf] ( identifier[noise] )
identifier[s] = identifier[np] . identifier[count_nonzero]... | def make_ita(noise, acf=None):
"""
Create the matrix ita of the noise where the noise may be a masked array
where ita(x,y) is the correlation between pixel pairs that have the same separation as x and y.
Parameters
----------
noise : 2d-array
The noise image
acf : 2d-array
... |
def register_error_handler(app, handler=None):
"""
Register error handler
Registers an exception handler on the app instance for every type of
exception code werkzeug is aware about.
:param app: flask.Flask - flask application instance
:param handler: function - the handler
:return: None
... | def function[register_error_handler, parameter[app, handler]]:
constant[
Register error handler
Registers an exception handler on the app instance for every type of
exception code werkzeug is aware about.
:param app: flask.Flask - flask application instance
:param handler: function - the ha... | keyword[def] identifier[register_error_handler] ( identifier[app] , identifier[handler] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[handler] :
identifier[handler] = identifier[default_error_handler]
keyword[for] identifier[code] keyword[in] identifier[excepti... | def register_error_handler(app, handler=None):
"""
Register error handler
Registers an exception handler on the app instance for every type of
exception code werkzeug is aware about.
:param app: flask.Flask - flask application instance
:param handler: function - the handler
:return: None
... |
def sanitize_for_archive(url, headers, payload):
"""Sanitize payload of a HTTP request by removing the token information
before storing/retrieving archived items
:param: url: HTTP url request
:param: headers: HTTP headers request
:param: payload: HTTP payload request
:r... | def function[sanitize_for_archive, parameter[url, headers, payload]]:
constant[Sanitize payload of a HTTP request by removing the token information
before storing/retrieving archived items
:param: url: HTTP url request
:param: headers: HTTP headers request
:param: payload: HTTP ... | keyword[def] identifier[sanitize_for_archive] ( identifier[url] , identifier[headers] , identifier[payload] ):
literal[string]
keyword[if] identifier[DiscourseClient] . identifier[PKEY] keyword[in] identifier[payload] :
identifier[payload] . identifier[pop] ( identifier[DiscourseCli... | def sanitize_for_archive(url, headers, payload):
"""Sanitize payload of a HTTP request by removing the token information
before storing/retrieving archived items
:param: url: HTTP url request
:param: headers: HTTP headers request
:param: payload: HTTP payload request
:retur... |
def _gl_look_at(self, pos, target, up):
"""
The standard lookAt method
:param pos: current position
:param target: target position to look at
:param up: direction up
"""
z = vector.normalise(pos - target)
x = vector.normalise(vector3.cross(vector.normalis... | def function[_gl_look_at, parameter[self, pos, target, up]]:
constant[
The standard lookAt method
:param pos: current position
:param target: target position to look at
:param up: direction up
]
variable[z] assign[=] call[name[vector].normalise, parameter[binary_... | keyword[def] identifier[_gl_look_at] ( identifier[self] , identifier[pos] , identifier[target] , identifier[up] ):
literal[string]
identifier[z] = identifier[vector] . identifier[normalise] ( identifier[pos] - identifier[target] )
identifier[x] = identifier[vector] . identifier[normalise] ... | def _gl_look_at(self, pos, target, up):
"""
The standard lookAt method
:param pos: current position
:param target: target position to look at
:param up: direction up
"""
z = vector.normalise(pos - target)
x = vector.normalise(vector3.cross(vector.normalise(up), z))
... |
def remove_router_from_hosting_device(self, client, hosting_device_id,
router_id):
"""Remove a router from hosting_device."""
res_path = hostingdevice.HostingDevice.resource_path
return client.delete((res_path + DEVICE_L3_ROUTERS + "/%s") % (
... | def function[remove_router_from_hosting_device, parameter[self, client, hosting_device_id, router_id]]:
constant[Remove a router from hosting_device.]
variable[res_path] assign[=] name[hostingdevice].HostingDevice.resource_path
return[call[name[client].delete, parameter[binary_operation[binary_opera... | keyword[def] identifier[remove_router_from_hosting_device] ( identifier[self] , identifier[client] , identifier[hosting_device_id] ,
identifier[router_id] ):
literal[string]
identifier[res_path] = identifier[hostingdevice] . identifier[HostingDevice] . identifier[resource_path]
keyword[r... | def remove_router_from_hosting_device(self, client, hosting_device_id, router_id):
"""Remove a router from hosting_device."""
res_path = hostingdevice.HostingDevice.resource_path
return client.delete((res_path + DEVICE_L3_ROUTERS + '/%s') % (hosting_device_id, router_id)) |
def _modify_trust(self, truster, mod_peer_func, trustee):
'''Modify a trusted peer device by deploying an iapp.
:param truster: ManagementRoot object -- device on which to perform
commands
:param mod_peer_func: function -- function to call to modify peer
:param ... | def function[_modify_trust, parameter[self, truster, mod_peer_func, trustee]]:
constant[Modify a trusted peer device by deploying an iapp.
:param truster: ManagementRoot object -- device on which to perform
commands
:param mod_peer_func: function -- function to call to ... | keyword[def] identifier[_modify_trust] ( identifier[self] , identifier[truster] , identifier[mod_peer_func] , identifier[trustee] ):
literal[string]
identifier[iapp_name] = literal[string]
identifier[mod_peer_cmd] = identifier[mod_peer_func] ( identifier[trustee] )
identifier[ia... | def _modify_trust(self, truster, mod_peer_func, trustee):
"""Modify a trusted peer device by deploying an iapp.
:param truster: ManagementRoot object -- device on which to perform
commands
:param mod_peer_func: function -- function to call to modify peer
:param trus... |
def _job_queue_empty(self):
"""
A callback method called when the job queue is empty.
:return: None
"""
self._iteratively_clean_pending_exits()
while self._pending_jobs:
# We don't have any exits remaining. Let's pop out a pending exit
pending_j... | def function[_job_queue_empty, parameter[self]]:
constant[
A callback method called when the job queue is empty.
:return: None
]
call[name[self]._iteratively_clean_pending_exits, parameter[]]
while name[self]._pending_jobs begin[:]
variable[pending_job] a... | keyword[def] identifier[_job_queue_empty] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_iteratively_clean_pending_exits] ()
keyword[while] identifier[self] . identifier[_pending_jobs] :
identifier[pending_job] = identifier[self] . identifier[... | def _job_queue_empty(self):
"""
A callback method called when the job queue is empty.
:return: None
"""
self._iteratively_clean_pending_exits()
while self._pending_jobs:
# We don't have any exits remaining. Let's pop out a pending exit
pending_job = self._get_one_pen... |
def set_image(self, text):
"""
Save image resource at `text` (path or url) to storage, then return the
replacement string and the necessary exercicse image file object.
Args:
- text (str): path or url to parse as an exercise image resource
Returns: (new_text, files)
... | def function[set_image, parameter[self, text]]:
constant[
Save image resource at `text` (path or url) to storage, then return the
replacement string and the necessary exercicse image file object.
Args:
- text (str): path or url to parse as an exercise image resource
Ret... | keyword[def] identifier[set_image] ( identifier[self] , identifier[text] ):
literal[string]
keyword[if] identifier[exercises] . identifier[CONTENT_STORAGE_PLACEHOLDER] keyword[in] identifier[text] :
keyword[return] identifier[text] ,[]
identifier[stri... | def set_image(self, text):
"""
Save image resource at `text` (path or url) to storage, then return the
replacement string and the necessary exercicse image file object.
Args:
- text (str): path or url to parse as an exercise image resource
Returns: (new_text, files)
... |
def evaluate_parameter_sets(self):
"""
This takes the parameter sets of the model instance and evaluates any formulas using the parameter values to create a
fixed, full set of parameters for each parameter set in the model
"""
#parameter_interpreter = ParameterInterpreter(self.... | def function[evaluate_parameter_sets, parameter[self]]:
constant[
This takes the parameter sets of the model instance and evaluates any formulas using the parameter values to create a
fixed, full set of parameters for each parameter set in the model
]
name[self].parameter_inter... | keyword[def] identifier[evaluate_parameter_sets] ( identifier[self] ):
literal[string]
identifier[self] . identifier[parameter_interpreter] = identifier[LcoptParameterSet] ( identifier[self] . identifier[modelInstance] )
identifier[self] . identifier[modelInstance] . ide... | def evaluate_parameter_sets(self):
"""
This takes the parameter sets of the model instance and evaluates any formulas using the parameter values to create a
fixed, full set of parameters for each parameter set in the model
"""
#parameter_interpreter = ParameterInterpreter(self.modelIns... |
def device_event_list(self, **kwargs): # noqa: E501
"""List all device events. # noqa: E501
List all device events for an account. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thr... | def function[device_event_list, parameter[self]]:
constant[List all device events. # noqa: E501
List all device events for an account. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> ... | keyword[def] identifier[device_event_list] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] identifier[self] . identifier[... | def device_event_list(self, **kwargs): # noqa: E501
'List all device events. # noqa: E501\n\n List all device events for an account. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass asynchronous=True\n >>> thre... |
def get_label(self, lang='en'):
"""
Returns the label for a certain language
:param lang:
:type lang: str
:return: returns the label in the specified language, an empty string if the label does not exist
"""
if self.fast_run:
return list(self.fast_run_... | def function[get_label, parameter[self, lang]]:
constant[
Returns the label for a certain language
:param lang:
:type lang: str
:return: returns the label in the specified language, an empty string if the label does not exist
]
if name[self].fast_run begin[:]
... | keyword[def] identifier[get_label] ( identifier[self] , identifier[lang] = literal[string] ):
literal[string]
keyword[if] identifier[self] . identifier[fast_run] :
keyword[return] identifier[list] ( identifier[self] . identifier[fast_run_container] . identifier[get_language_data] ( i... | def get_label(self, lang='en'):
"""
Returns the label for a certain language
:param lang:
:type lang: str
:return: returns the label in the specified language, an empty string if the label does not exist
"""
if self.fast_run:
return list(self.fast_run_container.ge... |
def _validate_codeblock_size(self, cparams):
"""
Code block dimensions must satisfy certain restrictions.
They must both be a power of 2 and the total area defined by the width
and height cannot be either too great or too small for the codec.
"""
if cparams.cblockw_init ... | def function[_validate_codeblock_size, parameter[self, cparams]]:
constant[
Code block dimensions must satisfy certain restrictions.
They must both be a power of 2 and the total area defined by the width
and height cannot be either too great or too small for the codec.
]
... | keyword[def] identifier[_validate_codeblock_size] ( identifier[self] , identifier[cparams] ):
literal[string]
keyword[if] identifier[cparams] . identifier[cblockw_init] != literal[int] keyword[and] identifier[cparams] . identifier[cblockh_init] != literal[int] :
identifier[... | def _validate_codeblock_size(self, cparams):
"""
Code block dimensions must satisfy certain restrictions.
They must both be a power of 2 and the total area defined by the width
and height cannot be either too great or too small for the codec.
"""
if cparams.cblockw_init != 0 and... |
def tzname(self, dt):
"""
http://docs.python.org/library/datetime.html#datetime.tzinfo.tzname
"""
sign = '+'
if self.__offset < datetime.timedelta():
sign = '-'
# total_seconds was introduced in Python 2.7
if hasattr(self.__offset, 'total_seconds'):
... | def function[tzname, parameter[self, dt]]:
constant[
http://docs.python.org/library/datetime.html#datetime.tzinfo.tzname
]
variable[sign] assign[=] constant[+]
if compare[name[self].__offset less[<] call[name[datetime].timedelta, parameter[]]] begin[:]
variable[s... | keyword[def] identifier[tzname] ( identifier[self] , identifier[dt] ):
literal[string]
identifier[sign] = literal[string]
keyword[if] identifier[self] . identifier[__offset] < identifier[datetime] . identifier[timedelta] ():
identifier[sign] = literal[string]
... | def tzname(self, dt):
"""
http://docs.python.org/library/datetime.html#datetime.tzinfo.tzname
"""
sign = '+'
if self.__offset < datetime.timedelta():
sign = '-' # depends on [control=['if'], data=[]]
# total_seconds was introduced in Python 2.7
if hasattr(self.__offset, 'to... |
def get_top_assets(self):
"""
Gets images and videos to populate top assets.
Map is built separately.
"""
images = self.get_all_images()[0:14]
video = []
if supports_video:
video = self.eventvideo_set.all()[0:10]
return list(chain(images, vid... | def function[get_top_assets, parameter[self]]:
constant[
Gets images and videos to populate top assets.
Map is built separately.
]
variable[images] assign[=] call[call[name[self].get_all_images, parameter[]]][<ast.Slice object at 0x7da20c6c6830>]
variable[video] assign[=... | keyword[def] identifier[get_top_assets] ( identifier[self] ):
literal[string]
identifier[images] = identifier[self] . identifier[get_all_images] ()[ literal[int] : literal[int] ]
identifier[video] =[]
keyword[if] identifier[supports_video] :
identifier[video] = ident... | def get_top_assets(self):
"""
Gets images and videos to populate top assets.
Map is built separately.
"""
images = self.get_all_images()[0:14]
video = []
if supports_video:
video = self.eventvideo_set.all()[0:10] # depends on [control=['if'], data=[]]
return list(ch... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.