code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def fit_shifts(xy, uv):
""" Performs a simple fit for the shift only between
matched lists of positions 'xy' and 'uv'.
Output: (same as for fit_arrays)
=================================
DEVELOPMENT NOTE:
Checks need to be put in place to verify that
enough ob... | def function[fit_shifts, parameter[xy, uv]]:
constant[ Performs a simple fit for the shift only between
matched lists of positions 'xy' and 'uv'.
Output: (same as for fit_arrays)
=================================
DEVELOPMENT NOTE:
Checks need to be put in place to ve... | keyword[def] identifier[fit_shifts] ( identifier[xy] , identifier[uv] ):
literal[string]
identifier[diff_pts] = identifier[xy] - identifier[uv]
identifier[Pcoeffs] = identifier[np] . identifier[array] ([ literal[int] , literal[int] , identifier[diff_pts] [:, literal[int] ]. identifier[mean] ( identif... | def fit_shifts(xy, uv):
""" Performs a simple fit for the shift only between
matched lists of positions 'xy' and 'uv'.
Output: (same as for fit_arrays)
=================================
DEVELOPMENT NOTE:
Checks need to be put in place to verify that
enough ob... |
def _started_channels(self):
"""Reimplemented to make a history request and load %guiref."""
super(IPythonWidget, self)._started_channels()
self._load_guiref_magic()
self.kernel_manager.shell_channel.history(hist_access_type='tail',
n=100... | def function[_started_channels, parameter[self]]:
constant[Reimplemented to make a history request and load %guiref.]
call[call[name[super], parameter[name[IPythonWidget], name[self]]]._started_channels, parameter[]]
call[name[self]._load_guiref_magic, parameter[]]
call[name[self].kernel... | keyword[def] identifier[_started_channels] ( identifier[self] ):
literal[string]
identifier[super] ( identifier[IPythonWidget] , identifier[self] ). identifier[_started_channels] ()
identifier[self] . identifier[_load_guiref_magic] ()
identifier[self] . identifier[kernel_manager] ... | def _started_channels(self):
"""Reimplemented to make a history request and load %guiref."""
super(IPythonWidget, self)._started_channels()
self._load_guiref_magic()
self.kernel_manager.shell_channel.history(hist_access_type='tail', n=1000) |
def show_firmware_version_output_show_firmware_version_firmware_full_version(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_firmware_version = ET.Element("show_firmware_version")
config = show_firmware_version
output = ET.SubElement(show_fi... | def function[show_firmware_version_output_show_firmware_version_firmware_full_version, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[show_firmware_version] assign[=] call[name[ET].Element, paramete... | keyword[def] identifier[show_firmware_version_output_show_firmware_version_firmware_full_version] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[show_firmware_version] = identifier[ET] . ... | def show_firmware_version_output_show_firmware_version_firmware_full_version(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
show_firmware_version = ET.Element('show_firmware_version')
config = show_firmware_version
output = ET.SubElement(show_firmware_version, 'out... |
def compute_hash_speed(num, quiet=False):
# type: (int, bool) -> float
""" Hash time.
"""
namelist = NameList(num)
os_fd, tmpfile_name = tempfile.mkstemp(text=True)
schema = NameList.SCHEMA
header_row = ','.join([f.identifier for f in schema.fields])
with open(tmpfile_name, 'wt') as f... | def function[compute_hash_speed, parameter[num, quiet]]:
constant[ Hash time.
]
variable[namelist] assign[=] call[name[NameList], parameter[name[num]]]
<ast.Tuple object at 0x7da18ede6830> assign[=] call[name[tempfile].mkstemp, parameter[]]
variable[schema] assign[=] name[NameList].S... | keyword[def] identifier[compute_hash_speed] ( identifier[num] , identifier[quiet] = keyword[False] ):
literal[string]
identifier[namelist] = identifier[NameList] ( identifier[num] )
identifier[os_fd] , identifier[tmpfile_name] = identifier[tempfile] . identifier[mkstemp] ( identifier[text] = keyword... | def compute_hash_speed(num, quiet=False):
# type: (int, bool) -> float
' Hash time.\n '
namelist = NameList(num)
(os_fd, tmpfile_name) = tempfile.mkstemp(text=True)
schema = NameList.SCHEMA
header_row = ','.join([f.identifier for f in schema.fields])
with open(tmpfile_name, 'wt') as f:
... |
def complete(self):
"""Mark a multipart object as complete."""
if Part.count(self) != self.last_part_number + 1:
raise MultipartMissingParts()
with db.session.begin_nested():
self.completed = True
self.file.readable = True
self.file.writable = Fal... | def function[complete, parameter[self]]:
constant[Mark a multipart object as complete.]
if compare[call[name[Part].count, parameter[name[self]]] not_equal[!=] binary_operation[name[self].last_part_number + constant[1]]] begin[:]
<ast.Raise object at 0x7da1b19a2f20>
with call[name[db].ses... | keyword[def] identifier[complete] ( identifier[self] ):
literal[string]
keyword[if] identifier[Part] . identifier[count] ( identifier[self] )!= identifier[self] . identifier[last_part_number] + literal[int] :
keyword[raise] identifier[MultipartMissingParts] ()
keyword[with]... | def complete(self):
"""Mark a multipart object as complete."""
if Part.count(self) != self.last_part_number + 1:
raise MultipartMissingParts() # depends on [control=['if'], data=[]]
with db.session.begin_nested():
self.completed = True
self.file.readable = True
self.file.wri... |
def skip_build(self):
"""Check if build should be skipped
"""
skip_msg = self.config.get('skip', '[ci skip]')
return (
os.environ.get('CODEBUILD_BUILD_SUCCEEDING') == '0' or
self.info['current_tag'] or
skip_msg in self.info['head']['message']
) | def function[skip_build, parameter[self]]:
constant[Check if build should be skipped
]
variable[skip_msg] assign[=] call[name[self].config.get, parameter[constant[skip], constant[[ci skip]]]]
return[<ast.BoolOp object at 0x7da204566740>] | keyword[def] identifier[skip_build] ( identifier[self] ):
literal[string]
identifier[skip_msg] = identifier[self] . identifier[config] . identifier[get] ( literal[string] , literal[string] )
keyword[return] (
identifier[os] . identifier[environ] . identifier[get] ( literal[string]... | def skip_build(self):
"""Check if build should be skipped
"""
skip_msg = self.config.get('skip', '[ci skip]')
return os.environ.get('CODEBUILD_BUILD_SUCCEEDING') == '0' or self.info['current_tag'] or skip_msg in self.info['head']['message'] |
def _CronJobFromRow(self, row):
"""Creates a cronjob object from a database result row."""
(job, create_time, enabled, forced_run_requested, last_run_status,
last_run_time, current_run_id, state, leased_until, leased_by) = row
job = rdf_cronjobs.CronJob.FromSerializedString(job)
job.current_run_id... | def function[_CronJobFromRow, parameter[self, row]]:
constant[Creates a cronjob object from a database result row.]
<ast.Tuple object at 0x7da1b1d90850> assign[=] name[row]
variable[job] assign[=] call[name[rdf_cronjobs].CronJob.FromSerializedString, parameter[name[job]]]
name[job].curre... | keyword[def] identifier[_CronJobFromRow] ( identifier[self] , identifier[row] ):
literal[string]
( identifier[job] , identifier[create_time] , identifier[enabled] , identifier[forced_run_requested] , identifier[last_run_status] ,
identifier[last_run_time] , identifier[current_run_id] , identifier[state... | def _CronJobFromRow(self, row):
"""Creates a cronjob object from a database result row."""
(job, create_time, enabled, forced_run_requested, last_run_status, last_run_time, current_run_id, state, leased_until, leased_by) = row
job = rdf_cronjobs.CronJob.FromSerializedString(job)
job.current_run_id = db_... |
def set_sorting(self, flag):
"""Enable result sorting after search is complete."""
self.sorting['status'] = flag
self.header().setSectionsClickable(flag == ON) | def function[set_sorting, parameter[self, flag]]:
constant[Enable result sorting after search is complete.]
call[name[self].sorting][constant[status]] assign[=] name[flag]
call[call[name[self].header, parameter[]].setSectionsClickable, parameter[compare[name[flag] equal[==] name[ON]]]] | keyword[def] identifier[set_sorting] ( identifier[self] , identifier[flag] ):
literal[string]
identifier[self] . identifier[sorting] [ literal[string] ]= identifier[flag]
identifier[self] . identifier[header] (). identifier[setSectionsClickable] ( identifier[flag] == identifier[ON] ) | def set_sorting(self, flag):
"""Enable result sorting after search is complete."""
self.sorting['status'] = flag
self.header().setSectionsClickable(flag == ON) |
def read_local_manifest(self):
""" Read the file manifest, or create a new one if there isn't one already """
manifest = file_or_default(self.get_full_file_path(self.manifest_file), {
'format_version' : 2,
'root' : '/',
'have_revision' : 'root',
... | def function[read_local_manifest, parameter[self]]:
constant[ Read the file manifest, or create a new one if there isn't one already ]
variable[manifest] assign[=] call[name[file_or_default], parameter[call[name[self].get_full_file_path, parameter[name[self].manifest_file]], dictionary[[<ast.Constant ob... | keyword[def] identifier[read_local_manifest] ( identifier[self] ):
literal[string]
identifier[manifest] = identifier[file_or_default] ( identifier[self] . identifier[get_full_file_path] ( identifier[self] . identifier[manifest_file] ),{
literal[string] : literal[int] ,
literal[st... | def read_local_manifest(self):
""" Read the file manifest, or create a new one if there isn't one already """
manifest = file_or_default(self.get_full_file_path(self.manifest_file), {'format_version': 2, 'root': '/', 'have_revision': 'root', 'files': {}}, json.loads)
if 'format_version' not in manifest or m... |
def _to_temperature(self, temperature):
""" Step to a given temperature.
:param temperature: Get to this temperature.
"""
self._to_value(self._temperature, temperature,
self.command_set.temperature_steps,
self._warmer, self._cooler) | def function[_to_temperature, parameter[self, temperature]]:
constant[ Step to a given temperature.
:param temperature: Get to this temperature.
]
call[name[self]._to_value, parameter[name[self]._temperature, name[temperature], name[self].command_set.temperature_steps, name[self]._warme... | keyword[def] identifier[_to_temperature] ( identifier[self] , identifier[temperature] ):
literal[string]
identifier[self] . identifier[_to_value] ( identifier[self] . identifier[_temperature] , identifier[temperature] ,
identifier[self] . identifier[command_set] . identifier[temperature_st... | def _to_temperature(self, temperature):
""" Step to a given temperature.
:param temperature: Get to this temperature.
"""
self._to_value(self._temperature, temperature, self.command_set.temperature_steps, self._warmer, self._cooler) |
def value_derived_from_wavefunction(self,
state: np.ndarray,
qubit_map: Dict[raw_types.Qid, int]
) -> Any:
"""The value of the display, derived from the full wavefunction.
Args:
... | def function[value_derived_from_wavefunction, parameter[self, state, qubit_map]]:
constant[The value of the display, derived from the full wavefunction.
Args:
state: The wavefunction.
qubit_map: A dictionary from qubit to qubit index in the
ordering used to defin... | keyword[def] identifier[value_derived_from_wavefunction] ( identifier[self] ,
identifier[state] : identifier[np] . identifier[ndarray] ,
identifier[qubit_map] : identifier[Dict] [ identifier[raw_types] . identifier[Qid] , identifier[int] ]
)-> identifier[Any] :
literal[string] | def value_derived_from_wavefunction(self, state: np.ndarray, qubit_map: Dict[raw_types.Qid, int]) -> Any:
"""The value of the display, derived from the full wavefunction.
Args:
state: The wavefunction.
qubit_map: A dictionary from qubit to qubit index in the
ordering... |
def main():
"""
program entry point
"""
parser = create_parser()
options = vars(parser.parse_args())
HASH_STORE.IGNORE_CACHE_FILE = options[constants.LABEL_FORCE]
moban_file = options[constants.LABEL_MOBANFILE]
load_engine_factory_and_engines() # Error: jinja2 if removed
if moban_fi... | def function[main, parameter[]]:
constant[
program entry point
]
variable[parser] assign[=] call[name[create_parser], parameter[]]
variable[options] assign[=] call[name[vars], parameter[call[name[parser].parse_args, parameter[]]]]
name[HASH_STORE].IGNORE_CACHE_FILE assign[=] call... | keyword[def] identifier[main] ():
literal[string]
identifier[parser] = identifier[create_parser] ()
identifier[options] = identifier[vars] ( identifier[parser] . identifier[parse_args] ())
identifier[HASH_STORE] . identifier[IGNORE_CACHE_FILE] = identifier[options] [ identifier[constants] . ident... | def main():
"""
program entry point
"""
parser = create_parser()
options = vars(parser.parse_args())
HASH_STORE.IGNORE_CACHE_FILE = options[constants.LABEL_FORCE]
moban_file = options[constants.LABEL_MOBANFILE]
load_engine_factory_and_engines() # Error: jinja2 if removed
if moban_fi... |
def write_long(self, n):
"""Write an integer as an unsigned2 32-bit value."""
if n < 0 or n >= 4294967296:
raise FrameSyntaxError(
'Octet {0!r} out of range 0..2**31-1'.format(n))
self._flushbits()
self.out.write(pack('>I', n)) | def function[write_long, parameter[self, n]]:
constant[Write an integer as an unsigned2 32-bit value.]
if <ast.BoolOp object at 0x7da1b17bb970> begin[:]
<ast.Raise object at 0x7da1b17bbca0>
call[name[self]._flushbits, parameter[]]
call[name[self].out.write, parameter[call[name[pa... | keyword[def] identifier[write_long] ( identifier[self] , identifier[n] ):
literal[string]
keyword[if] identifier[n] < literal[int] keyword[or] identifier[n] >= literal[int] :
keyword[raise] identifier[FrameSyntaxError] (
literal[string] . identifier[format] ( identifie... | def write_long(self, n):
"""Write an integer as an unsigned2 32-bit value."""
if n < 0 or n >= 4294967296:
raise FrameSyntaxError('Octet {0!r} out of range 0..2**31-1'.format(n)) # depends on [control=['if'], data=[]]
self._flushbits()
self.out.write(pack('>I', n)) |
def do_query(self, query, timeout=DEFAULT_TIMEOUT, tz=pytz.timezone("US/Pacific")):
"""
Query structure is as follows:
query = {
# We bind UUIDs found as the result of a Brick query to a variable name
# that we can use later.
# Each variable definition has th... | def function[do_query, parameter[self, query, timeout, tz]]:
constant[
Query structure is as follows:
query = {
# We bind UUIDs found as the result of a Brick query to a variable name
# that we can use later.
# Each variable definition has the following:
... | keyword[def] identifier[do_query] ( identifier[self] , identifier[query] , identifier[timeout] = identifier[DEFAULT_TIMEOUT] , identifier[tz] = identifier[pytz] . identifier[timezone] ( literal[string] )):
literal[string]
identifier[nonce] = identifier[str] ( identifier[random] . identifier[randint... | def do_query(self, query, timeout=DEFAULT_TIMEOUT, tz=pytz.timezone('US/Pacific')):
"""
Query structure is as follows:
query = {
# We bind UUIDs found as the result of a Brick query to a variable name
# that we can use later.
# Each variable definition has the fo... |
def check_files(self, paths=None):
"""Run all checks on the paths."""
if paths is None:
paths = self.paths
report = self.options.report
runner = self.runner
report.start()
try:
for path in paths:
if os.path.isdir(path):
... | def function[check_files, parameter[self, paths]]:
constant[Run all checks on the paths.]
if compare[name[paths] is constant[None]] begin[:]
variable[paths] assign[=] name[self].paths
variable[report] assign[=] name[self].options.report
variable[runner] assign[=] name[sel... | keyword[def] identifier[check_files] ( identifier[self] , identifier[paths] = keyword[None] ):
literal[string]
keyword[if] identifier[paths] keyword[is] keyword[None] :
identifier[paths] = identifier[self] . identifier[paths]
identifier[report] = identifier[self] . identif... | def check_files(self, paths=None):
"""Run all checks on the paths."""
if paths is None:
paths = self.paths # depends on [control=['if'], data=['paths']]
report = self.options.report
runner = self.runner
report.start()
try:
for path in paths:
if os.path.isdir(path):
... |
def FromFile(self, filePath: str) -> bool:
"""
Load image from a file.
filePath: str.
Return bool, True if succeed otherwise False.
"""
self.Release()
self._bitmap = _DllClient.instance().dll.BitmapFromFile(ctypes.c_wchar_p(filePath))
self._getsize()
... | def function[FromFile, parameter[self, filePath]]:
constant[
Load image from a file.
filePath: str.
Return bool, True if succeed otherwise False.
]
call[name[self].Release, parameter[]]
name[self]._bitmap assign[=] call[call[name[_DllClient].instance, parameter[]]... | keyword[def] identifier[FromFile] ( identifier[self] , identifier[filePath] : identifier[str] )-> identifier[bool] :
literal[string]
identifier[self] . identifier[Release] ()
identifier[self] . identifier[_bitmap] = identifier[_DllClient] . identifier[instance] (). identifier[dll] . identi... | def FromFile(self, filePath: str) -> bool:
"""
Load image from a file.
filePath: str.
Return bool, True if succeed otherwise False.
"""
self.Release()
self._bitmap = _DllClient.instance().dll.BitmapFromFile(ctypes.c_wchar_p(filePath))
self._getsize()
return self._bitm... |
def update_pull_request(self, git_pull_request_to_update, repository_id, pull_request_id, project=None):
"""UpdatePullRequest.
[Preview API] Update a pull request
:param :class:`<GitPullRequest> <azure.devops.v5_1.git.models.GitPullRequest>` git_pull_request_to_update: The pull request content t... | def function[update_pull_request, parameter[self, git_pull_request_to_update, repository_id, pull_request_id, project]]:
constant[UpdatePullRequest.
[Preview API] Update a pull request
:param :class:`<GitPullRequest> <azure.devops.v5_1.git.models.GitPullRequest>` git_pull_request_to_update: The ... | keyword[def] identifier[update_pull_request] ( identifier[self] , identifier[git_pull_request_to_update] , identifier[repository_id] , identifier[pull_request_id] , identifier[project] = keyword[None] ):
literal[string]
identifier[route_values] ={}
keyword[if] identifier[project] keyword... | def update_pull_request(self, git_pull_request_to_update, repository_id, pull_request_id, project=None):
"""UpdatePullRequest.
[Preview API] Update a pull request
:param :class:`<GitPullRequest> <azure.devops.v5_1.git.models.GitPullRequest>` git_pull_request_to_update: The pull request content that ... |
def send_extended(self, address, timestamp, value):
"""Queue an extended datapoint (ie. a string), return True/False for success.
Arguments:
address -- uint64_t representing a unique metric.
timestamp -- uint64_t representing number of nanoseconds (10^-9) since epoch.
value -- s... | def function[send_extended, parameter[self, address, timestamp, value]]:
constant[Queue an extended datapoint (ie. a string), return True/False for success.
Arguments:
address -- uint64_t representing a unique metric.
timestamp -- uint64_t representing number of nanoseconds (10^-9) sinc... | keyword[def] identifier[send_extended] ( identifier[self] , identifier[address] , identifier[timestamp] , identifier[value] ):
literal[string]
keyword[if] identifier[self] . identifier[marquise_ctx] keyword[is] keyword[None] :
keyword[raise] identifier[ValueError] ( literal[string]... | def send_extended(self, address, timestamp, value):
"""Queue an extended datapoint (ie. a string), return True/False for success.
Arguments:
address -- uint64_t representing a unique metric.
timestamp -- uint64_t representing number of nanoseconds (10^-9) since epoch.
value -- strin... |
def balance(self, account):
"""
Return the balance, a tuple with the eth and ocn balance.
:param account: Account instance to return the balance of
:return: Balance tuple of (eth, ocn)
"""
return Balance(self._keeper.get_ether_balance(account.address),
... | def function[balance, parameter[self, account]]:
constant[
Return the balance, a tuple with the eth and ocn balance.
:param account: Account instance to return the balance of
:return: Balance tuple of (eth, ocn)
]
return[call[name[Balance], parameter[call[name[self]._keeper.... | keyword[def] identifier[balance] ( identifier[self] , identifier[account] ):
literal[string]
keyword[return] identifier[Balance] ( identifier[self] . identifier[_keeper] . identifier[get_ether_balance] ( identifier[account] . identifier[address] ),
identifier[self] . identifier[_keeper] .... | def balance(self, account):
"""
Return the balance, a tuple with the eth and ocn balance.
:param account: Account instance to return the balance of
:return: Balance tuple of (eth, ocn)
"""
return Balance(self._keeper.get_ether_balance(account.address), self._keeper.token.get_tok... |
def _notify_delete(self, index_or_slice):
"""Notify about a deletion at an index_or_slice.
:return: a function that notifies about an add at the same place.
"""
if isinstance(index_or_slice, int):
length = len(self)
if -length <= index_or_slice < length:
... | def function[_notify_delete, parameter[self, index_or_slice]]:
constant[Notify about a deletion at an index_or_slice.
:return: a function that notifies about an add at the same place.
]
if call[name[isinstance], parameter[name[index_or_slice], name[int]]] begin[:]
variab... | keyword[def] identifier[_notify_delete] ( identifier[self] , identifier[index_or_slice] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[index_or_slice] , identifier[int] ):
identifier[length] = identifier[len] ( identifier[self] )
keyword[if] - identifi... | def _notify_delete(self, index_or_slice):
"""Notify about a deletion at an index_or_slice.
:return: a function that notifies about an add at the same place.
"""
if isinstance(index_or_slice, int):
length = len(self)
if -length <= index_or_slice < length:
self._notify... |
def get_network_project(network_id, **kwargs):
"""
get the project that a network is in
"""
net_proj = db.DBSession.query(Project).join(Network, and_(Project.id==Network.id, Network.id==network_id)).first()
if net_proj is None:
raise HydraError("Network %s not found"% network_id)
... | def function[get_network_project, parameter[network_id]]:
constant[
get the project that a network is in
]
variable[net_proj] assign[=] call[call[call[name[db].DBSession.query, parameter[name[Project]]].join, parameter[name[Network], call[name[and_], parameter[compare[name[Project].id equal[... | keyword[def] identifier[get_network_project] ( identifier[network_id] ,** identifier[kwargs] ):
literal[string]
identifier[net_proj] = identifier[db] . identifier[DBSession] . identifier[query] ( identifier[Project] ). identifier[join] ( identifier[Network] , identifier[and_] ( identifier[Project] . ident... | def get_network_project(network_id, **kwargs):
"""
get the project that a network is in
"""
net_proj = db.DBSession.query(Project).join(Network, and_(Project.id == Network.id, Network.id == network_id)).first()
if net_proj is None:
raise HydraError('Network %s not found' % network_id) #... |
def get_source_class(self, _class):
"""
Return the Java source code of a whole class
:param _class: `ClassDefItem` object, to get the source from
:return:
"""
if not _class.get_name() in self.classes:
return ""
return self.classes[_class.get_name()] | def function[get_source_class, parameter[self, _class]]:
constant[
Return the Java source code of a whole class
:param _class: `ClassDefItem` object, to get the source from
:return:
]
if <ast.UnaryOp object at 0x7da20c7ca7a0> begin[:]
return[constant[]]
retur... | keyword[def] identifier[get_source_class] ( identifier[self] , identifier[_class] ):
literal[string]
keyword[if] keyword[not] identifier[_class] . identifier[get_name] () keyword[in] identifier[self] . identifier[classes] :
keyword[return] literal[string]
keyword[return] ... | def get_source_class(self, _class):
"""
Return the Java source code of a whole class
:param _class: `ClassDefItem` object, to get the source from
:return:
"""
if not _class.get_name() in self.classes:
return '' # depends on [control=['if'], data=[]]
return self.clas... |
def _set_overlay_service_policy_brief_state(self, v, load=False):
"""
Setter method for overlay_service_policy_brief_state, mapped from YANG variable /overlay_service_policy_brief_state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_overlay_service_policy_br... | def function[_set_overlay_service_policy_brief_state, parameter[self, v, load]]:
constant[
Setter method for overlay_service_policy_brief_state, mapped from YANG variable /overlay_service_policy_brief_state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_... | keyword[def] identifier[_set_overlay_service_policy_brief_state] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
k... | def _set_overlay_service_policy_brief_state(self, v, load=False):
"""
Setter method for overlay_service_policy_brief_state, mapped from YANG variable /overlay_service_policy_brief_state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_overlay_service_policy_br... |
def initialize_layers(self, layers=None):
"""Sets up the Lasagne layers
:param layers: The dictionary of layers, or a
:class:`lasagne.Layers` instance, describing the underlying
network
:return: the output layer of the underlying lasagne network.
:seealso: :ref:`layer-... | def function[initialize_layers, parameter[self, layers]]:
constant[Sets up the Lasagne layers
:param layers: The dictionary of layers, or a
:class:`lasagne.Layers` instance, describing the underlying
network
:return: the output layer of the underlying lasagne network.
... | keyword[def] identifier[initialize_layers] ( identifier[self] , identifier[layers] = keyword[None] ):
literal[string]
keyword[if] identifier[layers] keyword[is] keyword[not] keyword[None] :
identifier[self] . identifier[layers] = identifier[layers]
identifier[self] . iden... | def initialize_layers(self, layers=None):
"""Sets up the Lasagne layers
:param layers: The dictionary of layers, or a
:class:`lasagne.Layers` instance, describing the underlying
network
:return: the output layer of the underlying lasagne network.
:seealso: :ref:`layer-def`... |
def add_to_typedef(typedef_curr, obo_line):
"""Add new fields to the current typedef."""
if obo_line[:4] == "id: ":
assert not typedef_curr.item_id
item_id = obo_line[4:]
typedef_curr.item_id = item_id
elif obo_line[:6] == "name: ":
assert not typedef_curr.name
typede... | def function[add_to_typedef, parameter[typedef_curr, obo_line]]:
constant[Add new fields to the current typedef.]
if compare[call[name[obo_line]][<ast.Slice object at 0x7da18bc73190>] equal[==] constant[id: ]] begin[:]
assert[<ast.UnaryOp object at 0x7da18bc70460>]
variable[item_... | keyword[def] identifier[add_to_typedef] ( identifier[typedef_curr] , identifier[obo_line] ):
literal[string]
keyword[if] identifier[obo_line] [: literal[int] ]== literal[string] :
keyword[assert] keyword[not] identifier[typedef_curr] . identifier[item_id]
identifier[item_id] = identif... | def add_to_typedef(typedef_curr, obo_line):
"""Add new fields to the current typedef."""
if obo_line[:4] == 'id: ':
assert not typedef_curr.item_id
item_id = obo_line[4:]
typedef_curr.item_id = item_id # depends on [control=['if'], data=[]]
elif obo_line[:6] == 'name: ':
ass... |
def periodogram_auto(self, oversampling=5, nyquist_factor=3,
return_periods=True):
"""Compute the periodogram on an automatically-determined grid
This function uses heuristic arguments to choose a suitable frequency
grid for the data. Note that depending on the data win... | def function[periodogram_auto, parameter[self, oversampling, nyquist_factor, return_periods]]:
constant[Compute the periodogram on an automatically-determined grid
This function uses heuristic arguments to choose a suitable frequency
grid for the data. Note that depending on the data window fun... | keyword[def] identifier[periodogram_auto] ( identifier[self] , identifier[oversampling] = literal[int] , identifier[nyquist_factor] = literal[int] ,
identifier[return_periods] = keyword[True] ):
literal[string]
identifier[N] = identifier[len] ( identifier[self] . identifier[t] )
identifie... | def periodogram_auto(self, oversampling=5, nyquist_factor=3, return_periods=True):
"""Compute the periodogram on an automatically-determined grid
This function uses heuristic arguments to choose a suitable frequency
grid for the data. Note that depending on the data window function,
the mod... |
def parent(self):
"""
Return the parent scope.
:return: FoldScope or None
"""
if TextBlockHelper.get_fold_lvl(self._trigger) > 0 and \
self._trigger.blockNumber():
block = self._trigger.previous()
ref_lvl = self.trigger_level - 1
... | def function[parent, parameter[self]]:
constant[
Return the parent scope.
:return: FoldScope or None
]
if <ast.BoolOp object at 0x7da18f721420> begin[:]
variable[block] assign[=] call[name[self]._trigger.previous, parameter[]]
variable[ref_lvl] as... | keyword[def] identifier[parent] ( identifier[self] ):
literal[string]
keyword[if] identifier[TextBlockHelper] . identifier[get_fold_lvl] ( identifier[self] . identifier[_trigger] )> literal[int] keyword[and] identifier[self] . identifier[_trigger] . identifier[blockNumber] ():
ident... | def parent(self):
"""
Return the parent scope.
:return: FoldScope or None
"""
if TextBlockHelper.get_fold_lvl(self._trigger) > 0 and self._trigger.blockNumber():
block = self._trigger.previous()
ref_lvl = self.trigger_level - 1
while block.blockNumber() and (not ... |
def p_expression_lessthan(self, p):
'expression : expression LT expression'
p[0] = LessThan(p[1], p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | def function[p_expression_lessthan, parameter[self, p]]:
constant[expression : expression LT expression]
call[name[p]][constant[0]] assign[=] call[name[LessThan], parameter[call[name[p]][constant[1]], call[name[p]][constant[3]]]]
call[name[p].set_lineno, parameter[constant[0], call[name[p].linen... | keyword[def] identifier[p_expression_lessthan] ( identifier[self] , identifier[p] ):
literal[string]
identifier[p] [ literal[int] ]= identifier[LessThan] ( identifier[p] [ literal[int] ], identifier[p] [ literal[int] ], identifier[lineno] = identifier[p] . identifier[lineno] ( literal[int] ))
... | def p_expression_lessthan(self, p):
"""expression : expression LT expression"""
p[0] = LessThan(p[1], p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) |
def raise_not_enough_arguments(self, string):
"""
Raises an errors.ArgumentError if not enough arguments were supplied.
Takes care of formatting for detailed error messages.
Arguments:
string (str): The string of the phrase for which there weren't enough
arguments.
Raises:
errors.ArgumentErr... | def function[raise_not_enough_arguments, parameter[self, string]]:
constant[
Raises an errors.ArgumentError if not enough arguments were supplied.
Takes care of formatting for detailed error messages.
Arguments:
string (str): The string of the phrase for which there weren't enough
arguments.
... | keyword[def] identifier[raise_not_enough_arguments] ( identifier[self] , identifier[string] ):
literal[string]
identifier[requested] = identifier[errors] . identifier[number] ( identifier[self] . identifier[counter] + literal[int] )
identifier[number] = identifier[len] ( identifier[self] . identifier[pos... | def raise_not_enough_arguments(self, string):
"""
Raises an errors.ArgumentError if not enough arguments were supplied.
Takes care of formatting for detailed error messages.
Arguments:
string (str): The string of the phrase for which there weren't enough
arguments.
Raises:
errors.ArgumentEr... |
def configValue(self):
""" Creates a QPen made of the children's config values.
"""
if not self.data:
return None
else:
pen = QtGui.QPen()
pen.setCosmetic(True)
pen.setColor(self.colorCti.configValue)
style = self.styleCti.confi... | def function[configValue, parameter[self]]:
constant[ Creates a QPen made of the children's config values.
]
if <ast.UnaryOp object at 0x7da1b04d1b10> begin[:]
return[constant[None]] | keyword[def] identifier[configValue] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[data] :
keyword[return] keyword[None]
keyword[else] :
identifier[pen] = identifier[QtGui] . identifier[QPen] ()
ident... | def configValue(self):
""" Creates a QPen made of the children's config values.
"""
if not self.data:
return None # depends on [control=['if'], data=[]]
else:
pen = QtGui.QPen()
pen.setCosmetic(True)
pen.setColor(self.colorCti.configValue)
style = self.styleC... |
def _get_base_component(self):
"""Returns Component protobuf message"""
comp = topology_pb2.Component()
comp.name = self.name
comp.spec = topology_pb2.ComponentObjectSpec.Value("PYTHON_CLASS_NAME")
comp.class_name = self.python_class_path
comp.config.CopyFrom(self._get_comp_config())
return ... | def function[_get_base_component, parameter[self]]:
constant[Returns Component protobuf message]
variable[comp] assign[=] call[name[topology_pb2].Component, parameter[]]
name[comp].name assign[=] name[self].name
name[comp].spec assign[=] call[name[topology_pb2].ComponentObjectSpec.Value,... | keyword[def] identifier[_get_base_component] ( identifier[self] ):
literal[string]
identifier[comp] = identifier[topology_pb2] . identifier[Component] ()
identifier[comp] . identifier[name] = identifier[self] . identifier[name]
identifier[comp] . identifier[spec] = identifier[topology_pb2] . ide... | def _get_base_component(self):
"""Returns Component protobuf message"""
comp = topology_pb2.Component()
comp.name = self.name
comp.spec = topology_pb2.ComponentObjectSpec.Value('PYTHON_CLASS_NAME')
comp.class_name = self.python_class_path
comp.config.CopyFrom(self._get_comp_config())
return ... |
def cdsparse(self, record):
"""
Finds core genes, and records gene names and sequences in dictionaries
:param record: SeqIO record
"""
try:
# Find genes that are present in all strains of interest - the number of times the gene is found is
# equal to the n... | def function[cdsparse, parameter[self, record]]:
constant[
Finds core genes, and records gene names and sequences in dictionaries
:param record: SeqIO record
]
<ast.Try object at 0x7da1b1e094b0> | keyword[def] identifier[cdsparse] ( identifier[self] , identifier[record] ):
literal[string]
keyword[try] :
keyword[if] identifier[self] . identifier[genes] [ identifier[self] . identifier[genenames] [ identifier[record] . identifier[id] ]]== identifier[len]... | def cdsparse(self, record):
"""
Finds core genes, and records gene names and sequences in dictionaries
:param record: SeqIO record
"""
try:
# Find genes that are present in all strains of interest - the number of times the gene is found is
# equal to the number of strains... |
def get_by_provider_display_name(self, provider_display_name):
"""
Gets a SAN Manager by provider display name.
Args:
provider_display_name: Name of the Provider Display Name
Returns:
dict: SAN Manager.
"""
san_managers = self._client.get_all()
... | def function[get_by_provider_display_name, parameter[self, provider_display_name]]:
constant[
Gets a SAN Manager by provider display name.
Args:
provider_display_name: Name of the Provider Display Name
Returns:
dict: SAN Manager.
]
variable[san_m... | keyword[def] identifier[get_by_provider_display_name] ( identifier[self] , identifier[provider_display_name] ):
literal[string]
identifier[san_managers] = identifier[self] . identifier[_client] . identifier[get_all] ()
identifier[result] =[ identifier[x] keyword[for] identifier[x] keywo... | def get_by_provider_display_name(self, provider_display_name):
"""
Gets a SAN Manager by provider display name.
Args:
provider_display_name: Name of the Provider Display Name
Returns:
dict: SAN Manager.
"""
san_managers = self._client.get_all()
resul... |
async def executemany(self, command: str, args, *, timeout: float=None):
"""Execute an SQL *command* for each sequence of arguments in *args*.
Example:
.. code-block:: pycon
>>> await con.executemany('''
... INSERT INTO mytab (a) VALUES ($1, $2, $3);
..... | <ast.AsyncFunctionDef object at 0x7da1b1957040> | keyword[async] keyword[def] identifier[executemany] ( identifier[self] , identifier[command] : identifier[str] , identifier[args] ,*, identifier[timeout] : identifier[float] = keyword[None] ):
literal[string]
identifier[self] . identifier[_check_open] ()
keyword[return] keyword[await] i... | async def executemany(self, command: str, args, *, timeout: float=None):
"""Execute an SQL *command* for each sequence of arguments in *args*.
Example:
.. code-block:: pycon
>>> await con.executemany('''
... INSERT INTO mytab (a) VALUES ($1, $2, $3);
... ''... |
def pctile(self,pct,res=1000):
"""Returns the desired percentile of the distribution.
Will only work if properly normalized. Designed to mimic
the `ppf` method of the `scipy.stats` random variate objects.
Works by gridding the CDF at a given resolution and matching the nearest
... | def function[pctile, parameter[self, pct, res]]:
constant[Returns the desired percentile of the distribution.
Will only work if properly normalized. Designed to mimic
the `ppf` method of the `scipy.stats` random variate objects.
Works by gridding the CDF at a given resolution and match... | keyword[def] identifier[pctile] ( identifier[self] , identifier[pct] , identifier[res] = literal[int] ):
literal[string]
identifier[grid] = identifier[np] . identifier[linspace] ( identifier[self] . identifier[minval] , identifier[self] . identifier[maxval] , identifier[res] )
keyword[retu... | def pctile(self, pct, res=1000):
"""Returns the desired percentile of the distribution.
Will only work if properly normalized. Designed to mimic
the `ppf` method of the `scipy.stats` random variate objects.
Works by gridding the CDF at a given resolution and matching the nearest
po... |
def _finaliseRequest(self, request, status, content, mimetype='text/plain'):
"""
Finalises the request.
@param request: The HTTP Request.
@type request: C{http.Request}
@param status: The HTTP status code.
@type status: C{int}
@param content: The content of the r... | def function[_finaliseRequest, parameter[self, request, status, content, mimetype]]:
constant[
Finalises the request.
@param request: The HTTP Request.
@type request: C{http.Request}
@param status: The HTTP status code.
@type status: C{int}
@param content: The co... | keyword[def] identifier[_finaliseRequest] ( identifier[self] , identifier[request] , identifier[status] , identifier[content] , identifier[mimetype] = literal[string] ):
literal[string]
identifier[request] . identifier[setResponseCode] ( identifier[status] )
identifier[request] . identifi... | def _finaliseRequest(self, request, status, content, mimetype='text/plain'):
"""
Finalises the request.
@param request: The HTTP Request.
@type request: C{http.Request}
@param status: The HTTP status code.
@type status: C{int}
@param content: The content of the respo... |
def add_error(self, group, term, sub_term, value):
"""For records that are not defined as terms, either add it to the
errors list."""
self._errors[(group, term, sub_term)] = value | def function[add_error, parameter[self, group, term, sub_term, value]]:
constant[For records that are not defined as terms, either add it to the
errors list.]
call[name[self]._errors][tuple[[<ast.Name object at 0x7da20c7943d0>, <ast.Name object at 0x7da20c795de0>, <ast.Name object at 0x7da20c796... | keyword[def] identifier[add_error] ( identifier[self] , identifier[group] , identifier[term] , identifier[sub_term] , identifier[value] ):
literal[string]
identifier[self] . identifier[_errors] [( identifier[group] , identifier[term] , identifier[sub_term] )]= identifier[value] | def add_error(self, group, term, sub_term, value):
"""For records that are not defined as terms, either add it to the
errors list."""
self._errors[group, term, sub_term] = value |
def get_gif_frames(img):
"""
Extracts the frames from an animated gif.
:param img: A PIL Image object
:return: An array of PIL image objects, each corresponding to a frame in the animation.
"""
gif_frames = []
n = 0
while img:
if img.mode != "RGB":
image = img.convert... | def function[get_gif_frames, parameter[img]]:
constant[
Extracts the frames from an animated gif.
:param img: A PIL Image object
:return: An array of PIL image objects, each corresponding to a frame in the animation.
]
variable[gif_frames] assign[=] list[[]]
variable[n] assign[=]... | keyword[def] identifier[get_gif_frames] ( identifier[img] ):
literal[string]
identifier[gif_frames] =[]
identifier[n] = literal[int]
keyword[while] identifier[img] :
keyword[if] identifier[img] . identifier[mode] != literal[string] :
identifier[image] = identifier[img] . ... | def get_gif_frames(img):
"""
Extracts the frames from an animated gif.
:param img: A PIL Image object
:return: An array of PIL image objects, each corresponding to a frame in the animation.
"""
gif_frames = []
n = 0
while img:
if img.mode != 'RGB':
image = img.convert... |
def namedb_create(path, genesis_block):
"""
Create a sqlite3 db at the given path.
Create all the tables and indexes we need.
"""
global BLOCKSTACK_DB_SCRIPT
if os.path.exists( path ):
raise Exception("Database '%s' already exists" % path)
lines = [l + ";" for l in BLOCKSTACK_DB_S... | def function[namedb_create, parameter[path, genesis_block]]:
constant[
Create a sqlite3 db at the given path.
Create all the tables and indexes we need.
]
<ast.Global object at 0x7da1b17235b0>
if call[name[os].path.exists, parameter[name[path]]] begin[:]
<ast.Raise object at 0x7d... | keyword[def] identifier[namedb_create] ( identifier[path] , identifier[genesis_block] ):
literal[string]
keyword[global] identifier[BLOCKSTACK_DB_SCRIPT]
keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[path] ):
keyword[raise] identifier[Exception] ( liter... | def namedb_create(path, genesis_block):
"""
Create a sqlite3 db at the given path.
Create all the tables and indexes we need.
"""
global BLOCKSTACK_DB_SCRIPT
if os.path.exists(path):
raise Exception("Database '%s' already exists" % path) # depends on [control=['if'], data=[]]
lines ... |
def cuboid(target, throat_diameter='throat.diameter',
throat_length='throat.length'):
r"""
Calculate surface area for a cuboid throat
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated a... | def function[cuboid, parameter[target, throat_diameter, throat_length]]:
constant[
Calculate surface area for a cuboid throat
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated array, and also ... | keyword[def] identifier[cuboid] ( identifier[target] , identifier[throat_diameter] = literal[string] ,
identifier[throat_length] = literal[string] ):
literal[string]
identifier[D] = identifier[target] [ identifier[throat_diameter] ]
identifier[L] = identifier[target] [ identifier[throat_length] ]
... | def cuboid(target, throat_diameter='throat.diameter', throat_length='throat.length'):
"""
Calculate surface area for a cuboid throat
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated array, and al... |
def move_group_in_parent(self, group = None, index = None):
"""Move group to another position in group's parent.
index must be a valid index of group.parent.groups
"""
if group is None or index is None:
raise KPError("group and index must be set")
e... | def function[move_group_in_parent, parameter[self, group, index]]:
constant[Move group to another position in group's parent.
index must be a valid index of group.parent.groups
]
if <ast.BoolOp object at 0x7da1b2519570> begin[:]
<ast.Raise object at 0x7da1b25196c0> | keyword[def] identifier[move_group_in_parent] ( identifier[self] , identifier[group] = keyword[None] , identifier[index] = keyword[None] ):
literal[string]
keyword[if] identifier[group] keyword[is] keyword[None] keyword[or] identifier[index] keyword[is] keyword[None] :
keyword[... | def move_group_in_parent(self, group=None, index=None):
"""Move group to another position in group's parent.
index must be a valid index of group.parent.groups
"""
if group is None or index is None:
raise KPError('group and index must be set') # depends on [control=['if'], dat... |
def _init_application(self, application=None):
"""Initialize application object for torext app, if a existed application is passed,
then just use this one without make a new one"""
if application:
self.application = application
else:
self.application = self.make_a... | def function[_init_application, parameter[self, application]]:
constant[Initialize application object for torext app, if a existed application is passed,
then just use this one without make a new one]
if name[application] begin[:]
name[self].application assign[=] name[application... | keyword[def] identifier[_init_application] ( identifier[self] , identifier[application] = keyword[None] ):
literal[string]
keyword[if] identifier[application] :
identifier[self] . identifier[application] = identifier[application]
keyword[else] :
identifier[self]... | def _init_application(self, application=None):
"""Initialize application object for torext app, if a existed application is passed,
then just use this one without make a new one"""
if application:
self.application = application # depends on [control=['if'], data=[]]
else:
self.appli... |
def _write_content_types_stream(phys_writer, parts):
"""
Write ``[Content_Types].xml`` part to the physical package with an
appropriate content type lookup target for each part in *parts*.
"""
content_types_blob = serialize_part_xml(
_ContentTypesItem.xml_for(parts)
... | def function[_write_content_types_stream, parameter[phys_writer, parts]]:
constant[
Write ``[Content_Types].xml`` part to the physical package with an
appropriate content type lookup target for each part in *parts*.
]
variable[content_types_blob] assign[=] call[name[serialize_par... | keyword[def] identifier[_write_content_types_stream] ( identifier[phys_writer] , identifier[parts] ):
literal[string]
identifier[content_types_blob] = identifier[serialize_part_xml] (
identifier[_ContentTypesItem] . identifier[xml_for] ( identifier[parts] )
)
identifier[ph... | def _write_content_types_stream(phys_writer, parts):
"""
Write ``[Content_Types].xml`` part to the physical package with an
appropriate content type lookup target for each part in *parts*.
"""
content_types_blob = serialize_part_xml(_ContentTypesItem.xml_for(parts))
phys_writer.write... |
def stmt_lambdef_handle(self, original, loc, tokens):
"""Process multi-line lambdef statements."""
if len(tokens) == 2:
params, stmts = tokens
elif len(tokens) == 3:
params, stmts, last = tokens
if "tests" in tokens:
stmts = stmts.asList() + ["... | def function[stmt_lambdef_handle, parameter[self, original, loc, tokens]]:
constant[Process multi-line lambdef statements.]
if compare[call[name[len], parameter[name[tokens]]] equal[==] constant[2]] begin[:]
<ast.Tuple object at 0x7da20c6c7ac0> assign[=] name[tokens]
variable[nam... | keyword[def] identifier[stmt_lambdef_handle] ( identifier[self] , identifier[original] , identifier[loc] , identifier[tokens] ):
literal[string]
keyword[if] identifier[len] ( identifier[tokens] )== literal[int] :
identifier[params] , identifier[stmts] = identifier[tokens]
ke... | def stmt_lambdef_handle(self, original, loc, tokens):
"""Process multi-line lambdef statements."""
if len(tokens) == 2:
(params, stmts) = tokens # depends on [control=['if'], data=[]]
elif len(tokens) == 3:
(params, stmts, last) = tokens
if 'tests' in tokens:
stmts = stm... |
def add_filter_rule(
self, name, condition, filters, actions, active=1, way='in'):
"""
:param: name filter name
:param: condition allof or anyof
:param: filters dict of filters
:param: actions dict of actions
:param: way string discribing if filter is for 'in'... | def function[add_filter_rule, parameter[self, name, condition, filters, actions, active, way]]:
constant[
:param: name filter name
:param: condition allof or anyof
:param: filters dict of filters
:param: actions dict of actions
:param: way string discribing if filter is f... | keyword[def] identifier[add_filter_rule] (
identifier[self] , identifier[name] , identifier[condition] , identifier[filters] , identifier[actions] , identifier[active] = literal[int] , identifier[way] = literal[string] ):
literal[string]
identifier[filters] [ literal[string] ]= identifier[conditi... | def add_filter_rule(self, name, condition, filters, actions, active=1, way='in'):
"""
:param: name filter name
:param: condition allof or anyof
:param: filters dict of filters
:param: actions dict of actions
:param: way string discribing if filter is for 'in' or 'out' message... |
def replace(self, **kw):
"""Return datetime with new specified fields given as arguments.
For example, dt.replace(days=4) would return a new datetime_tz object with
exactly the same as dt but with the days attribute equal to 4.
Any attribute can be replaced, but tzinfo can not be set to None.
Arg... | def function[replace, parameter[self]]:
constant[Return datetime with new specified fields given as arguments.
For example, dt.replace(days=4) would return a new datetime_tz object with
exactly the same as dt but with the days attribute equal to 4.
Any attribute can be replaced, but tzinfo can not... | keyword[def] identifier[replace] ( identifier[self] ,** identifier[kw] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[kw] :
keyword[if] identifier[kw] [ literal[string] ] keyword[is] keyword[None] :
keyword[raise] identifier[TypeError] ( literal[string] )
... | def replace(self, **kw):
"""Return datetime with new specified fields given as arguments.
For example, dt.replace(days=4) would return a new datetime_tz object with
exactly the same as dt but with the days attribute equal to 4.
Any attribute can be replaced, but tzinfo can not be set to None.
Arg... |
def wrap(self, wrapper):
"""
Returns the first function passed as an argument to the second,
allowing you to adjust arguments, run code before and after, and
conditionally execute the original function.
"""
def wrapped(*args, **kwargs):
if kwargs:
... | def function[wrap, parameter[self, wrapper]]:
constant[
Returns the first function passed as an argument to the second,
allowing you to adjust arguments, run code before and after, and
conditionally execute the original function.
]
def function[wrapped, parameter[]]:
... | keyword[def] identifier[wrap] ( identifier[self] , identifier[wrapper] ):
literal[string]
keyword[def] identifier[wrapped] (* identifier[args] ,** identifier[kwargs] ):
keyword[if] identifier[kwargs] :
identifier[kwargs] [ literal[string] ]= identifier[self] . ident... | def wrap(self, wrapper):
"""
Returns the first function passed as an argument to the second,
allowing you to adjust arguments, run code before and after, and
conditionally execute the original function.
"""
def wrapped(*args, **kwargs):
if kwargs:
kwargs['obj... |
def _load_defaults(self, default='settings.py'):
'''
Load the default settings
'''
if default[-3:] == '.py':
default = default[:-3]
self.my_settings = {}
try:
settings = importlib.import_module(default)
self.my_settings = self._convert... | def function[_load_defaults, parameter[self, default]]:
constant[
Load the default settings
]
if compare[call[name[default]][<ast.Slice object at 0x7da1b19ee890>] equal[==] constant[.py]] begin[:]
variable[default] assign[=] call[name[default]][<ast.Slice object at 0x7da1... | keyword[def] identifier[_load_defaults] ( identifier[self] , identifier[default] = literal[string] ):
literal[string]
keyword[if] identifier[default] [- literal[int] :]== literal[string] :
identifier[default] = identifier[default] [:- literal[int] ]
identifier[self] . identi... | def _load_defaults(self, default='settings.py'):
"""
Load the default settings
"""
if default[-3:] == '.py':
default = default[:-3] # depends on [control=['if'], data=[]]
self.my_settings = {}
try:
settings = importlib.import_module(default)
self.my_settings = se... |
def _build_predict(self, Xnew, full_cov=False):
"""
Compute the mean and variance of the latent function at some new points.
Note that this is very similar to the SGPR prediction, for which
there are notes in the SGPR notebook.
:param Xnew: Point to predict at.
"""
... | def function[_build_predict, parameter[self, Xnew, full_cov]]:
constant[
Compute the mean and variance of the latent function at some new points.
Note that this is very similar to the SGPR prediction, for which
there are notes in the SGPR notebook.
:param Xnew: Point to predict a... | keyword[def] identifier[_build_predict] ( identifier[self] , identifier[Xnew] , identifier[full_cov] = keyword[False] ):
literal[string]
identifier[pX] = identifier[DiagonalGaussian] ( identifier[self] . identifier[X_mean] , identifier[self] . identifier[X_var] )
identifier[num_inducing] ... | def _build_predict(self, Xnew, full_cov=False):
"""
Compute the mean and variance of the latent function at some new points.
Note that this is very similar to the SGPR prediction, for which
there are notes in the SGPR notebook.
:param Xnew: Point to predict at.
"""
pX = D... |
def plot_sfs(s, yscale='log', bins=None, n=None,
clip_endpoints=True, label=None, plot_kwargs=None,
ax=None):
"""Plot a site frequency spectrum.
Parameters
----------
s : array_like, int, shape (n_chromosomes,)
Site frequency spectrum.
yscale : string, optional
... | def function[plot_sfs, parameter[s, yscale, bins, n, clip_endpoints, label, plot_kwargs, ax]]:
constant[Plot a site frequency spectrum.
Parameters
----------
s : array_like, int, shape (n_chromosomes,)
Site frequency spectrum.
yscale : string, optional
Y axis scale.
bins : i... | keyword[def] identifier[plot_sfs] ( identifier[s] , identifier[yscale] = literal[string] , identifier[bins] = keyword[None] , identifier[n] = keyword[None] ,
identifier[clip_endpoints] = keyword[True] , identifier[label] = keyword[None] , identifier[plot_kwargs] = keyword[None] ,
identifier[ax] = keyword[None] ):
... | def plot_sfs(s, yscale='log', bins=None, n=None, clip_endpoints=True, label=None, plot_kwargs=None, ax=None):
"""Plot a site frequency spectrum.
Parameters
----------
s : array_like, int, shape (n_chromosomes,)
Site frequency spectrum.
yscale : string, optional
Y axis scale.
bin... |
def setShowRichText( self, state ):
"""
Sets whether or not the delegate should render rich text information \
as HTML when drawing the contents of the item.
:param state | <bool>
"""
delegate = self.itemDelegate()
if isinstance(delegate, XTr... | def function[setShowRichText, parameter[self, state]]:
constant[
Sets whether or not the delegate should render rich text information as HTML when drawing the contents of the item.
:param state | <bool>
]
variable[delegate] assign[=] call[name[self].itemDele... | keyword[def] identifier[setShowRichText] ( identifier[self] , identifier[state] ):
literal[string]
identifier[delegate] = identifier[self] . identifier[itemDelegate] ()
keyword[if] identifier[isinstance] ( identifier[delegate] , identifier[XTreeWidgetDelegate] ):
identifi... | def setShowRichText(self, state):
"""
Sets whether or not the delegate should render rich text information as HTML when drawing the contents of the item.
:param state | <bool>
"""
delegate = self.itemDelegate()
if isinstance(delegate, XTreeWidgetDelegate):
... |
def send_message(message: str, subject: str, recip: list, recip_email: list,
html_message: str = None):
"""
Sends message to specified value.
Source: Himanshu Shankar (https://github.com/iamhssingh)
Parameters
----------
message: str
Message that is to be sent to user.
... | def function[send_message, parameter[message, subject, recip, recip_email, html_message]]:
constant[
Sends message to specified value.
Source: Himanshu Shankar (https://github.com/iamhssingh)
Parameters
----------
message: str
Message that is to be sent to user.
subject: str
... | keyword[def] identifier[send_message] ( identifier[message] : identifier[str] , identifier[subject] : identifier[str] , identifier[recip] : identifier[list] , identifier[recip_email] : identifier[list] ,
identifier[html_message] : identifier[str] = keyword[None] ):
literal[string]
keyword[import] identi... | def send_message(message: str, subject: str, recip: list, recip_email: list, html_message: str=None):
"""
Sends message to specified value.
Source: Himanshu Shankar (https://github.com/iamhssingh)
Parameters
----------
message: str
Message that is to be sent to user.
subject: str
... |
def pressure(self):
"""The current pressure being applied on the tool in use,
normalized to the range [0, 1] and whether it has changed in this event.
If this axis does not exist on the current tool, this property is
(0, :obj:`False`).
Returns:
(float, bool): The current value of the the axis and whether... | def function[pressure, parameter[self]]:
constant[The current pressure being applied on the tool in use,
normalized to the range [0, 1] and whether it has changed in this event.
If this axis does not exist on the current tool, this property is
(0, :obj:`False`).
Returns:
(float, bool): The current ... | keyword[def] identifier[pressure] ( identifier[self] ):
literal[string]
identifier[pressure] = identifier[self] . identifier[_libinput] . identifier[libinput_event_tablet_tool_get_pressure] (
identifier[self] . identifier[_handle] )
identifier[changed] = identifier[self] . identifier[_libinput] . identi... | def pressure(self):
"""The current pressure being applied on the tool in use,
normalized to the range [0, 1] and whether it has changed in this event.
If this axis does not exist on the current tool, this property is
(0, :obj:`False`).
Returns:
(float, bool): The current value of the the axis and wheth... |
def addToDefinition(self, json_dict):
"""
The addToDefinition operation supports adding a definition
property to a hosted feature service. The result of this
operation is a response indicating success or failure with error
code and description.
This functi... | def function[addToDefinition, parameter[self, json_dict]]:
constant[
The addToDefinition operation supports adding a definition
property to a hosted feature service. The result of this
operation is a response indicating success or failure with error
code and descripti... | keyword[def] identifier[addToDefinition] ( identifier[self] , identifier[json_dict] ):
literal[string]
identifier[params] ={
literal[string] : literal[string] ,
literal[string] : identifier[json] . identifier[dumps] ( identifier[json_dict] ),
literal[string] : keyword[Fal... | def addToDefinition(self, json_dict):
"""
The addToDefinition operation supports adding a definition
property to a hosted feature service. The result of this
operation is a response indicating success or failure with error
code and description.
This function w... |
def run(self, concurrency=0, outline=False,
tail=False, dump=False, *args, **kwargs):
"""Kicks off the build/update of the stacks in the stack_definitions.
This is the main entry point for the Builder.
"""
plan = self._generate_plan(tail=tail)
if not plan.keys():
... | def function[run, parameter[self, concurrency, outline, tail, dump]]:
constant[Kicks off the build/update of the stacks in the stack_definitions.
This is the main entry point for the Builder.
]
variable[plan] assign[=] call[name[self]._generate_plan, parameter[]]
if <ast.UnaryO... | keyword[def] identifier[run] ( identifier[self] , identifier[concurrency] = literal[int] , identifier[outline] = keyword[False] ,
identifier[tail] = keyword[False] , identifier[dump] = keyword[False] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[plan] = identifier[self] ... | def run(self, concurrency=0, outline=False, tail=False, dump=False, *args, **kwargs):
"""Kicks off the build/update of the stacks in the stack_definitions.
This is the main entry point for the Builder.
"""
plan = self._generate_plan(tail=tail)
if not plan.keys():
logger.warn('WARNI... |
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt) | def function[_set_repo_options, parameter[repo, options]]:
constant[
Set the options to the repo.
]
variable[delimiters] assign[=] tuple[[<ast.Constant object at 0x7da18eb55450>, <ast.Constant object at 0x7da18eb57a00>]]
variable[pattern] assign[=] call[constant[|].join, parameter[call[n... | keyword[def] identifier[_set_repo_options] ( identifier[repo] , identifier[options] ):
literal[string]
identifier[delimiters] = literal[string] , literal[string]
identifier[pattern] = literal[string] . identifier[join] ( identifier[map] ( identifier[re] . identifier[escape] , identifier[delimiters] )... | def _set_repo_options(repo, options):
"""
Set the options to the repo.
"""
delimiters = ('[', ']')
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt) # depends on... |
async def get_response(self, path: str, scope: Scope) -> Response:
"""
Returns an HTTP response, given the incoming path, method and request headers.
"""
if scope["method"] not in ("GET", "HEAD"):
return PlainTextResponse("Method Not Allowed", status_code=405)
if pat... | <ast.AsyncFunctionDef object at 0x7da1b025fa60> | keyword[async] keyword[def] identifier[get_response] ( identifier[self] , identifier[path] : identifier[str] , identifier[scope] : identifier[Scope] )-> identifier[Response] :
literal[string]
keyword[if] identifier[scope] [ literal[string] ] keyword[not] keyword[in] ( literal[string] , literal[s... | async def get_response(self, path: str, scope: Scope) -> Response:
"""
Returns an HTTP response, given the incoming path, method and request headers.
"""
if scope['method'] not in ('GET', 'HEAD'):
return PlainTextResponse('Method Not Allowed', status_code=405) # depends on [control=['if... |
def _makeTimingRelative(absoluteDataList):
'''
Given normal pitch tier data, puts the times on a scale from 0 to 1
Input is a list of tuples of the form
([(time1, pitch1), (time2, pitch2),...]
Also returns the start and end time so that the process can be reversed
'''
timingSeq = [row[0] ... | def function[_makeTimingRelative, parameter[absoluteDataList]]:
constant[
Given normal pitch tier data, puts the times on a scale from 0 to 1
Input is a list of tuples of the form
([(time1, pitch1), (time2, pitch2),...]
Also returns the start and end time so that the process can be reversed
... | keyword[def] identifier[_makeTimingRelative] ( identifier[absoluteDataList] ):
literal[string]
identifier[timingSeq] =[ identifier[row] [ literal[int] ] keyword[for] identifier[row] keyword[in] identifier[absoluteDataList] ]
identifier[valueSeq] =[ identifier[list] ( identifier[row] [ literal[int]... | def _makeTimingRelative(absoluteDataList):
"""
Given normal pitch tier data, puts the times on a scale from 0 to 1
Input is a list of tuples of the form
([(time1, pitch1), (time2, pitch2),...]
Also returns the start and end time so that the process can be reversed
"""
timingSeq = [row[0] f... |
def _register_order_book_channels(self):
"""
Registers the binding for the order_book channels.
:return:
"""
channels = {'order_book': self.btcusd_ob_callback,
'order_book_btceur': self.btceur_ob_callback,
'order_book_eurusd': self.eurusd_o... | def function[_register_order_book_channels, parameter[self]]:
constant[
Registers the binding for the order_book channels.
:return:
]
variable[channels] assign[=] dictionary[[<ast.Constant object at 0x7da1b07bc4f0>, <ast.Constant object at 0x7da1b07bc4c0>, <ast.Constant object at... | keyword[def] identifier[_register_order_book_channels] ( identifier[self] ):
literal[string]
identifier[channels] ={ literal[string] : identifier[self] . identifier[btcusd_ob_callback] ,
literal[string] : identifier[self] . identifier[btceur_ob_callback] ,
literal[string] : identi... | def _register_order_book_channels(self):
"""
Registers the binding for the order_book channels.
:return:
"""
channels = {'order_book': self.btcusd_ob_callback, 'order_book_btceur': self.btceur_ob_callback, 'order_book_eurusd': self.eurusd_ob_callback, 'order_book_xrpusd': self.xrpusd_ob_... |
def radec2sky(ra, dec):
"""
Convert [ra], [dec] to [(ra[0], dec[0]),....]
and also ra,dec to [(ra,dec)] if ra/dec are not iterable
Parameters
----------
ra, dec : float or iterable
Sky coordinates
Returns
-------
sky : numpy.array
... | def function[radec2sky, parameter[ra, dec]]:
constant[
Convert [ra], [dec] to [(ra[0], dec[0]),....]
and also ra,dec to [(ra,dec)] if ra/dec are not iterable
Parameters
----------
ra, dec : float or iterable
Sky coordinates
Returns
-------
... | keyword[def] identifier[radec2sky] ( identifier[ra] , identifier[dec] ):
literal[string]
keyword[try] :
identifier[sky] = identifier[np] . identifier[array] ( identifier[list] ( identifier[zip] ( identifier[ra] , identifier[dec] )))
keyword[except] identifier[TypeError] :
... | def radec2sky(ra, dec):
"""
Convert [ra], [dec] to [(ra[0], dec[0]),....]
and also ra,dec to [(ra,dec)] if ra/dec are not iterable
Parameters
----------
ra, dec : float or iterable
Sky coordinates
Returns
-------
sky : numpy.array
... |
def generate(self, clusters, version=None):
"""
Generates HAProxy config file content based on a given list of
clusters.
"""
now = datetime.datetime.now()
sections = [
Section(
"Auto-generated by Lighthouse (%s)" % now.strftime("%c"),
... | def function[generate, parameter[self, clusters, version]]:
constant[
Generates HAProxy config file content based on a given list of
clusters.
]
variable[now] assign[=] call[name[datetime].datetime.now, parameter[]]
variable[sections] assign[=] list[[<ast.Call object at 0... | keyword[def] identifier[generate] ( identifier[self] , identifier[clusters] , identifier[version] = keyword[None] ):
literal[string]
identifier[now] = identifier[datetime] . identifier[datetime] . identifier[now] ()
identifier[sections] =[
identifier[Section] (
literal[s... | def generate(self, clusters, version=None):
"""
Generates HAProxy config file content based on a given list of
clusters.
"""
now = datetime.datetime.now()
sections = [Section('Auto-generated by Lighthouse (%s)' % now.strftime('%c'), self.global_stanza, self.defaults_stanza)]
meta... |
def download(self, job_id, destination=None, timeout=DEFAULT_TIMEOUT, retries=DEFAULT_RETRIES):
"""
Downloads all screenshots for given job_id to `destination` folder.
If `destination` is None, then screenshots will be saved in current directory.
"""
self._retries_num = 0
... | def function[download, parameter[self, job_id, destination, timeout, retries]]:
constant[
Downloads all screenshots for given job_id to `destination` folder.
If `destination` is None, then screenshots will be saved in current directory.
]
name[self]._retries_num assign[=] constan... | keyword[def] identifier[download] ( identifier[self] , identifier[job_id] , identifier[destination] = keyword[None] , identifier[timeout] = identifier[DEFAULT_TIMEOUT] , identifier[retries] = identifier[DEFAULT_RETRIES] ):
literal[string]
identifier[self] . identifier[_retries_num] = literal[int]
... | def download(self, job_id, destination=None, timeout=DEFAULT_TIMEOUT, retries=DEFAULT_RETRIES):
"""
Downloads all screenshots for given job_id to `destination` folder.
If `destination` is None, then screenshots will be saved in current directory.
"""
self._retries_num = 0
sleep(timeo... |
def refresh_session(self, sessionkey, refresh_token=None):
'''
Refresh Session Token
'''
if not refresh_token:
refresh_token = sessionkey
params = {
'appkey' : self.API_KEY,
'sessionkey' : sessionkey,
'refresh_token': refresh_token... | def function[refresh_session, parameter[self, sessionkey, refresh_token]]:
constant[
Refresh Session Token
]
if <ast.UnaryOp object at 0x7da1b25d97e0> begin[:]
variable[refresh_token] assign[=] name[sessionkey]
variable[params] assign[=] dictionary[[<ast.Constant ... | keyword[def] identifier[refresh_session] ( identifier[self] , identifier[sessionkey] , identifier[refresh_token] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[refresh_token] :
identifier[refresh_token] = identifier[sessionkey]
identifier[params] ={
... | def refresh_session(self, sessionkey, refresh_token=None):
"""
Refresh Session Token
"""
if not refresh_token:
refresh_token = sessionkey # depends on [control=['if'], data=[]]
params = {'appkey': self.API_KEY, 'sessionkey': sessionkey, 'refresh_token': refresh_token}
src = ''.j... |
def get_requirements_file_from_url(url):
"""fetches the requiremets from the url"""
response = requests.get(url)
if response.status_code == 200:
return StringIO(response.text)
else:
return StringIO("") | def function[get_requirements_file_from_url, parameter[url]]:
constant[fetches the requiremets from the url]
variable[response] assign[=] call[name[requests].get, parameter[name[url]]]
if compare[name[response].status_code equal[==] constant[200]] begin[:]
return[call[name[StringIO], par... | keyword[def] identifier[get_requirements_file_from_url] ( identifier[url] ):
literal[string]
identifier[response] = identifier[requests] . identifier[get] ( identifier[url] )
keyword[if] identifier[response] . identifier[status_code] == literal[int] :
keyword[return] identifier[StringIO] (... | def get_requirements_file_from_url(url):
"""fetches the requiremets from the url"""
response = requests.get(url)
if response.status_code == 200:
return StringIO(response.text) # depends on [control=['if'], data=[]]
else:
return StringIO('') |
def analyze(self, scratch, **kwargs):
"""Run and return the results of the VariableInitialization plugin."""
variables = dict((x, self.variable_state(x.scripts, x.variables))
for x in scratch.sprites)
variables['global'] = self.variable_state(self.iter_scripts(scratch),
... | def function[analyze, parameter[self, scratch]]:
constant[Run and return the results of the VariableInitialization plugin.]
variable[variables] assign[=] call[name[dict], parameter[<ast.GeneratorExp object at 0x7da18f723b20>]]
call[name[variables]][constant[global]] assign[=] call[name[self].var... | keyword[def] identifier[analyze] ( identifier[self] , identifier[scratch] ,** identifier[kwargs] ):
literal[string]
identifier[variables] = identifier[dict] (( identifier[x] , identifier[self] . identifier[variable_state] ( identifier[x] . identifier[scripts] , identifier[x] . identifier[variables]... | def analyze(self, scratch, **kwargs):
"""Run and return the results of the VariableInitialization plugin."""
variables = dict(((x, self.variable_state(x.scripts, x.variables)) for x in scratch.sprites))
variables['global'] = self.variable_state(self.iter_scripts(scratch), scratch.stage.variables)
# Outp... |
def is_writable(path):
"""Check if path has write access"""
try:
testfile = tempfile.TemporaryFile(dir=path)
testfile.close()
except OSError as e:
if e.errno == errno.EACCES: # 13
return False
return True | def function[is_writable, parameter[path]]:
constant[Check if path has write access]
<ast.Try object at 0x7da1b2043d90>
return[constant[True]] | keyword[def] identifier[is_writable] ( identifier[path] ):
literal[string]
keyword[try] :
identifier[testfile] = identifier[tempfile] . identifier[TemporaryFile] ( identifier[dir] = identifier[path] )
identifier[testfile] . identifier[close] ()
keyword[except] identifier[OSErro... | def is_writable(path):
"""Check if path has write access"""
try:
testfile = tempfile.TemporaryFile(dir=path)
testfile.close() # depends on [control=['try'], data=[]]
except OSError as e:
if e.errno == errno.EACCES: # 13
return False # depends on [control=['if'], data=[... |
def _initialize_data(self):
"""
This method is called once on construction. After that, it may be
manually called again to reset the device to its default state.
After the first call during construction, the class is frozen.
This means that attempting to define a new member var... | def function[_initialize_data, parameter[self]]:
constant[
This method is called once on construction. After that, it may be
manually called again to reset the device to its default state.
After the first call during construction, the class is frozen.
This means that attempting... | keyword[def] identifier[_initialize_data] ( identifier[self] ):
literal[string]
identifier[self] . identifier[serial_command_mode] = keyword[False]
identifier[self] . identifier[pump_overspeed] = keyword[False]
identifier[self] . identifier[start_commanded] = keyword[False]
... | def _initialize_data(self):
"""
This method is called once on construction. After that, it may be
manually called again to reset the device to its default state.
After the first call during construction, the class is frozen.
This means that attempting to define a new member variabl... |
def up(job, input_file_id_1, input_file_id_2):
"""Merges the two files and places them in the output.
"""
with job.fileStore.writeGlobalFileStream() as (fileHandle, output_id):
with job.fileStore.readGlobalFileStream(input_file_id_1) as inputFileHandle1:
with job.fileStore.readGlobalFile... | def function[up, parameter[job, input_file_id_1, input_file_id_2]]:
constant[Merges the two files and places them in the output.
]
with call[name[job].fileStore.writeGlobalFileStream, parameter[]] begin[:]
with call[name[job].fileStore.readGlobalFileStream, parameter[name[input_file_... | keyword[def] identifier[up] ( identifier[job] , identifier[input_file_id_1] , identifier[input_file_id_2] ):
literal[string]
keyword[with] identifier[job] . identifier[fileStore] . identifier[writeGlobalFileStream] () keyword[as] ( identifier[fileHandle] , identifier[output_id] ):
keyword[with] ... | def up(job, input_file_id_1, input_file_id_2):
"""Merges the two files and places them in the output.
"""
with job.fileStore.writeGlobalFileStream() as (fileHandle, output_id):
with job.fileStore.readGlobalFileStream(input_file_id_1) as inputFileHandle1:
with job.fileStore.readGlobalFile... |
def get_stats_monthly(start=None, end=None, **kwargs):
"""
MOVED to iexfinance.iexdata.get_stats_summary
"""
import warnings
warnings.warn(WNG_MSG % ("get_stats_monthly", "iexdata.get_stats_summary"))
return MonthlySummaryReader(start=start, end=end, **kwargs).fetch() | def function[get_stats_monthly, parameter[start, end]]:
constant[
MOVED to iexfinance.iexdata.get_stats_summary
]
import module[warnings]
call[name[warnings].warn, parameter[binary_operation[name[WNG_MSG] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Constant object at 0x7da1b1d8c070>, <ast... | keyword[def] identifier[get_stats_monthly] ( identifier[start] = keyword[None] , identifier[end] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[import] identifier[warnings]
identifier[warnings] . identifier[warn] ( identifier[WNG_MSG] %( literal[string] , literal[string] ))
... | def get_stats_monthly(start=None, end=None, **kwargs):
"""
MOVED to iexfinance.iexdata.get_stats_summary
"""
import warnings
warnings.warn(WNG_MSG % ('get_stats_monthly', 'iexdata.get_stats_summary'))
return MonthlySummaryReader(start=start, end=end, **kwargs).fetch() |
def LE16(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False):
'''16-bit field, Little endian encoded'''
return UInt16(value, min_value=min_value, max_value=max_value, encoder=ENC_INT_LE, fuzzable=fuzzable, name=name, full_range=full_range) | def function[LE16, parameter[value, min_value, max_value, fuzzable, name, full_range]]:
constant[16-bit field, Little endian encoded]
return[call[name[UInt16], parameter[name[value]]]] | keyword[def] identifier[LE16] ( identifier[value] , identifier[min_value] = keyword[None] , identifier[max_value] = keyword[None] , identifier[fuzzable] = keyword[True] , identifier[name] = keyword[None] , identifier[full_range] = keyword[False] ):
literal[string]
keyword[return] identifier[UInt16] ( iden... | def LE16(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False):
"""16-bit field, Little endian encoded"""
return UInt16(value, min_value=min_value, max_value=max_value, encoder=ENC_INT_LE, fuzzable=fuzzable, name=name, full_range=full_range) |
def id(self):
""" Bug ID number that caused this error """
m = re.match(r'Bug #(\d+) does not exist', self.message)
return m.group(1) | def function[id, parameter[self]]:
constant[ Bug ID number that caused this error ]
variable[m] assign[=] call[name[re].match, parameter[constant[Bug #(\d+) does not exist], name[self].message]]
return[call[name[m].group, parameter[constant[1]]]] | keyword[def] identifier[id] ( identifier[self] ):
literal[string]
identifier[m] = identifier[re] . identifier[match] ( literal[string] , identifier[self] . identifier[message] )
keyword[return] identifier[m] . identifier[group] ( literal[int] ) | def id(self):
""" Bug ID number that caused this error """
m = re.match('Bug #(\\d+) does not exist', self.message)
return m.group(1) |
def save_module(self, obj):
"""
Save a module as an import
"""
mod_name = obj.__name__
# If module is successfully found then it is not a dynamically created module
if hasattr(obj, '__file__'):
is_dynamic = False
else:
try:
... | def function[save_module, parameter[self, obj]]:
constant[
Save a module as an import
]
variable[mod_name] assign[=] name[obj].__name__
if call[name[hasattr], parameter[name[obj], constant[__file__]]] begin[:]
variable[is_dynamic] assign[=] constant[False]
... | keyword[def] identifier[save_module] ( identifier[self] , identifier[obj] ):
literal[string]
identifier[mod_name] = identifier[obj] . identifier[__name__]
keyword[if] identifier[hasattr] ( identifier[obj] , literal[string] ):
identifier[is_dynamic] = keyword[False] ... | def save_module(self, obj):
"""
Save a module as an import
"""
mod_name = obj.__name__
# If module is successfully found then it is not a dynamically created module
if hasattr(obj, '__file__'):
is_dynamic = False # depends on [control=['if'], data=[]]
else:
try:
... |
def log_env_gte(desired):
"""
Boolean check if the current environment LOGLEVEL is
at least as verbose as a desired LOGLEVEL
:param desired: <str> one of 9 keys in <brain.environment.stage>
:return: <bool>
"""
return LOGLEVELS.get(check_log_env()) >= LOGLEVELS.get(desired, LOGLEVELS[TEST]) | def function[log_env_gte, parameter[desired]]:
constant[
Boolean check if the current environment LOGLEVEL is
at least as verbose as a desired LOGLEVEL
:param desired: <str> one of 9 keys in <brain.environment.stage>
:return: <bool>
]
return[compare[call[name[LOGLEVELS].get, parameter[c... | keyword[def] identifier[log_env_gte] ( identifier[desired] ):
literal[string]
keyword[return] identifier[LOGLEVELS] . identifier[get] ( identifier[check_log_env] ())>= identifier[LOGLEVELS] . identifier[get] ( identifier[desired] , identifier[LOGLEVELS] [ identifier[TEST] ]) | def log_env_gte(desired):
"""
Boolean check if the current environment LOGLEVEL is
at least as verbose as a desired LOGLEVEL
:param desired: <str> one of 9 keys in <brain.environment.stage>
:return: <bool>
"""
return LOGLEVELS.get(check_log_env()) >= LOGLEVELS.get(desired, LOGLEVELS[TEST]) |
def collectintargz(target, source, env):
""" Puts all source files into a tar.gz file. """
# the rpm tool depends on a source package, until this is changed
# this hack needs to be here that tries to pack all sources in.
sources = env.FindSourceFiles()
# filter out the target we are building the so... | def function[collectintargz, parameter[target, source, env]]:
constant[ Puts all source files into a tar.gz file. ]
variable[sources] assign[=] call[name[env].FindSourceFiles, parameter[]]
variable[sources] assign[=] <ast.ListComp object at 0x7da20e954f10>
call[name[sources].extend, para... | keyword[def] identifier[collectintargz] ( identifier[target] , identifier[source] , identifier[env] ):
literal[string]
identifier[sources] = identifier[env] . identifier[FindSourceFiles] ()
identifier[sources] =[ identifier[s] keyword[for] identifier[s] keyword[in] identifier[sourc... | def collectintargz(target, source, env):
""" Puts all source files into a tar.gz file. """
# the rpm tool depends on a source package, until this is changed
# this hack needs to be here that tries to pack all sources in.
sources = env.FindSourceFiles()
# filter out the target we are building the sou... |
def _get_and_set_reconnection_handler(self, new_handler):
"""
Called by the _ControlReconnectionHandler when a new connection
is successfully created. Clears out the _reconnection_handler on
this ControlConnection.
"""
with self._reconnection_lock:
old = self... | def function[_get_and_set_reconnection_handler, parameter[self, new_handler]]:
constant[
Called by the _ControlReconnectionHandler when a new connection
is successfully created. Clears out the _reconnection_handler on
this ControlConnection.
]
with name[self]._reconnecti... | keyword[def] identifier[_get_and_set_reconnection_handler] ( identifier[self] , identifier[new_handler] ):
literal[string]
keyword[with] identifier[self] . identifier[_reconnection_lock] :
identifier[old] = identifier[self] . identifier[_reconnection_handler]
identifier[... | def _get_and_set_reconnection_handler(self, new_handler):
"""
Called by the _ControlReconnectionHandler when a new connection
is successfully created. Clears out the _reconnection_handler on
this ControlConnection.
"""
with self._reconnection_lock:
old = self._reconnecti... |
def add_permission(self, role, name):
""" authorize a group for something """
if self.has_permission(role, name):
return True
targetGroup = AuthGroup.objects(role=role, creator=self.client).first()
if not targetGroup:
return False
# Create or update
... | def function[add_permission, parameter[self, role, name]]:
constant[ authorize a group for something ]
if call[name[self].has_permission, parameter[name[role], name[name]]] begin[:]
return[constant[True]]
variable[targetGroup] assign[=] call[call[name[AuthGroup].objects, parameter[]].fir... | keyword[def] identifier[add_permission] ( identifier[self] , identifier[role] , identifier[name] ):
literal[string]
keyword[if] identifier[self] . identifier[has_permission] ( identifier[role] , identifier[name] ):
keyword[return] keyword[True]
identifier[targetGroup] = ide... | def add_permission(self, role, name):
""" authorize a group for something """
if self.has_permission(role, name):
return True # depends on [control=['if'], data=[]]
targetGroup = AuthGroup.objects(role=role, creator=self.client).first()
if not targetGroup:
return False # depends on [co... |
def to_netcdf(data, filename, *, group="posterior", coords=None, dims=None):
"""Save dataset as a netcdf file.
WARNING: Only idempotent in case `data` is InferenceData
Parameters
----------
data : InferenceData, or any object accepted by `convert_to_inference_data`
Object to be saved
f... | def function[to_netcdf, parameter[data, filename]]:
constant[Save dataset as a netcdf file.
WARNING: Only idempotent in case `data` is InferenceData
Parameters
----------
data : InferenceData, or any object accepted by `convert_to_inference_data`
Object to be saved
filename : str
... | keyword[def] identifier[to_netcdf] ( identifier[data] , identifier[filename] ,*, identifier[group] = literal[string] , identifier[coords] = keyword[None] , identifier[dims] = keyword[None] ):
literal[string]
identifier[inference_data] = identifier[convert_to_inference_data] ( identifier[data] , identifier[... | def to_netcdf(data, filename, *, group='posterior', coords=None, dims=None):
"""Save dataset as a netcdf file.
WARNING: Only idempotent in case `data` is InferenceData
Parameters
----------
data : InferenceData, or any object accepted by `convert_to_inference_data`
Object to be saved
f... |
def find_deck_spawns(provider: Provider, prod: bool=True) -> Iterable[str]:
'''find deck spawn transactions via Provider,
it requires that Deck spawn P2TH were imported in local node or
that remote API knows about P2TH address.'''
pa_params = param_query(provider.network)
if isinstance(provider, R... | def function[find_deck_spawns, parameter[provider, prod]]:
constant[find deck spawn transactions via Provider,
it requires that Deck spawn P2TH were imported in local node or
that remote API knows about P2TH address.]
variable[pa_params] assign[=] call[name[param_query], parameter[name[provider]... | keyword[def] identifier[find_deck_spawns] ( identifier[provider] : identifier[Provider] , identifier[prod] : identifier[bool] = keyword[True] )-> identifier[Iterable] [ identifier[str] ]:
literal[string]
identifier[pa_params] = identifier[param_query] ( identifier[provider] . identifier[network] )
k... | def find_deck_spawns(provider: Provider, prod: bool=True) -> Iterable[str]:
"""find deck spawn transactions via Provider,
it requires that Deck spawn P2TH were imported in local node or
that remote API knows about P2TH address."""
pa_params = param_query(provider.network)
if isinstance(provider, Rpc... |
def new(self, time_flags):
# type: (int) -> None
'''
Create a new Rock Ridge Time Stamp record.
Parameters:
time_flags - The flags to use for this time stamp record.
Returns:
Nothing.
'''
if self._initialized:
raise pycdlibexception.... | def function[new, parameter[self, time_flags]]:
constant[
Create a new Rock Ridge Time Stamp record.
Parameters:
time_flags - The flags to use for this time stamp record.
Returns:
Nothing.
]
if name[self]._initialized begin[:]
<ast.Raise object ... | keyword[def] identifier[new] ( identifier[self] , identifier[time_flags] ):
literal[string]
keyword[if] identifier[self] . identifier[_initialized] :
keyword[raise] identifier[pycdlibexception] . identifier[PyCdlibInternalError] ( literal[string] )
identifier[self] . ident... | def new(self, time_flags):
# type: (int) -> None
'\n Create a new Rock Ridge Time Stamp record.\n\n Parameters:\n time_flags - The flags to use for this time stamp record.\n Returns:\n Nothing.\n '
if self._initialized:
raise pycdlibexception.PyCdlibIntern... |
def append(self, item, name=None):
"""
Adds the given item to the end of the pipeline.
"""
with self.condition:
self.queue.append(item)
uuid = self._register_item(name, item)
self.condition.notify_all()
return uuid | def function[append, parameter[self, item, name]]:
constant[
Adds the given item to the end of the pipeline.
]
with name[self].condition begin[:]
call[name[self].queue.append, parameter[name[item]]]
variable[uuid] assign[=] call[name[self]._register_item, ... | keyword[def] identifier[append] ( identifier[self] , identifier[item] , identifier[name] = keyword[None] ):
literal[string]
keyword[with] identifier[self] . identifier[condition] :
identifier[self] . identifier[queue] . identifier[append] ( identifier[item] )
identifier[u... | def append(self, item, name=None):
"""
Adds the given item to the end of the pipeline.
"""
with self.condition:
self.queue.append(item)
uuid = self._register_item(name, item)
self.condition.notify_all()
return uuid # depends on [control=['with'], data=[]] |
def export(self):
""" Exports as dictionary """
data = {}
for key, value in self.items():
data[key] = value
return data | def function[export, parameter[self]]:
constant[ Exports as dictionary ]
variable[data] assign[=] dictionary[[], []]
for taget[tuple[[<ast.Name object at 0x7da1b2649270>, <ast.Name object at 0x7da1b2649a50>]]] in starred[call[name[self].items, parameter[]]] begin[:]
call[name[dat... | keyword[def] identifier[export] ( identifier[self] ):
literal[string]
identifier[data] ={}
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[self] . identifier[items] ():
identifier[data] [ identifier[key] ]= identifier[value]
keyword[return... | def export(self):
""" Exports as dictionary """
data = {}
for (key, value) in self.items():
data[key] = value # depends on [control=['for'], data=[]]
return data |
def render_mako_template_to(
template, outpath, subsd, only_update=False, cwd=None,
prev_subsd=None, create_dest_dirs=False, logger=None,
pass_warn_string=True, **kwargs):
"""
template: either string of path or file like obj.
Beware of the only_update option, it pays no attention to... | def function[render_mako_template_to, parameter[template, outpath, subsd, only_update, cwd, prev_subsd, create_dest_dirs, logger, pass_warn_string]]:
constant[
template: either string of path or file like obj.
Beware of the only_update option, it pays no attention to
an updated subsd.
pass_war... | keyword[def] identifier[render_mako_template_to] (
identifier[template] , identifier[outpath] , identifier[subsd] , identifier[only_update] = keyword[False] , identifier[cwd] = keyword[None] ,
identifier[prev_subsd] = keyword[None] , identifier[create_dest_dirs] = keyword[False] , identifier[logger] = keyword[None]... | def render_mako_template_to(template, outpath, subsd, only_update=False, cwd=None, prev_subsd=None, create_dest_dirs=False, logger=None, pass_warn_string=True, **kwargs):
"""
template: either string of path or file like obj.
Beware of the only_update option, it pays no attention to
an updated subsd.
... |
def get_empty_ids(self):
"""
Get documents id with missing targeted field
"""
cursor = self.get_collection().find(
{
'_id': {'$in': self._document_ids},
self._field: {'$exists': True}
},
{'_id': True}
)
... | def function[get_empty_ids, parameter[self]]:
constant[
Get documents id with missing targeted field
]
variable[cursor] assign[=] call[call[name[self].get_collection, parameter[]].find, parameter[dictionary[[<ast.Constant object at 0x7da1b1fa12a0>, <ast.Attribute object at 0x7da18c4cd450... | keyword[def] identifier[get_empty_ids] ( identifier[self] ):
literal[string]
identifier[cursor] = identifier[self] . identifier[get_collection] (). identifier[find] (
{
literal[string] :{ literal[string] : identifier[self] . identifier[_document_ids] },
identifier[self] . ... | def get_empty_ids(self):
"""
Get documents id with missing targeted field
"""
cursor = self.get_collection().find({'_id': {'$in': self._document_ids}, self._field: {'$exists': True}}, {'_id': True})
return set(self._document_ids) - {doc['_id'] for doc in cursor} |
def transform(self, X):
"""
Args:
X: DataFrame with NaN's
Returns:
Dictionary with one key - 'X' corresponding to given DataFrame but without nan's
"""
if self.fill_missing:
X = self.filler.complete(X)
return {'X': X} | def function[transform, parameter[self, X]]:
constant[
Args:
X: DataFrame with NaN's
Returns:
Dictionary with one key - 'X' corresponding to given DataFrame but without nan's
]
if name[self].fill_missing begin[:]
variable[X] assign[=] call... | keyword[def] identifier[transform] ( identifier[self] , identifier[X] ):
literal[string]
keyword[if] identifier[self] . identifier[fill_missing] :
identifier[X] = identifier[self] . identifier[filler] . identifier[complete] ( identifier[X] )
keyword[return] { literal[string] ... | def transform(self, X):
"""
Args:
X: DataFrame with NaN's
Returns:
Dictionary with one key - 'X' corresponding to given DataFrame but without nan's
"""
if self.fill_missing:
X = self.filler.complete(X) # depends on [control=['if'], data=[]]
return {'... |
def service_changed(self, event):
"""
Called by the framework when a service event occurs
"""
if (
self._ipopo_instance is None
or not self._ipopo_instance.check_event(event)
):
# stop() and clean() may have been called after we have been put
... | def function[service_changed, parameter[self, event]]:
constant[
Called by the framework when a service event occurs
]
if <ast.BoolOp object at 0x7da1b0390f40> begin[:]
return[None]
variable[kind] assign[=] call[name[event].get_kind, parameter[]]
variable[svc_ref]... | keyword[def] identifier[service_changed] ( identifier[self] , identifier[event] ):
literal[string]
keyword[if] (
identifier[self] . identifier[_ipopo_instance] keyword[is] keyword[None]
keyword[or] keyword[not] identifier[self] . identifier[_ipopo_instance] . identifier[check... | def service_changed(self, event):
"""
Called by the framework when a service event occurs
"""
if self._ipopo_instance is None or not self._ipopo_instance.check_event(event):
# stop() and clean() may have been called after we have been put
# inside a listener list copy...
... |
def get_managed_configurations(self):
"""Get the configurations managed by this scheduler
The configuration managed by a scheduler is the self configuration got
by the scheduler during the dispatching.
:return: a dict of scheduler links with instance_id as key and
hash, push_fl... | def function[get_managed_configurations, parameter[self]]:
constant[Get the configurations managed by this scheduler
The configuration managed by a scheduler is the self configuration got
by the scheduler during the dispatching.
:return: a dict of scheduler links with instance_id as ke... | keyword[def] identifier[get_managed_configurations] ( identifier[self] ):
literal[string]
identifier[res] ={}
keyword[if] identifier[self] . identifier[sched] . identifier[pushed_conf] keyword[and] identifier[self] . identifier[cur_... | def get_managed_configurations(self):
"""Get the configurations managed by this scheduler
The configuration managed by a scheduler is the self configuration got
by the scheduler during the dispatching.
:return: a dict of scheduler links with instance_id as key and
hash, push_flavor... |
def LMLgrad(self,params=None):
"""
evaluates the gradient of the log marginal likelihood for the given hyperparameters
"""
if params is not None:
self.setParams(params)
KV = self._update_cache()
W = KV['W']
LMLgrad = SP.zeros(self.covar.n_params)
... | def function[LMLgrad, parameter[self, params]]:
constant[
evaluates the gradient of the log marginal likelihood for the given hyperparameters
]
if compare[name[params] is_not constant[None]] begin[:]
call[name[self].setParams, parameter[name[params]]]
variable[KV]... | keyword[def] identifier[LMLgrad] ( identifier[self] , identifier[params] = keyword[None] ):
literal[string]
keyword[if] identifier[params] keyword[is] keyword[not] keyword[None] :
identifier[self] . identifier[setParams] ( identifier[params] )
identifier[KV] = identifier[s... | def LMLgrad(self, params=None):
"""
evaluates the gradient of the log marginal likelihood for the given hyperparameters
"""
if params is not None:
self.setParams(params) # depends on [control=['if'], data=['params']]
KV = self._update_cache()
W = KV['W']
LMLgrad = SP.zeros(s... |
def error(name=None, message=''):
'''
If name is None Then return empty dict
Otherwise raise an exception with __name__ from name, message from message
CLI Example:
.. code-block:: bash
salt-wheel error
salt-wheel error.error name="Exception" message="This is an error."
'''
... | def function[error, parameter[name, message]]:
constant[
If name is None Then return empty dict
Otherwise raise an exception with __name__ from name, message from message
CLI Example:
.. code-block:: bash
salt-wheel error
salt-wheel error.error name="Exception" message="This ... | keyword[def] identifier[error] ( identifier[name] = keyword[None] , identifier[message] = literal[string] ):
literal[string]
identifier[ret] ={}
keyword[if] identifier[name] keyword[is] keyword[not] keyword[None] :
identifier[salt] . identifier[utils] . identifier[error] . identifier[rais... | def error(name=None, message=''):
"""
If name is None Then return empty dict
Otherwise raise an exception with __name__ from name, message from message
CLI Example:
.. code-block:: bash
salt-wheel error
salt-wheel error.error name="Exception" message="This is an error."
"""
... |
def get_connected_components_as_subgraphs(graph):
"""Finds all connected components of the graph.
Returns a list of graph objects, each representing a connected component.
Returns an empty list for an empty graph.
"""
components = get_connected_components(graph)
list_of_graphs = []
for c i... | def function[get_connected_components_as_subgraphs, parameter[graph]]:
constant[Finds all connected components of the graph.
Returns a list of graph objects, each representing a connected component.
Returns an empty list for an empty graph.
]
variable[components] assign[=] call[name[get_conn... | keyword[def] identifier[get_connected_components_as_subgraphs] ( identifier[graph] ):
literal[string]
identifier[components] = identifier[get_connected_components] ( identifier[graph] )
identifier[list_of_graphs] =[]
keyword[for] identifier[c] keyword[in] identifier[components] :
id... | def get_connected_components_as_subgraphs(graph):
"""Finds all connected components of the graph.
Returns a list of graph objects, each representing a connected component.
Returns an empty list for an empty graph.
"""
components = get_connected_components(graph)
list_of_graphs = []
for c in ... |
def attrs(self, attribute_name):
"""
Retrieve HTML attribute values from the elements matched by the query.
Example usage:
.. code:: python
# Assume that the query matches html elements:
# <div class="foo"> and <div class="bar">
>> q.attrs('class')
... | def function[attrs, parameter[self, attribute_name]]:
constant[
Retrieve HTML attribute values from the elements matched by the query.
Example usage:
.. code:: python
# Assume that the query matches html elements:
# <div class="foo"> and <div class="bar">
... | keyword[def] identifier[attrs] ( identifier[self] , identifier[attribute_name] ):
literal[string]
identifier[desc] = literal[string] . identifier[format] ( identifier[attribute_name] )
keyword[return] identifier[self] . identifier[map] ( keyword[lambda] identifier[el] : identifier[el] . ... | def attrs(self, attribute_name):
"""
Retrieve HTML attribute values from the elements matched by the query.
Example usage:
.. code:: python
# Assume that the query matches html elements:
# <div class="foo"> and <div class="bar">
>> q.attrs('class')
... |
def translate(translationAmt):
"""Create a translation matrix."""
if not isinstance(translationAmt, Vector3):
raise ValueError("translationAmt must be a Vector3")
ma4 = Matrix4((1, 0, 0, translationAmt.x),
(0, 1, 0, translationAmt.y),
(0, ... | def function[translate, parameter[translationAmt]]:
constant[Create a translation matrix.]
if <ast.UnaryOp object at 0x7da20c6e4d30> begin[:]
<ast.Raise object at 0x7da20c6e4430>
variable[ma4] assign[=] call[name[Matrix4], parameter[tuple[[<ast.Constant object at 0x7da20c6e4a00>, <ast.Co... | keyword[def] identifier[translate] ( identifier[translationAmt] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[translationAmt] , identifier[Vector3] ):
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[ma4] = identifier[M... | def translate(translationAmt):
"""Create a translation matrix."""
if not isinstance(translationAmt, Vector3):
raise ValueError('translationAmt must be a Vector3') # depends on [control=['if'], data=[]]
ma4 = Matrix4((1, 0, 0, translationAmt.x), (0, 1, 0, translationAmt.y), (0, 0, 1, translationAmt.... |
def unaccentuate(s):
""" Replace accentuated chars in string by their non accentuated equivalent. """
return "".join(c for c in unicodedata.normalize("NFKD", s) if not unicodedata.combining(c)) | def function[unaccentuate, parameter[s]]:
constant[ Replace accentuated chars in string by their non accentuated equivalent. ]
return[call[constant[].join, parameter[<ast.GeneratorExp object at 0x7da18eb57430>]]] | keyword[def] identifier[unaccentuate] ( identifier[s] ):
literal[string]
keyword[return] literal[string] . identifier[join] ( identifier[c] keyword[for] identifier[c] keyword[in] identifier[unicodedata] . identifier[normalize] ( literal[string] , identifier[s] ) keyword[if] keyword[not] identifier[u... | def unaccentuate(s):
""" Replace accentuated chars in string by their non accentuated equivalent. """
return ''.join((c for c in unicodedata.normalize('NFKD', s) if not unicodedata.combining(c))) |
def parse_args(args=None):
"""
Handles the parsing of options for LIVVkit's command line interface
Args:
args: The list of arguments, typically sys.argv[1:]
"""
parser = argparse.ArgumentParser(description="Main script to run LIVVkit.",
formatter_class=a... | def function[parse_args, parameter[args]]:
constant[
Handles the parsing of options for LIVVkit's command line interface
Args:
args: The list of arguments, typically sys.argv[1:]
]
variable[parser] assign[=] call[name[argparse].ArgumentParser, parameter[]]
call[name[parser].... | keyword[def] identifier[parse_args] ( identifier[args] = keyword[None] ):
literal[string]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] ( identifier[description] = literal[string] ,
identifier[formatter_class] = identifier[argparse] . identifier[ArgumentDefaultsHelpFormatter] ... | def parse_args(args=None):
"""
Handles the parsing of options for LIVVkit's command line interface
Args:
args: The list of arguments, typically sys.argv[1:]
"""
parser = argparse.ArgumentParser(description='Main script to run LIVVkit.', formatter_class=argparse.ArgumentDefaultsHelpFormatter... |
def get_world_bbox(self):
"""Creates a bounding box of the entire world in EPSG: 3857
:return: Bounding box of entire world
:rtype: BBox
"""
return BBox((-self.POP_WEB_MAX, -self.POP_WEB_MAX, self.POP_WEB_MAX, self.POP_WEB_MAX), crs=CRS.POP_WEB) | def function[get_world_bbox, parameter[self]]:
constant[Creates a bounding box of the entire world in EPSG: 3857
:return: Bounding box of entire world
:rtype: BBox
]
return[call[name[BBox], parameter[tuple[[<ast.UnaryOp object at 0x7da18f00e830>, <ast.UnaryOp object at 0x7da18f00d75... | keyword[def] identifier[get_world_bbox] ( identifier[self] ):
literal[string]
keyword[return] identifier[BBox] ((- identifier[self] . identifier[POP_WEB_MAX] ,- identifier[self] . identifier[POP_WEB_MAX] , identifier[self] . identifier[POP_WEB_MAX] , identifier[self] . identifier[POP_WEB_MAX] ), i... | def get_world_bbox(self):
"""Creates a bounding box of the entire world in EPSG: 3857
:return: Bounding box of entire world
:rtype: BBox
"""
return BBox((-self.POP_WEB_MAX, -self.POP_WEB_MAX, self.POP_WEB_MAX, self.POP_WEB_MAX), crs=CRS.POP_WEB) |
def ml(line, cell=None):
"""Implements the datalab cell magic for MLWorkbench operations.
Args:
line: the contents of the ml command line.
Returns:
The results of executing the cell.
"""
parser = google.datalab.utils.commands.CommandParser(
prog='%ml',
description=textwrap.dedent("""\
... | def function[ml, parameter[line, cell]]:
constant[Implements the datalab cell magic for MLWorkbench operations.
Args:
line: the contents of the ml command line.
Returns:
The results of executing the cell.
]
variable[parser] assign[=] call[name[google].datalab.utils.commands.CommandParser,... | keyword[def] identifier[ml] ( identifier[line] , identifier[cell] = keyword[None] ):
literal[string]
identifier[parser] = identifier[google] . identifier[datalab] . identifier[utils] . identifier[commands] . identifier[CommandParser] (
identifier[prog] = literal[string] ,
identifier[description] = identi... | def ml(line, cell=None):
"""Implements the datalab cell magic for MLWorkbench operations.
Args:
line: the contents of the ml command line.
Returns:
The results of executing the cell.
"""
parser = google.datalab.utils.commands.CommandParser(prog='%ml', description=textwrap.dedent(' Execut... |
def invalid_type_error(method_name, arg_name, got_value, expected_type,
version='0.13.0'):
"""Raise a CompilationException when an adapter method available to macros
has changed.
"""
got_type = type(got_value)
msg = ("As of {version}, 'adapter.{method_name}' expects argument "... | def function[invalid_type_error, parameter[method_name, arg_name, got_value, expected_type, version]]:
constant[Raise a CompilationException when an adapter method available to macros
has changed.
]
variable[got_type] assign[=] call[name[type], parameter[name[got_value]]]
variable[msg] a... | keyword[def] identifier[invalid_type_error] ( identifier[method_name] , identifier[arg_name] , identifier[got_value] , identifier[expected_type] ,
identifier[version] = literal[string] ):
literal[string]
identifier[got_type] = identifier[type] ( identifier[got_value] )
identifier[msg] =( literal[stri... | def invalid_type_error(method_name, arg_name, got_value, expected_type, version='0.13.0'):
"""Raise a CompilationException when an adapter method available to macros
has changed.
"""
got_type = type(got_value)
msg = "As of {version}, 'adapter.{method_name}' expects argument '{arg_name}' to be of typ... |
def pow(cls, x: 'TensorFluent', y: 'TensorFluent') -> 'TensorFluent':
'''Returns a TensorFluent for the pow function.TensorFluent
Args:
x: The first operand.
y: The second operand.
Returns:
A TensorFluent wrapping the pow function.
'''
return... | def function[pow, parameter[cls, x, y]]:
constant[Returns a TensorFluent for the pow function.TensorFluent
Args:
x: The first operand.
y: The second operand.
Returns:
A TensorFluent wrapping the pow function.
]
return[call[name[cls]._binary_op, p... | keyword[def] identifier[pow] ( identifier[cls] , identifier[x] : literal[string] , identifier[y] : literal[string] )-> literal[string] :
literal[string]
keyword[return] identifier[cls] . identifier[_binary_op] ( identifier[x] , identifier[y] , identifier[tf] . identifier[pow] , identifier[tf] . id... | def pow(cls, x: 'TensorFluent', y: 'TensorFluent') -> 'TensorFluent':
"""Returns a TensorFluent for the pow function.TensorFluent
Args:
x: The first operand.
y: The second operand.
Returns:
A TensorFluent wrapping the pow function.
"""
return cls._bi... |
def get_ntp_peers(self):
"""Return the NTP peers configured on the device."""
ntp_table = junos_views.junos_ntp_peers_config_table(self.device)
ntp_table.get()
ntp_peers = ntp_table.items()
if not ntp_peers:
return {}
return {napalm_base.helpers.ip(peer[0])... | def function[get_ntp_peers, parameter[self]]:
constant[Return the NTP peers configured on the device.]
variable[ntp_table] assign[=] call[name[junos_views].junos_ntp_peers_config_table, parameter[name[self].device]]
call[name[ntp_table].get, parameter[]]
variable[ntp_peers] assign[=] cal... | keyword[def] identifier[get_ntp_peers] ( identifier[self] ):
literal[string]
identifier[ntp_table] = identifier[junos_views] . identifier[junos_ntp_peers_config_table] ( identifier[self] . identifier[device] )
identifier[ntp_table] . identifier[get] ()
identifier[ntp_peers] = ide... | def get_ntp_peers(self):
"""Return the NTP peers configured on the device."""
ntp_table = junos_views.junos_ntp_peers_config_table(self.device)
ntp_table.get()
ntp_peers = ntp_table.items()
if not ntp_peers:
return {} # depends on [control=['if'], data=[]]
return {napalm_base.helpers.ip... |
def get_insert_fields_and_values_from_dict(dictionary, datetime_format='%Y-%m-%d %H:%M:%S', db_escape=True):
"""Formats a dictionary to strings of fields and values for insert statements
@param dictionary: The dictionary whose keys and values are to be inserted
@param db_escape: If true, will d... | def function[get_insert_fields_and_values_from_dict, parameter[dictionary, datetime_format, db_escape]]:
constant[Formats a dictionary to strings of fields and values for insert statements
@param dictionary: The dictionary whose keys and values are to be inserted
@param db_escape: If true, will... | keyword[def] identifier[get_insert_fields_and_values_from_dict] ( identifier[dictionary] , identifier[datetime_format] = literal[string] , identifier[db_escape] = keyword[True] ):
literal[string]
keyword[if] identifier[db_escape] :
identifier[CoyoteDb] . identifier[escape_dictionary] ... | def get_insert_fields_and_values_from_dict(dictionary, datetime_format='%Y-%m-%d %H:%M:%S', db_escape=True):
"""Formats a dictionary to strings of fields and values for insert statements
@param dictionary: The dictionary whose keys and values are to be inserted
@param db_escape: If true, will db es... |
def shake_shake_branch(x, output_filters, stride, rand_forward, rand_backward,
hparams):
"""Building a 2 branching convnet."""
is_training = hparams.mode == tf.estimator.ModeKeys.TRAIN
x = tf.nn.relu(x)
x = tf.layers.conv2d(
x,
output_filters, (3, 3),
strides=(stride, st... | def function[shake_shake_branch, parameter[x, output_filters, stride, rand_forward, rand_backward, hparams]]:
constant[Building a 2 branching convnet.]
variable[is_training] assign[=] compare[name[hparams].mode equal[==] name[tf].estimator.ModeKeys.TRAIN]
variable[x] assign[=] call[name[tf].nn.r... | keyword[def] identifier[shake_shake_branch] ( identifier[x] , identifier[output_filters] , identifier[stride] , identifier[rand_forward] , identifier[rand_backward] ,
identifier[hparams] ):
literal[string]
identifier[is_training] = identifier[hparams] . identifier[mode] == identifier[tf] . identifier[estimato... | def shake_shake_branch(x, output_filters, stride, rand_forward, rand_backward, hparams):
"""Building a 2 branching convnet."""
is_training = hparams.mode == tf.estimator.ModeKeys.TRAIN
x = tf.nn.relu(x)
x = tf.layers.conv2d(x, output_filters, (3, 3), strides=(stride, stride), padding='SAME', name='conv1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.