code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def qasm(self):
"""Return OpenQASM string."""
string_temp = self.header + "\n"
string_temp += self.extension_lib + "\n"
for register in self.qregs:
string_temp += register.qasm() + "\n"
for register in self.cregs:
string_temp += register.qasm() + "\n"
... | def function[qasm, parameter[self]]:
constant[Return OpenQASM string.]
variable[string_temp] assign[=] binary_operation[name[self].header + constant[
]]
<ast.AugAssign object at 0x7da1b0536bf0>
for taget[name[register]] in starred[name[self].qregs] begin[:]
<ast.AugAssign object at 0... | keyword[def] identifier[qasm] ( identifier[self] ):
literal[string]
identifier[string_temp] = identifier[self] . identifier[header] + literal[string]
identifier[string_temp] += identifier[self] . identifier[extension_lib] + literal[string]
keyword[for] identifier[register] key... | def qasm(self):
"""Return OpenQASM string."""
string_temp = self.header + '\n'
string_temp += self.extension_lib + '\n'
for register in self.qregs:
string_temp += register.qasm() + '\n' # depends on [control=['for'], data=['register']]
for register in self.cregs:
string_temp += regi... |
def return_type(rettype):
"""
Decorate a function to automatically convert its return type to a string
using a custom function.
Web-based service functions must return text to the client. Tangelo
contains default logic to convert many kinds of values into string, but this
decorator allows the ... | def function[return_type, parameter[rettype]]:
constant[
Decorate a function to automatically convert its return type to a string
using a custom function.
Web-based service functions must return text to the client. Tangelo
contains default logic to convert many kinds of values into string, but... | keyword[def] identifier[return_type] ( identifier[rettype] ):
literal[string]
keyword[def] identifier[wrap] ( identifier[f] ):
@ identifier[functools] . identifier[wraps] ( identifier[f] )
keyword[def] identifier[converter] (* identifier[pargs] ,** identifier[kwargs] ):
... | def return_type(rettype):
"""
Decorate a function to automatically convert its return type to a string
using a custom function.
Web-based service functions must return text to the client. Tangelo
contains default logic to convert many kinds of values into string, but this
decorator allows the ... |
def frequency(self, data_frame):
"""
This method returns the number of #taps divided by the test duration
:param data_frame: the data frame
:type data_frame: pandas.DataFrame
:return frequency: frequency
:rtype frequency: float
"""
fr... | def function[frequency, parameter[self, data_frame]]:
constant[
This method returns the number of #taps divided by the test duration
:param data_frame: the data frame
:type data_frame: pandas.DataFrame
:return frequency: frequency
:rtype frequency: fl... | keyword[def] identifier[frequency] ( identifier[self] , identifier[data_frame] ):
literal[string]
identifier[freq] = identifier[sum] ( identifier[data_frame] . identifier[action_type] == literal[int] )/ identifier[data_frame] . identifier[td] [- literal[int] ]
identifier[duration] = identi... | def frequency(self, data_frame):
"""
This method returns the number of #taps divided by the test duration
:param data_frame: the data frame
:type data_frame: pandas.DataFrame
:return frequency: frequency
:rtype frequency: float
"""
freq = sum... |
def _parse_alfred_vis(self, data):
"""
Converts a alfred-vis JSON object
to a NetworkX Graph object which is then returned.
Additionally checks for "source_vesion" to determine the batman-adv version.
"""
# initialize graph and list of aggregated nodes
graph = sel... | def function[_parse_alfred_vis, parameter[self, data]]:
constant[
Converts a alfred-vis JSON object
to a NetworkX Graph object which is then returned.
Additionally checks for "source_vesion" to determine the batman-adv version.
]
variable[graph] assign[=] call[name[self].... | keyword[def] identifier[_parse_alfred_vis] ( identifier[self] , identifier[data] ):
literal[string]
identifier[graph] = identifier[self] . identifier[_init_graph] ()
keyword[if] literal[string] keyword[in] identifier[data] :
identifier[self] . identifier[version] =... | def _parse_alfred_vis(self, data):
"""
Converts a alfred-vis JSON object
to a NetworkX Graph object which is then returned.
Additionally checks for "source_vesion" to determine the batman-adv version.
"""
# initialize graph and list of aggregated nodes
graph = self._init_grap... |
def DiffPrimitiveArrays(self, oldObj, newObj):
"""Diff two primitive arrays"""
if len(oldObj) != len(newObj):
__Log__.debug('DiffDoArrays: Array lengths do not match %d != %d'
% (len(oldObj), len(newObj)))
return False
match = True
if self._ignoreArrayOrder:
... | def function[DiffPrimitiveArrays, parameter[self, oldObj, newObj]]:
constant[Diff two primitive arrays]
if compare[call[name[len], parameter[name[oldObj]]] not_equal[!=] call[name[len], parameter[name[newObj]]]] begin[:]
call[name[__Log__].debug, parameter[binary_operation[constant[DiffD... | keyword[def] identifier[DiffPrimitiveArrays] ( identifier[self] , identifier[oldObj] , identifier[newObj] ):
literal[string]
keyword[if] identifier[len] ( identifier[oldObj] )!= identifier[len] ( identifier[newObj] ):
identifier[__Log__] . identifier[debug] ( literal[string]
%( ide... | def DiffPrimitiveArrays(self, oldObj, newObj):
"""Diff two primitive arrays"""
if len(oldObj) != len(newObj):
__Log__.debug('DiffDoArrays: Array lengths do not match %d != %d' % (len(oldObj), len(newObj)))
return False # depends on [control=['if'], data=[]]
match = True
if self._ignoreA... |
def _get_samtools0_path(self):
"""Retrieve PATH to the samtools version specific for eriscript.
"""
samtools_path = os.path.realpath(os.path.join(self._get_ericscript_path(),"..", "..", "bin"))
return samtools_path | def function[_get_samtools0_path, parameter[self]]:
constant[Retrieve PATH to the samtools version specific for eriscript.
]
variable[samtools_path] assign[=] call[name[os].path.realpath, parameter[call[name[os].path.join, parameter[call[name[self]._get_ericscript_path, parameter[]], constant[..... | keyword[def] identifier[_get_samtools0_path] ( identifier[self] ):
literal[string]
identifier[samtools_path] = identifier[os] . identifier[path] . identifier[realpath] ( identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[_get_ericscript_path] (), literal[string] , ... | def _get_samtools0_path(self):
"""Retrieve PATH to the samtools version specific for eriscript.
"""
samtools_path = os.path.realpath(os.path.join(self._get_ericscript_path(), '..', '..', 'bin'))
return samtools_path |
def from_optional_dicts_by_key(cls, ds: Optional[dict],
force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> TOption[TDict[T]]:
"""From dict of dict to optional dict of instance.
:param ds: Dict of dict
:param force_snake_case: Keys are trans... | def function[from_optional_dicts_by_key, parameter[cls, ds, force_snake_case, force_cast, restrict]]:
constant[From dict of dict to optional dict of instance.
:param ds: Dict of dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param fo... | keyword[def] identifier[from_optional_dicts_by_key] ( identifier[cls] , identifier[ds] : identifier[Optional] [ identifier[dict] ],
identifier[force_snake_case] = keyword[True] , identifier[force_cast] : identifier[bool] = keyword[False] , identifier[restrict] : identifier[bool] = keyword[True] )-> identifier[TOptio... | def from_optional_dicts_by_key(cls, ds: Optional[dict], force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> TOption[TDict[T]]:
"""From dict of dict to optional dict of instance.
:param ds: Dict of dict
:param force_snake_case: Keys are transformed to snake case in order to compli... |
def add_view_info(self, view_info: ViewInfo):
'''Adds view information to error message'''
try:
next(info for info in self._view_infos if info.view == view_info.view)
except StopIteration:
indent = len(self._view_infos) * '\t'
self._view_infos.append(view_info... | def function[add_view_info, parameter[self, view_info]]:
constant[Adds view information to error message]
<ast.Try object at 0x7da20e955960> | keyword[def] identifier[add_view_info] ( identifier[self] , identifier[view_info] : identifier[ViewInfo] ):
literal[string]
keyword[try] :
identifier[next] ( identifier[info] keyword[for] identifier[info] keyword[in] identifier[self] . identifier[_view_infos] keyword[if] identifi... | def add_view_info(self, view_info: ViewInfo):
"""Adds view information to error message"""
try:
next((info for info in self._view_infos if info.view == view_info.view)) # depends on [control=['try'], data=[]]
except StopIteration:
indent = len(self._view_infos) * '\t'
self._view_inf... |
def _get_char_pixels(self, s):
"""
Internal. Safeguards the character indexed dictionary for the
show_message function below
"""
if len(s) == 1 and s in self._text_dict.keys():
return list(self._text_dict[s])
else:
return list(self._text_dict['?']... | def function[_get_char_pixels, parameter[self, s]]:
constant[
Internal. Safeguards the character indexed dictionary for the
show_message function below
]
if <ast.BoolOp object at 0x7da1b08a15a0> begin[:]
return[call[name[list], parameter[call[name[self]._text_dict][name[s... | keyword[def] identifier[_get_char_pixels] ( identifier[self] , identifier[s] ):
literal[string]
keyword[if] identifier[len] ( identifier[s] )== literal[int] keyword[and] identifier[s] keyword[in] identifier[self] . identifier[_text_dict] . identifier[keys] ():
keyword[return] id... | def _get_char_pixels(self, s):
"""
Internal. Safeguards the character indexed dictionary for the
show_message function below
"""
if len(s) == 1 and s in self._text_dict.keys():
return list(self._text_dict[s]) # depends on [control=['if'], data=[]]
else:
return list(s... |
def __parse_inchi():
'''Gets and parses file'''
filename = get_file('chebiId_inchi.tsv')
with io.open(filename, 'r', encoding='cp1252') as textfile:
next(textfile)
for line in textfile:
tokens = line.strip().split('\t')
__INCHIS[int(tokens[0])] = tokens[1] | def function[__parse_inchi, parameter[]]:
constant[Gets and parses file]
variable[filename] assign[=] call[name[get_file], parameter[constant[chebiId_inchi.tsv]]]
with call[name[io].open, parameter[name[filename], constant[r]]] begin[:]
call[name[next], parameter[name[textfile]]]... | keyword[def] identifier[__parse_inchi] ():
literal[string]
identifier[filename] = identifier[get_file] ( literal[string] )
keyword[with] identifier[io] . identifier[open] ( identifier[filename] , literal[string] , identifier[encoding] = literal[string] ) keyword[as] identifier[textfile] :
... | def __parse_inchi():
"""Gets and parses file"""
filename = get_file('chebiId_inchi.tsv')
with io.open(filename, 'r', encoding='cp1252') as textfile:
next(textfile)
for line in textfile:
tokens = line.strip().split('\t')
__INCHIS[int(tokens[0])] = tokens[1] # depends ... |
def get_structure_from_prev_run(vasprun, outcar=None, sym_prec=0.1,
international_monoclinic=True):
"""
Process structure from previous run.
Args:
vasprun (Vasprun): Vasprun that contains the final structure
from previous run.
outcar (Outcar): Out... | def function[get_structure_from_prev_run, parameter[vasprun, outcar, sym_prec, international_monoclinic]]:
constant[
Process structure from previous run.
Args:
vasprun (Vasprun): Vasprun that contains the final structure
from previous run.
outcar (Outcar): Outcar that contai... | keyword[def] identifier[get_structure_from_prev_run] ( identifier[vasprun] , identifier[outcar] = keyword[None] , identifier[sym_prec] = literal[int] ,
identifier[international_monoclinic] = keyword[True] ):
literal[string]
identifier[structure] = identifier[vasprun] . identifier[final_structure]
i... | def get_structure_from_prev_run(vasprun, outcar=None, sym_prec=0.1, international_monoclinic=True):
"""
Process structure from previous run.
Args:
vasprun (Vasprun): Vasprun that contains the final structure
from previous run.
outcar (Outcar): Outcar that contains the magnetizat... |
def raise_307(instance, location):
"""Abort the current request with a 307 (Temporary Redirect) response
code. Sets the Location header correctly. If the location does not start
with a slash, the path of the current request is prepended.
:param instance: Resource instance (used to access the response)
... | def function[raise_307, parameter[instance, location]]:
constant[Abort the current request with a 307 (Temporary Redirect) response
code. Sets the Location header correctly. If the location does not start
with a slash, the path of the current request is prepended.
:param instance: Resource instance... | keyword[def] identifier[raise_307] ( identifier[instance] , identifier[location] ):
literal[string]
identifier[_set_location] ( identifier[instance] , identifier[location] )
identifier[instance] . identifier[response] . identifier[status] = literal[int]
keyword[raise] identifier[ResponseExcepti... | def raise_307(instance, location):
"""Abort the current request with a 307 (Temporary Redirect) response
code. Sets the Location header correctly. If the location does not start
with a slash, the path of the current request is prepended.
:param instance: Resource instance (used to access the response)
... |
def _configure_sockets(self, config, with_streamer=False, with_forwarder=False):
"""Configure sockets for HQ
:param dict config: test configuration
:param bool with_streamer: tell if we need to connect to streamer or simply bind
:param bool with_forwarder: tell if we need to connect to ... | def function[_configure_sockets, parameter[self, config, with_streamer, with_forwarder]]:
constant[Configure sockets for HQ
:param dict config: test configuration
:param bool with_streamer: tell if we need to connect to streamer or simply bind
:param bool with_forwarder: tell if we need... | keyword[def] identifier[_configure_sockets] ( identifier[self] , identifier[config] , identifier[with_streamer] = keyword[False] , identifier[with_forwarder] = keyword[False] ):
literal[string]
identifier[rc_port] = identifier[config] . identifier[get] ( literal[string] , literal[int] )
i... | def _configure_sockets(self, config, with_streamer=False, with_forwarder=False):
"""Configure sockets for HQ
:param dict config: test configuration
:param bool with_streamer: tell if we need to connect to streamer or simply bind
:param bool with_forwarder: tell if we need to connect to forw... |
def _sample_template(sample, out_dir):
"""R code to get QC for one sample"""
bam_fn = dd.get_work_bam(sample)
genome = dd.get_genome_build(sample)
if genome in supported:
peaks = sample.get("peaks_files", []).get("main")
if peaks:
r_code = ("library(ChIPQC);\n"
... | def function[_sample_template, parameter[sample, out_dir]]:
constant[R code to get QC for one sample]
variable[bam_fn] assign[=] call[name[dd].get_work_bam, parameter[name[sample]]]
variable[genome] assign[=] call[name[dd].get_genome_build, parameter[name[sample]]]
if compare[name[genome... | keyword[def] identifier[_sample_template] ( identifier[sample] , identifier[out_dir] ):
literal[string]
identifier[bam_fn] = identifier[dd] . identifier[get_work_bam] ( identifier[sample] )
identifier[genome] = identifier[dd] . identifier[get_genome_build] ( identifier[sample] )
keyword[if] iden... | def _sample_template(sample, out_dir):
"""R code to get QC for one sample"""
bam_fn = dd.get_work_bam(sample)
genome = dd.get_genome_build(sample)
if genome in supported:
peaks = sample.get('peaks_files', []).get('main')
if peaks:
r_code = 'library(ChIPQC);\nsample = ChIPQCsa... |
def get_revocation_time(self):
"""Get the revocation time as naive datetime.
Note that this method is only used by cryptography>=2.4.
"""
if self.revoked is False:
return
if timezone.is_aware(self.revoked_date):
# convert datetime object to UTC and make ... | def function[get_revocation_time, parameter[self]]:
constant[Get the revocation time as naive datetime.
Note that this method is only used by cryptography>=2.4.
]
if compare[name[self].revoked is constant[False]] begin[:]
return[None]
if call[name[timezone].is_aware, par... | keyword[def] identifier[get_revocation_time] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[revoked] keyword[is] keyword[False] :
keyword[return]
keyword[if] identifier[timezone] . identifier[is_aware] ( identifier[self] . identifier[revo... | def get_revocation_time(self):
"""Get the revocation time as naive datetime.
Note that this method is only used by cryptography>=2.4.
"""
if self.revoked is False:
return # depends on [control=['if'], data=[]]
if timezone.is_aware(self.revoked_date):
# convert datetime obje... |
def lock(self, key, value, *, flags=None, session):
"""Locks the Key with the given Session
Parameters:
key (str): Key to set
value (Payload): Value to set, It will be encoded by flags
session (ObjectID): Session ID
The Key will only be set if its current mo... | def function[lock, parameter[self, key, value]]:
constant[Locks the Key with the given Session
Parameters:
key (str): Key to set
value (Payload): Value to set, It will be encoded by flags
session (ObjectID): Session ID
The Key will only be set if its current... | keyword[def] identifier[lock] ( identifier[self] , identifier[key] , identifier[value] ,*, identifier[flags] = keyword[None] , identifier[session] ):
literal[string]
identifier[self] . identifier[append] ({
literal[string] : literal[string] ,
literal[string] : identifier[key] ,
... | def lock(self, key, value, *, flags=None, session):
"""Locks the Key with the given Session
Parameters:
key (str): Key to set
value (Payload): Value to set, It will be encoded by flags
session (ObjectID): Session ID
The Key will only be set if its current modify... |
def run(self, ds, skip_checks, *checker_names):
"""
Runs this CheckSuite on the dataset with all the passed Checker instances.
Returns a dictionary mapping checker names to a 2-tuple of their grouped scores and errors/exceptions while running checks.
"""
ret_val = {}
ch... | def function[run, parameter[self, ds, skip_checks]]:
constant[
Runs this CheckSuite on the dataset with all the passed Checker instances.
Returns a dictionary mapping checker names to a 2-tuple of their grouped scores and errors/exceptions while running checks.
]
variable[ret_va... | keyword[def] identifier[run] ( identifier[self] , identifier[ds] , identifier[skip_checks] ,* identifier[checker_names] ):
literal[string]
identifier[ret_val] ={}
identifier[checkers] = identifier[self] . identifier[_get_valid_checkers] ( identifier[ds] , identifier[checker_names] )
... | def run(self, ds, skip_checks, *checker_names):
"""
Runs this CheckSuite on the dataset with all the passed Checker instances.
Returns a dictionary mapping checker names to a 2-tuple of their grouped scores and errors/exceptions while running checks.
"""
ret_val = {}
checkers = self... |
def from_schemafile(cls, schemafile):
"""Create a Flatson instance from a schemafile
"""
with open(schemafile) as f:
return cls(json.load(f)) | def function[from_schemafile, parameter[cls, schemafile]]:
constant[Create a Flatson instance from a schemafile
]
with call[name[open], parameter[name[schemafile]]] begin[:]
return[call[name[cls], parameter[call[name[json].load, parameter[name[f]]]]]] | keyword[def] identifier[from_schemafile] ( identifier[cls] , identifier[schemafile] ):
literal[string]
keyword[with] identifier[open] ( identifier[schemafile] ) keyword[as] identifier[f] :
keyword[return] identifier[cls] ( identifier[json] . identifier[load] ( identifier[f] )) | def from_schemafile(cls, schemafile):
"""Create a Flatson instance from a schemafile
"""
with open(schemafile) as f:
return cls(json.load(f)) # depends on [control=['with'], data=['f']] |
def calculate_size(name, id):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += calculate_size_str(id)
return data_size | def function[calculate_size, parameter[name, id]]:
constant[ Calculates the request payload size]
variable[data_size] assign[=] constant[0]
<ast.AugAssign object at 0x7da1b16a40d0>
<ast.AugAssign object at 0x7da1b16a71c0>
return[name[data_size]] | keyword[def] identifier[calculate_size] ( identifier[name] , identifier[id] ):
literal[string]
identifier[data_size] = literal[int]
identifier[data_size] += identifier[calculate_size_str] ( identifier[name] )
identifier[data_size] += identifier[calculate_size_str] ( identifier[id] )
keyword... | def calculate_size(name, id):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += calculate_size_str(id)
return data_size |
def extractRuntime(runtime_dirs):
"""
Used to find the correct static lib name to pass to gcc
"""
names = [str(item) for name in runtime_dirs for item in os.listdir(name)]
string = '\n'.join(names)
result = extract(RUNTIME_PATTERN, string, condense=True)
return result | def function[extractRuntime, parameter[runtime_dirs]]:
constant[
Used to find the correct static lib name to pass to gcc
]
variable[names] assign[=] <ast.ListComp object at 0x7da1b2373190>
variable[string] assign[=] call[constant[
].join, parameter[name[names]]]
variable[result] ... | keyword[def] identifier[extractRuntime] ( identifier[runtime_dirs] ):
literal[string]
identifier[names] =[ identifier[str] ( identifier[item] ) keyword[for] identifier[name] keyword[in] identifier[runtime_dirs] keyword[for] identifier[item] keyword[in] identifier[os] . identifier[listdir] ( identifi... | def extractRuntime(runtime_dirs):
"""
Used to find the correct static lib name to pass to gcc
"""
names = [str(item) for name in runtime_dirs for item in os.listdir(name)]
string = '\n'.join(names)
result = extract(RUNTIME_PATTERN, string, condense=True)
return result |
def arango_id_to_key(_id):
"""Remove illegal chars from potential arangodb _key (id)
Args:
_id (str): id to be used as arangodb _key
Returns:
(str): _key value with illegal chars removed
"""
key = re.sub(r"[^a-zA-Z0-9\_\-\:\.\@\(\)\+\,\=\;\$\!\*\%]+", r"_", _id)
if len(key) > ... | def function[arango_id_to_key, parameter[_id]]:
constant[Remove illegal chars from potential arangodb _key (id)
Args:
_id (str): id to be used as arangodb _key
Returns:
(str): _key value with illegal chars removed
]
variable[key] assign[=] call[name[re].sub, parameter[const... | keyword[def] identifier[arango_id_to_key] ( identifier[_id] ):
literal[string]
identifier[key] = identifier[re] . identifier[sub] ( literal[string] , literal[string] , identifier[_id] )
keyword[if] identifier[len] ( identifier[key] )> literal[int] :
identifier[log] . identifier[error] (
... | def arango_id_to_key(_id):
"""Remove illegal chars from potential arangodb _key (id)
Args:
_id (str): id to be used as arangodb _key
Returns:
(str): _key value with illegal chars removed
"""
key = re.sub('[^a-zA-Z0-9\\_\\-\\:\\.\\@\\(\\)\\+\\,\\=\\;\\$\\!\\*\\%]+', '_', _id)
if... |
def no_sleep():
"""
Context that prevents the computer from going to sleep.
"""
mode = power.ES.continuous | power.ES.system_required
handle_nonzero_success(power.SetThreadExecutionState(mode))
try:
yield
finally:
handle_nonzero_success(power.SetThreadExecutionState(power.ES.continuous)) | def function[no_sleep, parameter[]]:
constant[
Context that prevents the computer from going to sleep.
]
variable[mode] assign[=] binary_operation[name[power].ES.continuous <ast.BitOr object at 0x7da2590d6aa0> name[power].ES.system_required]
call[name[handle_nonzero_success], parameter[call[na... | keyword[def] identifier[no_sleep] ():
literal[string]
identifier[mode] = identifier[power] . identifier[ES] . identifier[continuous] | identifier[power] . identifier[ES] . identifier[system_required]
identifier[handle_nonzero_success] ( identifier[power] . identifier[SetThreadExecutionState] ( identifier[mode... | def no_sleep():
"""
Context that prevents the computer from going to sleep.
"""
mode = power.ES.continuous | power.ES.system_required
handle_nonzero_success(power.SetThreadExecutionState(mode))
try:
yield # depends on [control=['try'], data=[]]
finally:
handle_nonzero_success(powe... |
def _match_service(self, line_with_color):
"""Return line if line matches this service's name, return None otherwise."""
line = re.compile("(\x1b\[\d+m)+").sub("", line_with_color) # Strip color codes
regexp = re.compile(r"^\[(.*?)\]\s(.*?)$")
if regexp.match(line):
t... | def function[_match_service, parameter[self, line_with_color]]:
constant[Return line if line matches this service's name, return None otherwise.]
variable[line] assign[=] call[call[name[re].compile, parameter[constant[(\[\d+m)+]]].sub, parameter[constant[], name[line_with_color]]]
variable[rege... | keyword[def] identifier[_match_service] ( identifier[self] , identifier[line_with_color] ):
literal[string]
identifier[line] = identifier[re] . identifier[compile] ( literal[string] ). identifier[sub] ( literal[string] , identifier[line_with_color] )
identifier[regexp] = identifier[re] . ... | def _match_service(self, line_with_color):
"""Return line if line matches this service's name, return None otherwise."""
line = re.compile('(\x1b\\[\\d+m)+').sub('', line_with_color) # Strip color codes
regexp = re.compile('^\\[(.*?)\\]\\s(.*?)$')
if regexp.match(line):
title = regexp.match(lin... |
def EventIvorn(ivorn, cite_type):
"""
Used to cite earlier VOEvents.
Use in conjunction with :func:`.add_citations`
Args:
ivorn(str): It is assumed this will be copied verbatim from elsewhere,
and so these should have any prefix (e.g. 'ivo://','http://')
already in plac... | def function[EventIvorn, parameter[ivorn, cite_type]]:
constant[
Used to cite earlier VOEvents.
Use in conjunction with :func:`.add_citations`
Args:
ivorn(str): It is assumed this will be copied verbatim from elsewhere,
and so these should have any prefix (e.g. 'ivo://','http:/... | keyword[def] identifier[EventIvorn] ( identifier[ivorn] , identifier[cite_type] ):
literal[string]
identifier[c] = identifier[objectify] . identifier[StringElement] ( identifier[cite] = identifier[cite_type] )
identifier[c] . identifier[_setText] ( identifier[ivorn] )
identifier[c] . identif... | def EventIvorn(ivorn, cite_type):
"""
Used to cite earlier VOEvents.
Use in conjunction with :func:`.add_citations`
Args:
ivorn(str): It is assumed this will be copied verbatim from elsewhere,
and so these should have any prefix (e.g. 'ivo://','http://')
already in plac... |
def get_polygons(self, by_spec=False, depth=None):
"""
Returns a list of polygons created by this reference.
Parameters
----------
by_spec : bool
If ``True``, the return value is a dictionary with the
polygons of each individual pair (layer, datatype).
... | def function[get_polygons, parameter[self, by_spec, depth]]:
constant[
Returns a list of polygons created by this reference.
Parameters
----------
by_spec : bool
If ``True``, the return value is a dictionary with the
polygons of each individual pair (laye... | keyword[def] identifier[get_polygons] ( identifier[self] , identifier[by_spec] = keyword[False] , identifier[depth] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[self] . identifier[ref_cell] , identifier[Cell] ):
keyword[return] iden... | def get_polygons(self, by_spec=False, depth=None):
"""
Returns a list of polygons created by this reference.
Parameters
----------
by_spec : bool
If ``True``, the return value is a dictionary with the
polygons of each individual pair (layer, datatype).
... |
def folder2db(folder_name, debug, energy_limit, skip_folders,
goto_reaction):
"""Read folder and collect data in local sqlite3 database"""
folder_name = folder_name.rstrip('/')
skip = []
for s in skip_folders.split(', '):
for sk in s.split(','):
skip.append(sk)
pub... | def function[folder2db, parameter[folder_name, debug, energy_limit, skip_folders, goto_reaction]]:
constant[Read folder and collect data in local sqlite3 database]
variable[folder_name] assign[=] call[name[folder_name].rstrip, parameter[constant[/]]]
variable[skip] assign[=] list[[]]
for... | keyword[def] identifier[folder2db] ( identifier[folder_name] , identifier[debug] , identifier[energy_limit] , identifier[skip_folders] ,
identifier[goto_reaction] ):
literal[string]
identifier[folder_name] = identifier[folder_name] . identifier[rstrip] ( literal[string] )
identifier[skip] =[]
k... | def folder2db(folder_name, debug, energy_limit, skip_folders, goto_reaction):
"""Read folder and collect data in local sqlite3 database"""
folder_name = folder_name.rstrip('/')
skip = []
for s in skip_folders.split(', '):
for sk in s.split(','):
skip.append(sk) # depends on [control... |
def make_frog_fresco(text, width, padding=8):
"""\
Formats your lovely text into a speech bubble spouted by this adorable
little frog.
"""
stem = r' /'
frog = r"""
{text}
{stem}
@..@
(----)
( >__< )
^^ ~~ ^^"""
offset = len(stem) - 1
formatted_indent = ' ' * offset
formatt... | def function[make_frog_fresco, parameter[text, width, padding]]:
constant[ Formats your lovely text into a speech bubble spouted by this adorable
little frog.
]
variable[stem] assign[=] constant[ /]
variable[frog] assign[=] constant[
{text}
{stem}
@..@
(----)
( >__< )
^^ ~~ ... | keyword[def] identifier[make_frog_fresco] ( identifier[text] , identifier[width] , identifier[padding] = literal[int] ):
literal[string]
identifier[stem] = literal[string]
identifier[frog] = literal[string]
identifier[offset] = identifier[len] ( identifier[stem] )- literal[int]
identifie... | def make_frog_fresco(text, width, padding=8):
""" Formats your lovely text into a speech bubble spouted by this adorable
little frog.
"""
stem = ' /'
frog = '\n{text}\n{stem}\n @..@\n (----)\n( >__< )\n^^ ~~ ^^'
offset = len(stem) - 1
formatted_indent = ' ' * offset
formatted_... |
def _unpack_obs(obs, space, tensorlib=tf):
"""Unpack a flattened Dict or Tuple observation array/tensor.
Arguments:
obs: The flattened observation tensor
space: The original space prior to flattening
tensorlib: The library used to unflatten (reshape) the array/tensor
"""
if (is... | def function[_unpack_obs, parameter[obs, space, tensorlib]]:
constant[Unpack a flattened Dict or Tuple observation array/tensor.
Arguments:
obs: The flattened observation tensor
space: The original space prior to flattening
tensorlib: The library used to unflatten (reshape) the arra... | keyword[def] identifier[_unpack_obs] ( identifier[obs] , identifier[space] , identifier[tensorlib] = identifier[tf] ):
literal[string]
keyword[if] ( identifier[isinstance] ( identifier[space] , identifier[gym] . identifier[spaces] . identifier[Dict] )
keyword[or] identifier[isinstance] ( identifier[... | def _unpack_obs(obs, space, tensorlib=tf):
"""Unpack a flattened Dict or Tuple observation array/tensor.
Arguments:
obs: The flattened observation tensor
space: The original space prior to flattening
tensorlib: The library used to unflatten (reshape) the array/tensor
"""
if isin... |
def ds_geom(ds, t_srs=None):
"""Return dataset bbox envelope as geom
"""
gt = ds.GetGeoTransform()
ds_srs = get_ds_srs(ds)
if t_srs is None:
t_srs = ds_srs
ns = ds.RasterXSize
nl = ds.RasterYSize
x = np.array([0, ns, ns, 0, 0], dtype=float)
y = np.array([0, 0, nl, nl, 0], dty... | def function[ds_geom, parameter[ds, t_srs]]:
constant[Return dataset bbox envelope as geom
]
variable[gt] assign[=] call[name[ds].GetGeoTransform, parameter[]]
variable[ds_srs] assign[=] call[name[get_ds_srs], parameter[name[ds]]]
if compare[name[t_srs] is constant[None]] begin[:]
... | keyword[def] identifier[ds_geom] ( identifier[ds] , identifier[t_srs] = keyword[None] ):
literal[string]
identifier[gt] = identifier[ds] . identifier[GetGeoTransform] ()
identifier[ds_srs] = identifier[get_ds_srs] ( identifier[ds] )
keyword[if] identifier[t_srs] keyword[is] keyword[None] :
... | def ds_geom(ds, t_srs=None):
"""Return dataset bbox envelope as geom
"""
gt = ds.GetGeoTransform()
ds_srs = get_ds_srs(ds)
if t_srs is None:
t_srs = ds_srs # depends on [control=['if'], data=['t_srs']]
ns = ds.RasterXSize
nl = ds.RasterYSize
x = np.array([0, ns, ns, 0, 0], dtype... |
def c(self):
"""Caching client for not repeapting checks"""
if self._client is None:
self._parse_settings()
self._client = Rumetr(**self.settings)
return self._client | def function[c, parameter[self]]:
constant[Caching client for not repeapting checks]
if compare[name[self]._client is constant[None]] begin[:]
call[name[self]._parse_settings, parameter[]]
name[self]._client assign[=] call[name[Rumetr], parameter[]]
return[name[self].... | keyword[def] identifier[c] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_client] keyword[is] keyword[None] :
identifier[self] . identifier[_parse_settings] ()
identifier[self] . identifier[_client] = identifier[Rumetr] (** identifier[s... | def c(self):
"""Caching client for not repeapting checks"""
if self._client is None:
self._parse_settings()
self._client = Rumetr(**self.settings) # depends on [control=['if'], data=[]]
return self._client |
def summary(self, raw):
"""Parse, format and return scan summary."""
taxonomies = []
level = "info"
namespace = "Patrowl"
# getreport service
if self.service == 'getreport':
if 'risk_level' in raw and raw['risk_level']:
risk_level = raw['risk_... | def function[summary, parameter[self, raw]]:
constant[Parse, format and return scan summary.]
variable[taxonomies] assign[=] list[[]]
variable[level] assign[=] constant[info]
variable[namespace] assign[=] constant[Patrowl]
if compare[name[self].service equal[==] constant[getrepor... | keyword[def] identifier[summary] ( identifier[self] , identifier[raw] ):
literal[string]
identifier[taxonomies] =[]
identifier[level] = literal[string]
identifier[namespace] = literal[string]
keyword[if] identifier[self] . identifier[service] == literal[strin... | def summary(self, raw):
"""Parse, format and return scan summary."""
taxonomies = []
level = 'info'
namespace = 'Patrowl'
# getreport service
if self.service == 'getreport':
if 'risk_level' in raw and raw['risk_level']:
risk_level = raw['risk_level']
# Grade
... |
def doctemplate(*args):
"""Return a decorator putting ``args`` into the docstring of the decorated ``func``.
>>> @doctemplate('spam', 'spam')
... def spam():
... '''Returns %s, lovely %s.'''
... return 'Spam'
>>> spam.__doc__
'Returns spam, lovely spam.'
"""
def decorator(f... | def function[doctemplate, parameter[]]:
constant[Return a decorator putting ``args`` into the docstring of the decorated ``func``.
>>> @doctemplate('spam', 'spam')
... def spam():
... '''Returns %s, lovely %s.'''
... return 'Spam'
>>> spam.__doc__
'Returns spam, lovely spam.'
... | keyword[def] identifier[doctemplate] (* identifier[args] ):
literal[string]
keyword[def] identifier[decorator] ( identifier[func] ):
identifier[func] . identifier[__doc__] = identifier[func] . identifier[__doc__] % identifier[tuple] ( identifier[args] )
keyword[return] identifier[func] ... | def doctemplate(*args):
"""Return a decorator putting ``args`` into the docstring of the decorated ``func``.
>>> @doctemplate('spam', 'spam')
... def spam():
... '''Returns %s, lovely %s.'''
... return 'Spam'
>>> spam.__doc__
'Returns spam, lovely spam.'
"""
def decorator(... |
def _set_element_property(parent_to_parse, element_path, prop_name, value):
""" Assigns the value to the parsed parent element and then returns it """
element = get_element(parent_to_parse)
if element is None:
return None
if element_path and not element_exists(element, element_path):
... | def function[_set_element_property, parameter[parent_to_parse, element_path, prop_name, value]]:
constant[ Assigns the value to the parsed parent element and then returns it ]
variable[element] assign[=] call[name[get_element], parameter[name[parent_to_parse]]]
if compare[name[element] is consta... | keyword[def] identifier[_set_element_property] ( identifier[parent_to_parse] , identifier[element_path] , identifier[prop_name] , identifier[value] ):
literal[string]
identifier[element] = identifier[get_element] ( identifier[parent_to_parse] )
keyword[if] identifier[element] keyword[is] keyword[... | def _set_element_property(parent_to_parse, element_path, prop_name, value):
""" Assigns the value to the parsed parent element and then returns it """
element = get_element(parent_to_parse)
if element is None:
return None # depends on [control=['if'], data=[]]
if element_path and (not element_e... |
def account(self):
"""
:returns: Account provided as the authenticating account
:rtype: AccountContext
"""
if self._account is None:
self._account = AccountContext(self, self.domain.twilio.account_sid)
return self._account | def function[account, parameter[self]]:
constant[
:returns: Account provided as the authenticating account
:rtype: AccountContext
]
if compare[name[self]._account is constant[None]] begin[:]
name[self]._account assign[=] call[name[AccountContext], parameter[name[s... | keyword[def] identifier[account] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_account] keyword[is] keyword[None] :
identifier[self] . identifier[_account] = identifier[AccountContext] ( identifier[self] , identifier[self] . identifier[domain] . id... | def account(self):
"""
:returns: Account provided as the authenticating account
:rtype: AccountContext
"""
if self._account is None:
self._account = AccountContext(self, self.domain.twilio.account_sid) # depends on [control=['if'], data=[]]
return self._account |
def transform(self, sequences):
"""Apply the dimensionality reduction on X.
Parameters
----------
sequences: list of array-like, each of shape (n_samples_i, n_features)
Training data, where n_samples_i in the number of samples
in sequence i and n_features is the ... | def function[transform, parameter[self, sequences]]:
constant[Apply the dimensionality reduction on X.
Parameters
----------
sequences: list of array-like, each of shape (n_samples_i, n_features)
Training data, where n_samples_i in the number of samples
in sequen... | keyword[def] identifier[transform] ( identifier[self] , identifier[sequences] ):
literal[string]
identifier[check_iter_of_sequences] ( identifier[sequences] , identifier[max_iter] = literal[int] )
identifier[sequences_new] =[]
keyword[for] identifier[X] keyword[in] identifier[... | def transform(self, sequences):
"""Apply the dimensionality reduction on X.
Parameters
----------
sequences: list of array-like, each of shape (n_samples_i, n_features)
Training data, where n_samples_i in the number of samples
in sequence i and n_features is the numb... |
def _query_mysql(self):
"""
Queries mysql and returns a cursor to the results.
"""
mysql = MySqlHook(mysql_conn_id=self.mysql_conn_id)
conn = mysql.get_conn()
cursor = conn.cursor()
cursor.execute(self.sql)
return cursor | def function[_query_mysql, parameter[self]]:
constant[
Queries mysql and returns a cursor to the results.
]
variable[mysql] assign[=] call[name[MySqlHook], parameter[]]
variable[conn] assign[=] call[name[mysql].get_conn, parameter[]]
variable[cursor] assign[=] call[name[c... | keyword[def] identifier[_query_mysql] ( identifier[self] ):
literal[string]
identifier[mysql] = identifier[MySqlHook] ( identifier[mysql_conn_id] = identifier[self] . identifier[mysql_conn_id] )
identifier[conn] = identifier[mysql] . identifier[get_conn] ()
identifier[cursor] = id... | def _query_mysql(self):
"""
Queries mysql and returns a cursor to the results.
"""
mysql = MySqlHook(mysql_conn_id=self.mysql_conn_id)
conn = mysql.get_conn()
cursor = conn.cursor()
cursor.execute(self.sql)
return cursor |
def invalidate_files(self, direct_filenames):
"""Invalidates the given filenames in an internal product Graph instance."""
invalidated = self._scheduler.invalidate_files(direct_filenames)
self._maybe_visualize()
return invalidated | def function[invalidate_files, parameter[self, direct_filenames]]:
constant[Invalidates the given filenames in an internal product Graph instance.]
variable[invalidated] assign[=] call[name[self]._scheduler.invalidate_files, parameter[name[direct_filenames]]]
call[name[self]._maybe_visualize, pa... | keyword[def] identifier[invalidate_files] ( identifier[self] , identifier[direct_filenames] ):
literal[string]
identifier[invalidated] = identifier[self] . identifier[_scheduler] . identifier[invalidate_files] ( identifier[direct_filenames] )
identifier[self] . identifier[_maybe_visualize] ()
key... | def invalidate_files(self, direct_filenames):
"""Invalidates the given filenames in an internal product Graph instance."""
invalidated = self._scheduler.invalidate_files(direct_filenames)
self._maybe_visualize()
return invalidated |
def _longest_val_in_column(self, col):
"""
get size of longest value in specific column
:param col: str, column name
:return int
"""
try:
# +2 is for implicit separator
return max([len(x[col]) for x in self.table if x[col]]) + 2
except Key... | def function[_longest_val_in_column, parameter[self, col]]:
constant[
get size of longest value in specific column
:param col: str, column name
:return int
]
<ast.Try object at 0x7da1b0fdb730> | keyword[def] identifier[_longest_val_in_column] ( identifier[self] , identifier[col] ):
literal[string]
keyword[try] :
keyword[return] identifier[max] ([ identifier[len] ( identifier[x] [ identifier[col] ]) keyword[for] identifier[x] keyword[in] identifier[self] . identifi... | def _longest_val_in_column(self, col):
"""
get size of longest value in specific column
:param col: str, column name
:return int
"""
try:
# +2 is for implicit separator
return max([len(x[col]) for x in self.table if x[col]]) + 2 # depends on [control=['try'], da... |
def download():
"""
Download all files from an FTP share
"""
ftp = ftplib.FTP(SITE)
ftp.set_debuglevel(DEBUG)
ftp.login(USER, PASSWD)
ftp.cwd(DIR)
filelist = ftp.nlst()
filecounter = MANAGER.counter(total=len(filelist), desc='Downloading',
unit='fil... | def function[download, parameter[]]:
constant[
Download all files from an FTP share
]
variable[ftp] assign[=] call[name[ftplib].FTP, parameter[name[SITE]]]
call[name[ftp].set_debuglevel, parameter[name[DEBUG]]]
call[name[ftp].login, parameter[name[USER], name[PASSWD]]]
ca... | keyword[def] identifier[download] ():
literal[string]
identifier[ftp] = identifier[ftplib] . identifier[FTP] ( identifier[SITE] )
identifier[ftp] . identifier[set_debuglevel] ( identifier[DEBUG] )
identifier[ftp] . identifier[login] ( identifier[USER] , identifier[PASSWD] )
identifier[ftp] ... | def download():
"""
Download all files from an FTP share
"""
ftp = ftplib.FTP(SITE)
ftp.set_debuglevel(DEBUG)
ftp.login(USER, PASSWD)
ftp.cwd(DIR)
filelist = ftp.nlst()
filecounter = MANAGER.counter(total=len(filelist), desc='Downloading', unit='files')
for filename in filelist:
... |
def _get_video(edx_video_id):
"""
Get a Video instance, prefetching encoded video and course information.
Raises ValVideoNotFoundError if the video cannot be retrieved.
"""
try:
return Video.objects.prefetch_related("encoded_videos", "courses").get(edx_video_id=edx_video_id)
except Vide... | def function[_get_video, parameter[edx_video_id]]:
constant[
Get a Video instance, prefetching encoded video and course information.
Raises ValVideoNotFoundError if the video cannot be retrieved.
]
<ast.Try object at 0x7da20c795210> | keyword[def] identifier[_get_video] ( identifier[edx_video_id] ):
literal[string]
keyword[try] :
keyword[return] identifier[Video] . identifier[objects] . identifier[prefetch_related] ( literal[string] , literal[string] ). identifier[get] ( identifier[edx_video_id] = identifier[edx_video_id] )
... | def _get_video(edx_video_id):
"""
Get a Video instance, prefetching encoded video and course information.
Raises ValVideoNotFoundError if the video cannot be retrieved.
"""
try:
return Video.objects.prefetch_related('encoded_videos', 'courses').get(edx_video_id=edx_video_id) # depends on [... |
def _generic_convert_string(v, from_type, to_type, encoding):
"""
Generic method to convert any argument type (string type, list, set, tuple, dict) to an equivalent,
with string values converted to given 'to_type' (str or unicode).
This method must be used with Python 2 interpreter only.
:param v: ... | def function[_generic_convert_string, parameter[v, from_type, to_type, encoding]]:
constant[
Generic method to convert any argument type (string type, list, set, tuple, dict) to an equivalent,
with string values converted to given 'to_type' (str or unicode).
This method must be used with Python 2 in... | keyword[def] identifier[_generic_convert_string] ( identifier[v] , identifier[from_type] , identifier[to_type] , identifier[encoding] ):
literal[string]
keyword[assert] identifier[six] . identifier[PY2] , literal[string]
keyword[assert] identifier[from_type] != identifier[to_type]
keyword[i... | def _generic_convert_string(v, from_type, to_type, encoding):
"""
Generic method to convert any argument type (string type, list, set, tuple, dict) to an equivalent,
with string values converted to given 'to_type' (str or unicode).
This method must be used with Python 2 interpreter only.
:param v: ... |
def set_column_sizes(self, values):
"""Sets the size value for each column
Args:
values (iterable of int or str): values are treated as percentage.
"""
self.style['grid-template-columns'] = ' '.join(map(lambda value: (str(value) if str(value).endswith('%') else str(value) + ... | def function[set_column_sizes, parameter[self, values]]:
constant[Sets the size value for each column
Args:
values (iterable of int or str): values are treated as percentage.
]
call[name[self].style][constant[grid-template-columns]] assign[=] call[constant[ ].join, parameter... | keyword[def] identifier[set_column_sizes] ( identifier[self] , identifier[values] ):
literal[string]
identifier[self] . identifier[style] [ literal[string] ]= literal[string] . identifier[join] ( identifier[map] ( keyword[lambda] identifier[value] :( identifier[str] ( identifier[value] ) keyword[i... | def set_column_sizes(self, values):
"""Sets the size value for each column
Args:
values (iterable of int or str): values are treated as percentage.
"""
self.style['grid-template-columns'] = ' '.join(map(lambda value: str(value) if str(value).endswith('%') else str(value) + '%', valu... |
def start(self):
"""
This method defines the workflow of SirMordred. So it calls to:
- initialize the databases
- execute the different phases for the first iteration
(collection, identities, enrichment)
- start the collection and enrichment in parallel by data source
... | def function[start, parameter[self]]:
constant[
This method defines the workflow of SirMordred. So it calls to:
- initialize the databases
- execute the different phases for the first iteration
(collection, identities, enrichment)
- start the collection and enrichment i... | keyword[def] identifier[start] ( identifier[self] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] )
identifier[logger] . identifier[info] ( literal[string] )
identifier[logger] . identifier[info] ( literal[string] )
identifier[logger] ... | def start(self):
"""
This method defines the workflow of SirMordred. So it calls to:
- initialize the databases
- execute the different phases for the first iteration
(collection, identities, enrichment)
- start the collection and enrichment in parallel by data source
... |
def azureContainers(self, *args, **kwargs):
"""
List containers in an Account Managed by Auth
Retrieve a list of all containers in an account.
This method gives output: ``v1/azure-container-list-response.json#``
This method is ``stable``
"""
return self._makeA... | def function[azureContainers, parameter[self]]:
constant[
List containers in an Account Managed by Auth
Retrieve a list of all containers in an account.
This method gives output: ``v1/azure-container-list-response.json#``
This method is ``stable``
]
return[call[nam... | keyword[def] identifier[azureContainers] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[_makeApiCall] ( identifier[self] . identifier[funcinfo] [ literal[string] ],* identifier[args] ,** identifier[kwargs] ) | def azureContainers(self, *args, **kwargs):
"""
List containers in an Account Managed by Auth
Retrieve a list of all containers in an account.
This method gives output: ``v1/azure-container-list-response.json#``
This method is ``stable``
"""
return self._makeApiCall(se... |
def get_par_change_limits(self):
""" calculate the various parameter change limits used in pest.
Works in control file values space (not log transformed space). Also
adds columns for effective upper and lower which account for par bounds and the
value of parchglim
Returns
... | def function[get_par_change_limits, parameter[self]]:
constant[ calculate the various parameter change limits used in pest.
Works in control file values space (not log transformed space). Also
adds columns for effective upper and lower which account for par bounds and the
value of parc... | keyword[def] identifier[get_par_change_limits] ( identifier[self] ):
literal[string]
identifier[par] = identifier[self] . identifier[parameter_data]
identifier[fpars] = identifier[par] . identifier[loc] [ identifier[par] . identifier[parchglim] == literal[string] , literal[string] ]
... | def get_par_change_limits(self):
""" calculate the various parameter change limits used in pest.
Works in control file values space (not log transformed space). Also
adds columns for effective upper and lower which account for par bounds and the
value of parchglim
Returns
... |
def apply(self, node):
""" Apply transformation and return if an update happened. """
new_node = self.run(node)
return self.update, new_node | def function[apply, parameter[self, node]]:
constant[ Apply transformation and return if an update happened. ]
variable[new_node] assign[=] call[name[self].run, parameter[name[node]]]
return[tuple[[<ast.Attribute object at 0x7da20c76c0a0>, <ast.Name object at 0x7da20c76f1f0>]]] | keyword[def] identifier[apply] ( identifier[self] , identifier[node] ):
literal[string]
identifier[new_node] = identifier[self] . identifier[run] ( identifier[node] )
keyword[return] identifier[self] . identifier[update] , identifier[new_node] | def apply(self, node):
""" Apply transformation and return if an update happened. """
new_node = self.run(node)
return (self.update, new_node) |
def delete(self):
"""
Remove the document and all of its bundles from ProvStore.
.. warning::
Cannot be undone.
"""
if self.abstract:
raise AbstractDocumentException()
self._api.delete_document(self.id)
self._id = None
return True | def function[delete, parameter[self]]:
constant[
Remove the document and all of its bundles from ProvStore.
.. warning::
Cannot be undone.
]
if name[self].abstract begin[:]
<ast.Raise object at 0x7da20e9b0220>
call[name[self]._api.delete_document, para... | keyword[def] identifier[delete] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[abstract] :
keyword[raise] identifier[AbstractDocumentException] ()
identifier[self] . identifier[_api] . identifier[delete_document] ( identifier[self] . identif... | def delete(self):
"""
Remove the document and all of its bundles from ProvStore.
.. warning::
Cannot be undone.
"""
if self.abstract:
raise AbstractDocumentException() # depends on [control=['if'], data=[]]
self._api.delete_document(self.id)
self._id = None
... |
def get_time(self) -> float:
"""
Get the current time in seconds
Returns:
The current time in seconds
"""
if self.pause_time is not None:
curr_time = self.pause_time - self.offset - self.start_time
return curr_time
curr_time = time.ti... | def function[get_time, parameter[self]]:
constant[
Get the current time in seconds
Returns:
The current time in seconds
]
if compare[name[self].pause_time is_not constant[None]] begin[:]
variable[curr_time] assign[=] binary_operation[binary_operation[... | keyword[def] identifier[get_time] ( identifier[self] )-> identifier[float] :
literal[string]
keyword[if] identifier[self] . identifier[pause_time] keyword[is] keyword[not] keyword[None] :
identifier[curr_time] = identifier[self] . identifier[pause_time] - identifier[self] . identif... | def get_time(self) -> float:
"""
Get the current time in seconds
Returns:
The current time in seconds
"""
if self.pause_time is not None:
curr_time = self.pause_time - self.offset - self.start_time
return curr_time # depends on [control=['if'], data=[]]
... |
def _create_service(self, parameters={}, **kwargs):
"""
Create a Cloud Foundry service that has custom parameters.
"""
logging.debug("_create_service()")
logging.debug(str.join(',', [self.service_name, self.plan_name,
self.name, str(parameters)]))
return self... | def function[_create_service, parameter[self, parameters]]:
constant[
Create a Cloud Foundry service that has custom parameters.
]
call[name[logging].debug, parameter[constant[_create_service()]]]
call[name[logging].debug, parameter[call[name[str].join, parameter[constant[,], lis... | keyword[def] identifier[_create_service] ( identifier[self] , identifier[parameters] ={},** identifier[kwargs] ):
literal[string]
identifier[logging] . identifier[debug] ( literal[string] )
identifier[logging] . identifier[debug] ( identifier[str] . identifier[join] ( literal[string] ,[ id... | def _create_service(self, parameters={}, **kwargs):
"""
Create a Cloud Foundry service that has custom parameters.
"""
logging.debug('_create_service()')
logging.debug(str.join(',', [self.service_name, self.plan_name, self.name, str(parameters)]))
return self.service.create_service(self.... |
def gradient_n_pal(colors, values=None, name='gradientn'):
"""
Create a n color gradient palette
Parameters
----------
colors : list
list of colors
values : list, optional
list of points in the range [0, 1] at which to
place each color. Must be the same size as
`... | def function[gradient_n_pal, parameter[colors, values, name]]:
constant[
Create a n color gradient palette
Parameters
----------
colors : list
list of colors
values : list, optional
list of points in the range [0, 1] at which to
place each color. Must be the same siz... | keyword[def] identifier[gradient_n_pal] ( identifier[colors] , identifier[values] = keyword[None] , identifier[name] = literal[string] ):
literal[string]
keyword[if] identifier[values] keyword[is] keyword[None] :
identifier[colormap] = identifier[mcolors] . identifier[LinearSegme... | def gradient_n_pal(colors, values=None, name='gradientn'):
"""
Create a n color gradient palette
Parameters
----------
colors : list
list of colors
values : list, optional
list of points in the range [0, 1] at which to
place each color. Must be the same size as
`... |
def cancel_spot_instance_requests(self, request_ids):
"""
Cancel the specified Spot Instance Requests.
:type request_ids: list
:param request_ids: A list of strings of the Request IDs to terminate
:rtype: list
:return: A list of the instances terminated
"""
... | def function[cancel_spot_instance_requests, parameter[self, request_ids]]:
constant[
Cancel the specified Spot Instance Requests.
:type request_ids: list
:param request_ids: A list of strings of the Request IDs to terminate
:rtype: list
:return: A list of the instances ... | keyword[def] identifier[cancel_spot_instance_requests] ( identifier[self] , identifier[request_ids] ):
literal[string]
identifier[params] ={}
keyword[if] identifier[request_ids] :
identifier[self] . identifier[build_list_params] ( identifier[params] , identifier[request_ids] ... | def cancel_spot_instance_requests(self, request_ids):
"""
Cancel the specified Spot Instance Requests.
:type request_ids: list
:param request_ids: A list of strings of the Request IDs to terminate
:rtype: list
:return: A list of the instances terminated
"""
para... |
def loadItems(self, excludeRead=False, loadLimit=20, since=None, until=None):
"""
Load items and call itemsLoadedDone to transform data in objects
"""
self.clearItems()
self.loadtLoadOk = False
self.lastLoadLength = 0
self._itemsLoadedDone(self._getContent(excl... | def function[loadItems, parameter[self, excludeRead, loadLimit, since, until]]:
constant[
Load items and call itemsLoadedDone to transform data in objects
]
call[name[self].clearItems, parameter[]]
name[self].loadtLoadOk assign[=] constant[False]
name[self].lastLoadLength... | keyword[def] identifier[loadItems] ( identifier[self] , identifier[excludeRead] = keyword[False] , identifier[loadLimit] = literal[int] , identifier[since] = keyword[None] , identifier[until] = keyword[None] ):
literal[string]
identifier[self] . identifier[clearItems] ()
identifier[self] .... | def loadItems(self, excludeRead=False, loadLimit=20, since=None, until=None):
"""
Load items and call itemsLoadedDone to transform data in objects
"""
self.clearItems()
self.loadtLoadOk = False
self.lastLoadLength = 0
self._itemsLoadedDone(self._getContent(excludeRead, None, loadLimi... |
def read_var_bytes(self, max_size=sys.maxsize) -> bytes:
"""
Read a variable length of bytes from the stream.
Args:
max_size (int): (Optional) maximum number of bytes to read.
Returns:
bytes:
"""
length = self.read_var_int(max_size)
retur... | def function[read_var_bytes, parameter[self, max_size]]:
constant[
Read a variable length of bytes from the stream.
Args:
max_size (int): (Optional) maximum number of bytes to read.
Returns:
bytes:
]
variable[length] assign[=] call[name[self].rea... | keyword[def] identifier[read_var_bytes] ( identifier[self] , identifier[max_size] = identifier[sys] . identifier[maxsize] )-> identifier[bytes] :
literal[string]
identifier[length] = identifier[self] . identifier[read_var_int] ( identifier[max_size] )
keyword[return] identifier[self] . id... | def read_var_bytes(self, max_size=sys.maxsize) -> bytes:
"""
Read a variable length of bytes from the stream.
Args:
max_size (int): (Optional) maximum number of bytes to read.
Returns:
bytes:
"""
length = self.read_var_int(max_size)
return self.read_... |
def add_user(
self,
name,
**attrs
):
"""Add a user to config."""
if self.user_exists(name):
raise KubeConfError("user with the given name already exists.")
users = self.get_users()
# Add parameters.
new_user = {'name': name, ... | def function[add_user, parameter[self, name]]:
constant[Add a user to config.]
if call[name[self].user_exists, parameter[name[name]]] begin[:]
<ast.Raise object at 0x7da18c4ceaa0>
variable[users] assign[=] call[name[self].get_users, parameter[]]
variable[new_user] assign[=] dicti... | keyword[def] identifier[add_user] (
identifier[self] ,
identifier[name] ,
** identifier[attrs]
):
literal[string]
keyword[if] identifier[self] . identifier[user_exists] ( identifier[name] ):
keyword[raise] identifier[KubeConfError] ( literal[string] )
identifier[users] =... | def add_user(self, name, **attrs):
"""Add a user to config."""
if self.user_exists(name):
raise KubeConfError('user with the given name already exists.') # depends on [control=['if'], data=[]]
users = self.get_users()
# Add parameters.
new_user = {'name': name, 'user': {}}
attrs_ = new_... |
def _get_environment(self):
"""Defines any necessary environment variables for the pod executor"""
env = {}
for env_var_name, env_var_val in six.iteritems(self.kube_config.kube_env_vars):
env[env_var_name] = env_var_val
env["AIRFLOW__CORE__EXECUTOR"] = "LocalExecutor"
... | def function[_get_environment, parameter[self]]:
constant[Defines any necessary environment variables for the pod executor]
variable[env] assign[=] dictionary[[], []]
for taget[tuple[[<ast.Name object at 0x7da18bcc8b80>, <ast.Name object at 0x7da18bccace0>]]] in starred[call[name[six].iteritems,... | keyword[def] identifier[_get_environment] ( identifier[self] ):
literal[string]
identifier[env] ={}
keyword[for] identifier[env_var_name] , identifier[env_var_val] keyword[in] identifier[six] . identifier[iteritems] ( identifier[self] . identifier[kube_config] . identifier[kube_env_var... | def _get_environment(self):
"""Defines any necessary environment variables for the pod executor"""
env = {}
for (env_var_name, env_var_val) in six.iteritems(self.kube_config.kube_env_vars):
env[env_var_name] = env_var_val # depends on [control=['for'], data=[]]
env['AIRFLOW__CORE__EXECUTOR'] = ... |
def star(self) -> snug.Query[bool]:
"""star this repo"""
req = snug.PUT(BASE + f'/user/starred/{self.owner}/{self.name}')
return (yield req).status_code == 204 | def function[star, parameter[self]]:
constant[star this repo]
variable[req] assign[=] call[name[snug].PUT, parameter[binary_operation[name[BASE] + <ast.JoinedStr object at 0x7da1b2448cd0>]]]
return[compare[<ast.Yield object at 0x7da1b244aaa0>.status_code equal[==] constant[204]]] | keyword[def] identifier[star] ( identifier[self] )-> identifier[snug] . identifier[Query] [ identifier[bool] ]:
literal[string]
identifier[req] = identifier[snug] . identifier[PUT] ( identifier[BASE] + literal[string] )
keyword[return] ( keyword[yield] identifier[req] ). identifier[status... | def star(self) -> snug.Query[bool]:
"""star this repo"""
req = snug.PUT(BASE + f'/user/starred/{self.owner}/{self.name}')
return (yield req).status_code == 204 |
def _parse_key(self, indent):
"""Parse a series of key-value pairs."""
data = {}
new_indent = indent
while not self._finished and new_indent == indent:
self._skip_whitespace()
cur_token = self._cur_token
if cur_token['type'] is TT.id:
... | def function[_parse_key, parameter[self, indent]]:
constant[Parse a series of key-value pairs.]
variable[data] assign[=] dictionary[[], []]
variable[new_indent] assign[=] name[indent]
while <ast.BoolOp object at 0x7da2047eb5e0> begin[:]
call[name[self]._skip_whitespace, p... | keyword[def] identifier[_parse_key] ( identifier[self] , identifier[indent] ):
literal[string]
identifier[data] ={}
identifier[new_indent] = identifier[indent]
keyword[while] keyword[not] identifier[self] . identifier[_finished] keyword[and] identifier[new_indent] == identif... | def _parse_key(self, indent):
"""Parse a series of key-value pairs."""
data = {}
new_indent = indent
while not self._finished and new_indent == indent:
self._skip_whitespace()
cur_token = self._cur_token
if cur_token['type'] is TT.id:
key = cur_token['value']
... |
def zscale(image, nsamples=1000, contrast=0.25):
"""Implement IRAF zscale algorithm
nsamples=1000 and contrast=0.25 are the IRAF display task defaults
image is a 2-d numpy array
returns (z1, z2)
"""
# Sample the image
samples = zsc_sample(image, nsamples)
return zscale_samples(samples,... | def function[zscale, parameter[image, nsamples, contrast]]:
constant[Implement IRAF zscale algorithm
nsamples=1000 and contrast=0.25 are the IRAF display task defaults
image is a 2-d numpy array
returns (z1, z2)
]
variable[samples] assign[=] call[name[zsc_sample], parameter[name[image], ... | keyword[def] identifier[zscale] ( identifier[image] , identifier[nsamples] = literal[int] , identifier[contrast] = literal[int] ):
literal[string]
identifier[samples] = identifier[zsc_sample] ( identifier[image] , identifier[nsamples] )
keyword[return] identifier[zscale_samples] ( identifier[s... | def zscale(image, nsamples=1000, contrast=0.25):
"""Implement IRAF zscale algorithm
nsamples=1000 and contrast=0.25 are the IRAF display task defaults
image is a 2-d numpy array
returns (z1, z2)
"""
# Sample the image
samples = zsc_sample(image, nsamples)
return zscale_samples(samples, c... |
def list_buckets(self, offset=0, limit=100):
"""Limit breaks above 100"""
# TODO: If limit > 100, do multiple fetches
if limit > 100:
raise Exception("Zenobase can't handle limits over 100")
return self._get("/users/{}/buckets/?order=label&offset={}&limit={}".format(self.clie... | def function[list_buckets, parameter[self, offset, limit]]:
constant[Limit breaks above 100]
if compare[name[limit] greater[>] constant[100]] begin[:]
<ast.Raise object at 0x7da20e961270>
return[call[name[self]._get, parameter[call[constant[/users/{}/buckets/?order=label&offset={}&limit={}].... | keyword[def] identifier[list_buckets] ( identifier[self] , identifier[offset] = literal[int] , identifier[limit] = literal[int] ):
literal[string]
keyword[if] identifier[limit] > literal[int] :
keyword[raise] identifier[Exception] ( literal[string] )
keyword[return]... | def list_buckets(self, offset=0, limit=100):
"""Limit breaks above 100"""
# TODO: If limit > 100, do multiple fetches
if limit > 100:
raise Exception("Zenobase can't handle limits over 100") # depends on [control=['if'], data=[]]
return self._get('/users/{}/buckets/?order=label&offset={}&limit=... |
def __add_delayed_assert_failure(self):
""" Add a delayed_assert failure into a list for future processing. """
current_url = self.driver.current_url
message = self.__get_exception_message()
self.__delayed_assert_failures.append(
"CHECK #%s: (%s)\n %s" % (
sel... | def function[__add_delayed_assert_failure, parameter[self]]:
constant[ Add a delayed_assert failure into a list for future processing. ]
variable[current_url] assign[=] name[self].driver.current_url
variable[message] assign[=] call[name[self].__get_exception_message, parameter[]]
call[na... | keyword[def] identifier[__add_delayed_assert_failure] ( identifier[self] ):
literal[string]
identifier[current_url] = identifier[self] . identifier[driver] . identifier[current_url]
identifier[message] = identifier[self] . identifier[__get_exception_message] ()
identifier[self] .... | def __add_delayed_assert_failure(self):
""" Add a delayed_assert failure into a list for future processing. """
current_url = self.driver.current_url
message = self.__get_exception_message()
self.__delayed_assert_failures.append('CHECK #%s: (%s)\n %s' % (self.__delayed_assert_count, current_url, message... |
def eval_basis(self, x, regularize=True):
"""
basis_mat = C.eval_basis(x)
Evaluates self's basis functions on x and returns them stacked
in a matrix. basis_mat[i,j] gives basis function i evaluated at
x[j,:].
"""
if regularize:
x = regularize_array(x)... | def function[eval_basis, parameter[self, x, regularize]]:
constant[
basis_mat = C.eval_basis(x)
Evaluates self's basis functions on x and returns them stacked
in a matrix. basis_mat[i,j] gives basis function i evaluated at
x[j,:].
]
if name[regularize] begin[:]
... | keyword[def] identifier[eval_basis] ( identifier[self] , identifier[x] , identifier[regularize] = keyword[True] ):
literal[string]
keyword[if] identifier[regularize] :
identifier[x] = identifier[regularize_array] ( identifier[x] )
identifier[out] = identifier[zeros] (( ident... | def eval_basis(self, x, regularize=True):
"""
basis_mat = C.eval_basis(x)
Evaluates self's basis functions on x and returns them stacked
in a matrix. basis_mat[i,j] gives basis function i evaluated at
x[j,:].
"""
if regularize:
x = regularize_array(x) # depends ... |
def connect(self):
"""Connects the client object to redis.
It's safe to use this method even if you are already connected.
Note: this method is useless with autoconnect mode (default).
Returns:
a Future object with True as result if the connection was ok.
"""
... | def function[connect, parameter[self]]:
constant[Connects the client object to redis.
It's safe to use this method even if you are already connected.
Note: this method is useless with autoconnect mode (default).
Returns:
a Future object with True as result if the connection... | keyword[def] identifier[connect] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[is_connected] ():
keyword[raise] identifier[tornado] . identifier[gen] . identifier[Return] ( keyword[True] )
identifier[cb1] = identifier[self] . identifier[_rea... | def connect(self):
"""Connects the client object to redis.
It's safe to use this method even if you are already connected.
Note: this method is useless with autoconnect mode (default).
Returns:
a Future object with True as result if the connection was ok.
"""
if sel... |
def _enforce_bounds(self, x):
""""Enforce the bounds on x if only infinitesimal violations occurs"""
assert len(x) == len(self.bounds)
x_enforced = []
for x_i, (lb, ub) in zip(x, self.bounds):
if x_i < lb:
if x_i > lb - (ub-lb)/1e10:
x_enfo... | def function[_enforce_bounds, parameter[self, x]]:
constant["Enforce the bounds on x if only infinitesimal violations occurs]
assert[compare[call[name[len], parameter[name[x]]] equal[==] call[name[len], parameter[name[self].bounds]]]]
variable[x_enforced] assign[=] list[[]]
for taget[tuple[[... | keyword[def] identifier[_enforce_bounds] ( identifier[self] , identifier[x] ):
literal[string]
keyword[assert] identifier[len] ( identifier[x] )== identifier[len] ( identifier[self] . identifier[bounds] )
identifier[x_enforced] =[]
keyword[for] identifier[x_i] ,( identifier[lb] ... | def _enforce_bounds(self, x):
""""Enforce the bounds on x if only infinitesimal violations occurs"""
assert len(x) == len(self.bounds)
x_enforced = []
for (x_i, (lb, ub)) in zip(x, self.bounds):
if x_i < lb:
if x_i > lb - (ub - lb) / 10000000000.0:
x_enforced.append(l... |
def _decompress_data(self, data, options):
'''Decompress data'''
compression_algorithm_id = options['compression_algorithm_id']
if compression_algorithm_id not in self.compression_algorithms:
raise Exception('Unknown compression algorithm id: %d'
% compre... | def function[_decompress_data, parameter[self, data, options]]:
constant[Decompress data]
variable[compression_algorithm_id] assign[=] call[name[options]][constant[compression_algorithm_id]]
if compare[name[compression_algorithm_id] <ast.NotIn object at 0x7da2590d7190> name[self].compression_alg... | keyword[def] identifier[_decompress_data] ( identifier[self] , identifier[data] , identifier[options] ):
literal[string]
identifier[compression_algorithm_id] = identifier[options] [ literal[string] ]
keyword[if] identifier[compression_algorithm_id] keyword[not] keyword[in] identifier[... | def _decompress_data(self, data, options):
"""Decompress data"""
compression_algorithm_id = options['compression_algorithm_id']
if compression_algorithm_id not in self.compression_algorithms:
raise Exception('Unknown compression algorithm id: %d' % compression_algorithm_id) # depends on [control=['... |
def _ParseCredentialOptions(self, options):
"""Parses the credential options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
"""
credentials = getattr(options, 'credentials', [])
if not isinstance(credentials, list):... | def function[_ParseCredentialOptions, parameter[self, options]]:
constant[Parses the credential options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
]
variable[credentials] assign[=] call[name[getattr], parame... | keyword[def] identifier[_ParseCredentialOptions] ( identifier[self] , identifier[options] ):
literal[string]
identifier[credentials] = identifier[getattr] ( identifier[options] , literal[string] ,[])
keyword[if] keyword[not] identifier[isinstance] ( identifier[credentials] , identifier[list] ):
... | def _ParseCredentialOptions(self, options):
"""Parses the credential options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
"""
credentials = getattr(options, 'credentials', [])
if not isinstance(credentials, list):... |
def exists_evaluator(self, index):
""" Evaluate the given exists match condition for the user attributes.
Args:
index: Index of the condition to be evaluated.
Returns:
Boolean: True if the user attributes have a non-null value for the given condition,
otherwise False.
... | def function[exists_evaluator, parameter[self, index]]:
constant[ Evaluate the given exists match condition for the user attributes.
Args:
index: Index of the condition to be evaluated.
Returns:
Boolean: True if the user attributes have a non-null value for the given condition,
... | keyword[def] identifier[exists_evaluator] ( identifier[self] , identifier[index] ):
literal[string]
identifier[attr_name] = identifier[self] . identifier[condition_data] [ identifier[index] ][ literal[int] ]
keyword[return] identifier[self] . identifier[attributes] . identifier[get] ( identifier[attr... | def exists_evaluator(self, index):
""" Evaluate the given exists match condition for the user attributes.
Args:
index: Index of the condition to be evaluated.
Returns:
Boolean: True if the user attributes have a non-null value for the given condition,
otherwise False.
... |
def cut_cuboid(
self,
a=20,
b=None,
c=None,
origin=None,
outside_sliced=True,
preserve_bonds=False):
"""Cut a cuboid specified by edge and radius.
Args:
a (float): Value of the a edge.
b (float):... | def function[cut_cuboid, parameter[self, a, b, c, origin, outside_sliced, preserve_bonds]]:
constant[Cut a cuboid specified by edge and radius.
Args:
a (float): Value of the a edge.
b (float): Value of the b edge. Takes value of a if None.
c (float): Value of the c e... | keyword[def] identifier[cut_cuboid] (
identifier[self] ,
identifier[a] = literal[int] ,
identifier[b] = keyword[None] ,
identifier[c] = keyword[None] ,
identifier[origin] = keyword[None] ,
identifier[outside_sliced] = keyword[True] ,
identifier[preserve_bonds] = keyword[False] ):
literal[string]
... | def cut_cuboid(self, a=20, b=None, c=None, origin=None, outside_sliced=True, preserve_bonds=False):
"""Cut a cuboid specified by edge and radius.
Args:
a (float): Value of the a edge.
b (float): Value of the b edge. Takes value of a if None.
c (float): Value of the c edg... |
def _server_url(server):
"""
Normalizes a given server string to an url
>>> print(_server_url('a'))
http://a
>>> print(_server_url('a:9345'))
http://a:9345
>>> print(_server_url('https://a:9345'))
https://a:9345
>>> print(_server_url('https://a'))
https://a
>>> print(_server... | def function[_server_url, parameter[server]]:
constant[
Normalizes a given server string to an url
>>> print(_server_url('a'))
http://a
>>> print(_server_url('a:9345'))
http://a:9345
>>> print(_server_url('https://a:9345'))
https://a:9345
>>> print(_server_url('https://a'))
... | keyword[def] identifier[_server_url] ( identifier[server] ):
literal[string]
keyword[if] keyword[not] identifier[_HTTP_PAT] . identifier[match] ( identifier[server] ):
identifier[server] = literal[string] % identifier[server]
identifier[parsed] = identifier[urlparse] ( identifier[server] )... | def _server_url(server):
"""
Normalizes a given server string to an url
>>> print(_server_url('a'))
http://a
>>> print(_server_url('a:9345'))
http://a:9345
>>> print(_server_url('https://a:9345'))
https://a:9345
>>> print(_server_url('https://a'))
https://a
>>> print(_server... |
def __load_predictions(self):
"""private method set the predictions attribute from:
mixed list of row names, matrix files and ndarrays
a single row name
an ascii file
can be none if only interested in parameters.
"""
if self.prediction... | def function[__load_predictions, parameter[self]]:
constant[private method set the predictions attribute from:
mixed list of row names, matrix files and ndarrays
a single row name
an ascii file
can be none if only interested in parameters.
]
... | keyword[def] identifier[__load_predictions] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[prediction_arg] keyword[is] keyword[None] :
identifier[self] . identifier[__predictions] = keyword[None]
keyword[return]
identifier[sel... | def __load_predictions(self):
"""private method set the predictions attribute from:
mixed list of row names, matrix files and ndarrays
a single row name
an ascii file
can be none if only interested in parameters.
"""
if self.prediction_arg is ... |
def get_plugin_actions(self):
"""Return a list of actions related to plugin."""
create_nb_action = create_action(self,
_("New notebook"),
icon=ima.icon('filenew'),
triggered=se... | def function[get_plugin_actions, parameter[self]]:
constant[Return a list of actions related to plugin.]
variable[create_nb_action] assign[=] call[name[create_action], parameter[name[self], call[name[_], parameter[constant[New notebook]]]]]
name[self].save_as_action assign[=] call[name[create_ac... | keyword[def] identifier[get_plugin_actions] ( identifier[self] ):
literal[string]
identifier[create_nb_action] = identifier[create_action] ( identifier[self] ,
identifier[_] ( literal[string] ),
identifier[icon] = identifier[ima] . identifier[icon] ( literal[string] ),
... | def get_plugin_actions(self):
"""Return a list of actions related to plugin."""
create_nb_action = create_action(self, _('New notebook'), icon=ima.icon('filenew'), triggered=self.create_new_client)
self.save_as_action = create_action(self, _('Save as...'), icon=ima.icon('filesaveas'), triggered=self.save_as... |
def cores(self):
"""Generate the set of all cores in the system.
Yields
------
(x, y, p, :py:class:`~rig.machine_control.consts.AppState`)
A core in the machine, and its state. Cores related to a specific
chip are yielded consecutively in ascending order of core ... | def function[cores, parameter[self]]:
constant[Generate the set of all cores in the system.
Yields
------
(x, y, p, :py:class:`~rig.machine_control.consts.AppState`)
A core in the machine, and its state. Cores related to a specific
chip are yielded consecutively ... | keyword[def] identifier[cores] ( identifier[self] ):
literal[string]
keyword[for] ( identifier[x] , identifier[y] ), identifier[chip_info] keyword[in] identifier[iteritems] ( identifier[self] ):
keyword[for] identifier[p] , identifier[state] keyword[in] identifier[enumerate] ( ide... | def cores(self):
"""Generate the set of all cores in the system.
Yields
------
(x, y, p, :py:class:`~rig.machine_control.consts.AppState`)
A core in the machine, and its state. Cores related to a specific
chip are yielded consecutively in ascending order of core numb... |
def _entry_management_url_download(self, passed):
"""
Check if the given information is a URL.
If it is the case, it download and update the location of file to test.
:param passed: The url passed to the system.
:type passed: str
:return: The state of the check.
... | def function[_entry_management_url_download, parameter[self, passed]]:
constant[
Check if the given information is a URL.
If it is the case, it download and update the location of file to test.
:param passed: The url passed to the system.
:type passed: str
:return: The ... | keyword[def] identifier[_entry_management_url_download] ( identifier[self] , identifier[passed] ):
literal[string]
keyword[if] identifier[passed] keyword[and] identifier[self] . identifier[checker] . identifier[is_url_valid] ( identifier[passed] ):
ident... | def _entry_management_url_download(self, passed):
"""
Check if the given information is a URL.
If it is the case, it download and update the location of file to test.
:param passed: The url passed to the system.
:type passed: str
:return: The state of the check.
:rt... |
def _get_gosrcs_upper(self, goids, max_upper, go2parentids):
"""Get GO IDs for the upper portion of the GO DAG."""
gosrcs_upper = set()
get_nt = self.gosubdag.go2nt.get
go2nt = {g:get_nt(g) for g in goids}
# Sort by descending order of descendant counts to find potential new hdrg... | def function[_get_gosrcs_upper, parameter[self, goids, max_upper, go2parentids]]:
constant[Get GO IDs for the upper portion of the GO DAG.]
variable[gosrcs_upper] assign[=] call[name[set], parameter[]]
variable[get_nt] assign[=] name[self].gosubdag.go2nt.get
variable[go2nt] assign[=] <as... | keyword[def] identifier[_get_gosrcs_upper] ( identifier[self] , identifier[goids] , identifier[max_upper] , identifier[go2parentids] ):
literal[string]
identifier[gosrcs_upper] = identifier[set] ()
identifier[get_nt] = identifier[self] . identifier[gosubdag] . identifier[go2nt] . identifie... | def _get_gosrcs_upper(self, goids, max_upper, go2parentids):
"""Get GO IDs for the upper portion of the GO DAG."""
gosrcs_upper = set()
get_nt = self.gosubdag.go2nt.get
go2nt = {g: get_nt(g) for g in goids}
# Sort by descending order of descendant counts to find potential new hdrgos
go_nt = sort... |
def clear_modified_data(self):
"""
Clears only the modified data
"""
self.__modified_data__ = {}
self.__deleted_fields__ = []
for value in self.__original_data__.values():
try:
value.clear_modified_data()
except AttributeError:
... | def function[clear_modified_data, parameter[self]]:
constant[
Clears only the modified data
]
name[self].__modified_data__ assign[=] dictionary[[], []]
name[self].__deleted_fields__ assign[=] list[[]]
for taget[name[value]] in starred[call[name[self].__original_data__.val... | keyword[def] identifier[clear_modified_data] ( identifier[self] ):
literal[string]
identifier[self] . identifier[__modified_data__] ={}
identifier[self] . identifier[__deleted_fields__] =[]
keyword[for] identifier[value] keyword[in] identifier[self] . identifier[__original_dat... | def clear_modified_data(self):
"""
Clears only the modified data
"""
self.__modified_data__ = {}
self.__deleted_fields__ = []
for value in self.__original_data__.values():
try:
value.clear_modified_data() # depends on [control=['try'], data=[]]
except Attribu... |
def set_servo(self, gpio, pulse_width_us):
"""
Sets a pulse-width on a gpio to repeat every subcycle
(by default every 20ms).
"""
# Make sure we can set the exact pulse_width_us
_pulse_incr_us = _PWM.get_pulse_incr_us()
if pulse_width_us % _pulse_incr_us:
... | def function[set_servo, parameter[self, gpio, pulse_width_us]]:
constant[
Sets a pulse-width on a gpio to repeat every subcycle
(by default every 20ms).
]
variable[_pulse_incr_us] assign[=] call[name[_PWM].get_pulse_incr_us, parameter[]]
if binary_operation[name[pulse_wid... | keyword[def] identifier[set_servo] ( identifier[self] , identifier[gpio] , identifier[pulse_width_us] ):
literal[string]
identifier[_pulse_incr_us] = identifier[_PWM] . identifier[get_pulse_incr_us] ()
keyword[if] identifier[pulse_width_us] % identifier[_pulse_incr_us] :
... | def set_servo(self, gpio, pulse_width_us):
"""
Sets a pulse-width on a gpio to repeat every subcycle
(by default every 20ms).
"""
# Make sure we can set the exact pulse_width_us
_pulse_incr_us = _PWM.get_pulse_incr_us()
if pulse_width_us % _pulse_incr_us:
# No clean divis... |
def FundamentalType(self, _type):
"""Returns the proper ctypes class name for a fundamental type
1) activates generation of appropriate headers for
## int128_t
## c_long_double_t
2) return appropriate name for type
"""
log.debug('HERE in FundamentalType for %s %s... | def function[FundamentalType, parameter[self, _type]]:
constant[Returns the proper ctypes class name for a fundamental type
1) activates generation of appropriate headers for
## int128_t
## c_long_double_t
2) return appropriate name for type
]
call[name[log].debu... | keyword[def] identifier[FundamentalType] ( identifier[self] , identifier[_type] ):
literal[string]
identifier[log] . identifier[debug] ( literal[string] , identifier[_type] , identifier[_type] . identifier[name] )
keyword[if] identifier[_type] . identifier[name] keyword[in] [ literal[str... | def FundamentalType(self, _type):
"""Returns the proper ctypes class name for a fundamental type
1) activates generation of appropriate headers for
## int128_t
## c_long_double_t
2) return appropriate name for type
"""
log.debug('HERE in FundamentalType for %s %s', _type... |
def sign(self, message):
"""Signs a message.
Args:
message: bytes, Message to be signed.
Returns:
string, The signature of the message for the given key.
"""
message = _helpers._to_bytes(message, encoding='utf-8')
return crypto.sign(self._key, me... | def function[sign, parameter[self, message]]:
constant[Signs a message.
Args:
message: bytes, Message to be signed.
Returns:
string, The signature of the message for the given key.
]
variable[message] assign[=] call[name[_helpers]._to_bytes, parameter[na... | keyword[def] identifier[sign] ( identifier[self] , identifier[message] ):
literal[string]
identifier[message] = identifier[_helpers] . identifier[_to_bytes] ( identifier[message] , identifier[encoding] = literal[string] )
keyword[return] identifier[crypto] . identifier[sign] ( identifier[... | def sign(self, message):
"""Signs a message.
Args:
message: bytes, Message to be signed.
Returns:
string, The signature of the message for the given key.
"""
message = _helpers._to_bytes(message, encoding='utf-8')
return crypto.sign(self._key, message, 'sha2... |
def _set_blob_properties(self, sd, digest):
# type: (SyncCopy, blobxfer.models.synccopy.Descriptor, str) -> None
"""Set blob properties (md5, cache control)
:param SyncCopy self: this
:param blobxfer.models.synccopy.Descriptor sd: synccopy descriptor
:param str digest: md5 digest... | def function[_set_blob_properties, parameter[self, sd, digest]]:
constant[Set blob properties (md5, cache control)
:param SyncCopy self: this
:param blobxfer.models.synccopy.Descriptor sd: synccopy descriptor
:param str digest: md5 digest
]
call[name[blobxfer].operations.... | keyword[def] identifier[_set_blob_properties] ( identifier[self] , identifier[sd] , identifier[digest] ):
literal[string]
identifier[blobxfer] . identifier[operations] . identifier[azure] . identifier[blob] . identifier[set_blob_properties] (
identifier[sd] . identifier[dst_entity] , iden... | def _set_blob_properties(self, sd, digest):
# type: (SyncCopy, blobxfer.models.synccopy.Descriptor, str) -> None
'Set blob properties (md5, cache control)\n :param SyncCopy self: this\n :param blobxfer.models.synccopy.Descriptor sd: synccopy descriptor\n :param str digest: md5 digest\n ... |
def annotate(self, *args, **kwargs):
"""
Return a query set in which the returned objects have been annotated
with data aggregated from related fields.
"""
obj = self._clone()
if args:
for arg in args:
if isinstance(arg, Facet):
... | def function[annotate, parameter[self]]:
constant[
Return a query set in which the returned objects have been annotated
with data aggregated from related fields.
]
variable[obj] assign[=] call[name[self]._clone, parameter[]]
if name[args] begin[:]
for tage... | keyword[def] identifier[annotate] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[obj] = identifier[self] . identifier[_clone] ()
keyword[if] identifier[args] :
keyword[for] identifier[arg] keyword[in] identifier[args] :
... | def annotate(self, *args, **kwargs):
"""
Return a query set in which the returned objects have been annotated
with data aggregated from related fields.
"""
obj = self._clone()
if args:
for arg in args:
if isinstance(arg, Facet):
obj._facets.append(... |
def get_referenced_object(prev_obj, obj, dot_separated_name,
desired_type=None):
"""
get objects based on a path
Args:
prev_obj: the object containing obj (req. if obj is a list)
obj: the current object
dot_separated_name: the attribute name "a.b.c.d" start... | def function[get_referenced_object, parameter[prev_obj, obj, dot_separated_name, desired_type]]:
constant[
get objects based on a path
Args:
prev_obj: the object containing obj (req. if obj is a list)
obj: the current object
dot_separated_name: the attribute name "a.b.c.d" start... | keyword[def] identifier[get_referenced_object] ( identifier[prev_obj] , identifier[obj] , identifier[dot_separated_name] ,
identifier[desired_type] = keyword[None] ):
literal[string]
keyword[from] identifier[textx] . identifier[scoping] keyword[import] identifier[Postponed]
keyword[assert] ident... | def get_referenced_object(prev_obj, obj, dot_separated_name, desired_type=None):
"""
get objects based on a path
Args:
prev_obj: the object containing obj (req. if obj is a list)
obj: the current object
dot_separated_name: the attribute name "a.b.c.d" starting from obj
No... |
def logout(self):
"""Log out of the account."""
self._master_token = None
self._auth_token = None
self._email = None
self._android_id = None | def function[logout, parameter[self]]:
constant[Log out of the account.]
name[self]._master_token assign[=] constant[None]
name[self]._auth_token assign[=] constant[None]
name[self]._email assign[=] constant[None]
name[self]._android_id assign[=] constant[None] | keyword[def] identifier[logout] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_master_token] = keyword[None]
identifier[self] . identifier[_auth_token] = keyword[None]
identifier[self] . identifier[_email] = keyword[None]
identifier[self] . identi... | def logout(self):
"""Log out of the account."""
self._master_token = None
self._auth_token = None
self._email = None
self._android_id = None |
def process_exception(self, request, exception):
"""
When we get a CasTicketException, that is probably caused by the ticket timing out.
So logout/login and get the same page again.
"""
if isinstance(exception, CasTicketException):
do_logout(request)
# Th... | def function[process_exception, parameter[self, request, exception]]:
constant[
When we get a CasTicketException, that is probably caused by the ticket timing out.
So logout/login and get the same page again.
]
if call[name[isinstance], parameter[name[exception], name[CasTicketEx... | keyword[def] identifier[process_exception] ( identifier[self] , identifier[request] , identifier[exception] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[exception] , identifier[CasTicketException] ):
identifier[do_logout] ( identifier[request] )
... | def process_exception(self, request, exception):
"""
When we get a CasTicketException, that is probably caused by the ticket timing out.
So logout/login and get the same page again.
"""
if isinstance(exception, CasTicketException):
do_logout(request)
# This assumes that r... |
def clone_to_path(gh_token, folder, sdk_git_id, branch_or_commit=None, *, pr_number=None):
"""Clone the given repo_id to the folder.
If PR number is specified fetch the magic branches
pull/<id>/head or pull/<id>/merge from Github. "merge" is tried first, and fallback to "head".
Beware that pr_number im... | def function[clone_to_path, parameter[gh_token, folder, sdk_git_id, branch_or_commit]]:
constant[Clone the given repo_id to the folder.
If PR number is specified fetch the magic branches
pull/<id>/head or pull/<id>/merge from Github. "merge" is tried first, and fallback to "head".
Beware that pr_nu... | keyword[def] identifier[clone_to_path] ( identifier[gh_token] , identifier[folder] , identifier[sdk_git_id] , identifier[branch_or_commit] = keyword[None] ,*, identifier[pr_number] = keyword[None] ):
literal[string]
identifier[_LOGGER] . identifier[info] ( literal[string] , identifier[sdk_git_id] )
id... | def clone_to_path(gh_token, folder, sdk_git_id, branch_or_commit=None, *, pr_number=None):
"""Clone the given repo_id to the folder.
If PR number is specified fetch the magic branches
pull/<id>/head or pull/<id>/merge from Github. "merge" is tried first, and fallback to "head".
Beware that pr_number im... |
def update(self, other, join='left', overwrite=True, filter_func=None,
errors='ignore'):
"""
Modify Panel in place using non-NA values from other Panel.
May also use object coercible to Panel. Will align on items.
Parameters
----------
other : Panel, or o... | def function[update, parameter[self, other, join, overwrite, filter_func, errors]]:
constant[
Modify Panel in place using non-NA values from other Panel.
May also use object coercible to Panel. Will align on items.
Parameters
----------
other : Panel, or object coercibl... | keyword[def] identifier[update] ( identifier[self] , identifier[other] , identifier[join] = literal[string] , identifier[overwrite] = keyword[True] , identifier[filter_func] = keyword[None] ,
identifier[errors] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance]... | def update(self, other, join='left', overwrite=True, filter_func=None, errors='ignore'):
"""
Modify Panel in place using non-NA values from other Panel.
May also use object coercible to Panel. Will align on items.
Parameters
----------
other : Panel, or object coercible to ... |
def load_configuration(self) -> None:
"""
Read the configuration from a configuration file
"""
config_file = self.default_config_file
if self.config_file:
config_file = self.config_file
self.config = ConfigParser()
self.config.read(config_file) | def function[load_configuration, parameter[self]]:
constant[
Read the configuration from a configuration file
]
variable[config_file] assign[=] name[self].default_config_file
if name[self].config_file begin[:]
variable[config_file] assign[=] name[self].config_file... | keyword[def] identifier[load_configuration] ( identifier[self] )-> keyword[None] :
literal[string]
identifier[config_file] = identifier[self] . identifier[default_config_file]
keyword[if] identifier[self] . identifier[config_file] :
identifier[config_file] = identifier[self]... | def load_configuration(self) -> None:
"""
Read the configuration from a configuration file
"""
config_file = self.default_config_file
if self.config_file:
config_file = self.config_file # depends on [control=['if'], data=[]]
self.config = ConfigParser()
self.config.read(conf... |
def refresh(self, leave_clean=False):
"""Attempt to pull-with-rebase from upstream. This is implemented as fetch-plus-rebase
so that we can distinguish between errors in the fetch stage (likely network errors)
and errors in the rebase stage (conflicts). If leave_clean is true, then in the event
... | def function[refresh, parameter[self, leave_clean]]:
constant[Attempt to pull-with-rebase from upstream. This is implemented as fetch-plus-rebase
so that we can distinguish between errors in the fetch stage (likely network errors)
and errors in the rebase stage (conflicts). If leave_clean is tru... | keyword[def] identifier[refresh] ( identifier[self] , identifier[leave_clean] = keyword[False] ):
literal[string]
identifier[remote] , identifier[merge] = identifier[self] . identifier[_get_upstream] ()
identifier[self] . identifier[_check_call] ([ literal[string] , literal[string] , identifier[remote... | def refresh(self, leave_clean=False):
"""Attempt to pull-with-rebase from upstream. This is implemented as fetch-plus-rebase
so that we can distinguish between errors in the fetch stage (likely network errors)
and errors in the rebase stage (conflicts). If leave_clean is true, then in the event
... |
def _remote_browser_class(env_vars, tags=None):
"""
Returns class, kwargs, and args needed to instantiate the remote browser.
"""
if tags is None:
tags = []
# Interpret the environment variables, raising an exception if they're
# invalid
envs = _required_envs(env_vars)
envs.upda... | def function[_remote_browser_class, parameter[env_vars, tags]]:
constant[
Returns class, kwargs, and args needed to instantiate the remote browser.
]
if compare[name[tags] is constant[None]] begin[:]
variable[tags] assign[=] list[[]]
variable[envs] assign[=] call[name[_re... | keyword[def] identifier[_remote_browser_class] ( identifier[env_vars] , identifier[tags] = keyword[None] ):
literal[string]
keyword[if] identifier[tags] keyword[is] keyword[None] :
identifier[tags] =[]
identifier[envs] = identifier[_required_envs] ( identifier[env_vars] ... | def _remote_browser_class(env_vars, tags=None):
"""
Returns class, kwargs, and args needed to instantiate the remote browser.
"""
if tags is None:
tags = [] # depends on [control=['if'], data=['tags']]
# Interpret the environment variables, raising an exception if they're
# invalid
... |
def _get_command(classes):
"""Associates each command class with command depending on setup.cfg
"""
commands = {}
setup_file = os.path.join(
os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')),
'setup.cfg')
for line in open(setup_file, 'r'):
for cl in classes:
... | def function[_get_command, parameter[classes]]:
constant[Associates each command class with command depending on setup.cfg
]
variable[commands] assign[=] dictionary[[], []]
variable[setup_file] assign[=] call[name[os].path.join, parameter[call[name[os].path.abspath, parameter[call[name[os].p... | keyword[def] identifier[_get_command] ( identifier[classes] ):
literal[string]
identifier[commands] ={}
identifier[setup_file] = identifier[os] . identifier[path] . identifier[join] (
identifier[os] . identifier[path] . identifier[abspath] ( identifier[os] . identifier[path] . identifier[join] ( ... | def _get_command(classes):
"""Associates each command class with command depending on setup.cfg
"""
commands = {}
setup_file = os.path.join(os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')), 'setup.cfg')
for line in open(setup_file, 'r'):
for cl in classes:
if cl ... |
def average_colors(c1, c2):
''' Average the values of two colors together '''
r = int((c1[0] + c2[0])/2)
g = int((c1[1] + c2[1])/2)
b = int((c1[2] + c2[2])/2)
return (r, g, b) | def function[average_colors, parameter[c1, c2]]:
constant[ Average the values of two colors together ]
variable[r] assign[=] call[name[int], parameter[binary_operation[binary_operation[call[name[c1]][constant[0]] + call[name[c2]][constant[0]]] / constant[2]]]]
variable[g] assign[=] call[name[int... | keyword[def] identifier[average_colors] ( identifier[c1] , identifier[c2] ):
literal[string]
identifier[r] = identifier[int] (( identifier[c1] [ literal[int] ]+ identifier[c2] [ literal[int] ])/ literal[int] )
identifier[g] = identifier[int] (( identifier[c1] [ literal[int] ]+ identifier[c2] [ literal... | def average_colors(c1, c2):
""" Average the values of two colors together """
r = int((c1[0] + c2[0]) / 2)
g = int((c1[1] + c2[1]) / 2)
b = int((c1[2] + c2[2]) / 2)
return (r, g, b) |
def update(self, bqm, ignore_info=True):
"""Update one binary quadratic model from another.
Args:
bqm (:class:`.BinaryQuadraticModel`):
The updating binary quadratic model. Any variables in the updating
model are added to the updated model. Values of biases a... | def function[update, parameter[self, bqm, ignore_info]]:
constant[Update one binary quadratic model from another.
Args:
bqm (:class:`.BinaryQuadraticModel`):
The updating binary quadratic model. Any variables in the updating
model are added to the updated mod... | keyword[def] identifier[update] ( identifier[self] , identifier[bqm] , identifier[ignore_info] = keyword[True] ):
literal[string]
identifier[self] . identifier[add_variables_from] ( identifier[bqm] . identifier[linear] , identifier[vartype] = identifier[bqm] . identifier[vartype] )
identif... | def update(self, bqm, ignore_info=True):
"""Update one binary quadratic model from another.
Args:
bqm (:class:`.BinaryQuadraticModel`):
The updating binary quadratic model. Any variables in the updating
model are added to the updated model. Values of biases and t... |
def chebyshev(coefs, time, domain):
"""Evaluate a Chebyshev Polynomial
Args:
coefs (list, np.array): Coefficients defining the polynomial
time (int, float): Time where to evaluate the polynomial
domain (list, tuple): Domain (or time interval) for which the polynomial is defined: [left, ... | def function[chebyshev, parameter[coefs, time, domain]]:
constant[Evaluate a Chebyshev Polynomial
Args:
coefs (list, np.array): Coefficients defining the polynomial
time (int, float): Time where to evaluate the polynomial
domain (list, tuple): Domain (or time interval) for which the... | keyword[def] identifier[chebyshev] ( identifier[coefs] , identifier[time] , identifier[domain] ):
literal[string]
keyword[return] identifier[Chebyshev] ( identifier[coefs] , identifier[domain] = identifier[domain] )( identifier[time] )- literal[int] * identifier[coefs] [ literal[int] ] | def chebyshev(coefs, time, domain):
"""Evaluate a Chebyshev Polynomial
Args:
coefs (list, np.array): Coefficients defining the polynomial
time (int, float): Time where to evaluate the polynomial
domain (list, tuple): Domain (or time interval) for which the polynomial is defined: [left, ... |
def zscore(bars, window=20, stds=1, col='close'):
""" get zscore of price """
std = numpy_rolling_std(bars[col], window)
mean = numpy_rolling_mean(bars[col], window)
return (bars[col] - mean) / (std * stds) | def function[zscore, parameter[bars, window, stds, col]]:
constant[ get zscore of price ]
variable[std] assign[=] call[name[numpy_rolling_std], parameter[call[name[bars]][name[col]], name[window]]]
variable[mean] assign[=] call[name[numpy_rolling_mean], parameter[call[name[bars]][name[col]], nam... | keyword[def] identifier[zscore] ( identifier[bars] , identifier[window] = literal[int] , identifier[stds] = literal[int] , identifier[col] = literal[string] ):
literal[string]
identifier[std] = identifier[numpy_rolling_std] ( identifier[bars] [ identifier[col] ], identifier[window] )
identifier[mean] ... | def zscore(bars, window=20, stds=1, col='close'):
""" get zscore of price """
std = numpy_rolling_std(bars[col], window)
mean = numpy_rolling_mean(bars[col], window)
return (bars[col] - mean) / (std * stds) |
def build_gui(self, container):
"""
This method is called when the plugin is invoked. It builds the
GUI used by the plugin into the widget layout passed as
``container``.
This method could be called several times if the plugin is opened
and closed. The method may be omi... | def function[build_gui, parameter[self, container]]:
constant[
This method is called when the plugin is invoked. It builds the
GUI used by the plugin into the widget layout passed as
``container``.
This method could be called several times if the plugin is opened
and clo... | keyword[def] identifier[build_gui] ( identifier[self] , identifier[container] ):
literal[string]
identifier[top] = identifier[Widgets] . identifier[VBox] ()
identifier[top] . identifier[set_border_width] ( literal[int] )
identifier[vbox] , identifier[sw... | def build_gui(self, container):
"""
This method is called when the plugin is invoked. It builds the
GUI used by the plugin into the widget layout passed as
``container``.
This method could be called several times if the plugin is opened
and closed. The method may be omitted... |
def receive_message(self, message, data):
""" Called when a media message is received. """
if data[MESSAGE_TYPE] == TYPE_MEDIA_STATUS:
self._process_media_status(data)
return True
return False | def function[receive_message, parameter[self, message, data]]:
constant[ Called when a media message is received. ]
if compare[call[name[data]][name[MESSAGE_TYPE]] equal[==] name[TYPE_MEDIA_STATUS]] begin[:]
call[name[self]._process_media_status, parameter[name[data]]]
return[con... | keyword[def] identifier[receive_message] ( identifier[self] , identifier[message] , identifier[data] ):
literal[string]
keyword[if] identifier[data] [ identifier[MESSAGE_TYPE] ]== identifier[TYPE_MEDIA_STATUS] :
identifier[self] . identifier[_process_media_status] ( identifier[data] )... | def receive_message(self, message, data):
""" Called when a media message is received. """
if data[MESSAGE_TYPE] == TYPE_MEDIA_STATUS:
self._process_media_status(data)
return True # depends on [control=['if'], data=[]]
return False |
def getDisplaySize(data_type_oid, type_modifier):
"""
Returns the column display size for the given Vertica type with
consideration of the type modifier.
The display size of a column is the maximum number of characters needed to
display data in character form.
"""
if data_type_oid == Verti... | def function[getDisplaySize, parameter[data_type_oid, type_modifier]]:
constant[
Returns the column display size for the given Vertica type with
consideration of the type modifier.
The display size of a column is the maximum number of characters needed to
display data in character form.
]
... | keyword[def] identifier[getDisplaySize] ( identifier[data_type_oid] , identifier[type_modifier] ):
literal[string]
keyword[if] identifier[data_type_oid] == identifier[VerticaType] . identifier[BOOL] :
keyword[return] literal[int]
keyword[elif] identifier[data_type_oid] == identifier... | def getDisplaySize(data_type_oid, type_modifier):
"""
Returns the column display size for the given Vertica type with
consideration of the type modifier.
The display size of a column is the maximum number of characters needed to
display data in character form.
"""
if data_type_oid == Vertic... |
def make_mecard(name, reading=None, email=None, phone=None, videophone=None,
memo=None, nickname=None, birthday=None, url=None, pobox=None,
roomno=None, houseno=None, city=None, prefecture=None,
zipcode=None, country=None):
"""\
Returns a QR Code which encodes a `... | def function[make_mecard, parameter[name, reading, email, phone, videophone, memo, nickname, birthday, url, pobox, roomno, houseno, city, prefecture, zipcode, country]]:
constant[ Returns a QR Code which encodes a `MeCard <https://en.wikipedia.org/wiki/MeCard>`_
:param str name: Name. If it contains a c... | keyword[def] identifier[make_mecard] ( identifier[name] , identifier[reading] = keyword[None] , identifier[email] = keyword[None] , identifier[phone] = keyword[None] , identifier[videophone] = keyword[None] ,
identifier[memo] = keyword[None] , identifier[nickname] = keyword[None] , identifier[birthday] = keyword[Non... | def make_mecard(name, reading=None, email=None, phone=None, videophone=None, memo=None, nickname=None, birthday=None, url=None, pobox=None, roomno=None, houseno=None, city=None, prefecture=None, zipcode=None, country=None):
""" Returns a QR Code which encodes a `MeCard <https://en.wikipedia.org/wiki/MeCard>`_
... |
def get_scaled_cutout_basic(self, x1, y1, x2, y2, scale_x, scale_y,
method='basic'):
"""Extract a region of the image defined by corners (x1, y1) and
(x2, y2) and scale it by scale factors (scale_x, scale_y).
`method` describes the method of interpolation used, w... | def function[get_scaled_cutout_basic, parameter[self, x1, y1, x2, y2, scale_x, scale_y, method]]:
constant[Extract a region of the image defined by corners (x1, y1) and
(x2, y2) and scale it by scale factors (scale_x, scale_y).
`method` describes the method of interpolation used, where the
... | keyword[def] identifier[get_scaled_cutout_basic] ( identifier[self] , identifier[x1] , identifier[y1] , identifier[x2] , identifier[y2] , identifier[scale_x] , identifier[scale_y] ,
identifier[method] = literal[string] ):
literal[string]
identifier[new_wd] = identifier[int] ( identifier[round] ( ... | def get_scaled_cutout_basic(self, x1, y1, x2, y2, scale_x, scale_y, method='basic'):
"""Extract a region of the image defined by corners (x1, y1) and
(x2, y2) and scale it by scale factors (scale_x, scale_y).
`method` describes the method of interpolation used, where the
default "basic" is ... |
def delete(filething):
""" delete(filething)
Arguments:
filething (filething)
Raises:
mutagen.MutagenError
Remove tags from a file.
"""
t = OggFLAC(filething)
filething.fileobj.seek(0)
t.delete(filething) | def function[delete, parameter[filething]]:
constant[ delete(filething)
Arguments:
filething (filething)
Raises:
mutagen.MutagenError
Remove tags from a file.
]
variable[t] assign[=] call[name[OggFLAC], parameter[name[filething]]]
call[name[filething].fileobj.se... | keyword[def] identifier[delete] ( identifier[filething] ):
literal[string]
identifier[t] = identifier[OggFLAC] ( identifier[filething] )
identifier[filething] . identifier[fileobj] . identifier[seek] ( literal[int] )
identifier[t] . identifier[delete] ( identifier[filething] ) | def delete(filething):
""" delete(filething)
Arguments:
filething (filething)
Raises:
mutagen.MutagenError
Remove tags from a file.
"""
t = OggFLAC(filething)
filething.fileobj.seek(0)
t.delete(filething) |
def main():
"""The main function of the script"""
desc = 'Benchmark the files generated by generate.py'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument(
'--src',
dest='src_dir',
default='generated',
help='The directory containing the sources to benc... | def function[main, parameter[]]:
constant[The main function of the script]
variable[desc] assign[=] constant[Benchmark the files generated by generate.py]
variable[parser] assign[=] call[name[argparse].ArgumentParser, parameter[]]
call[name[parser].add_argument, parameter[constant[--src]... | keyword[def] identifier[main] ():
literal[string]
identifier[desc] = literal[string]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] ( identifier[description] = identifier[desc] )
identifier[parser] . identifier[add_argument] (
literal[string] ,
identifier[dest] ... | def main():
"""The main function of the script"""
desc = 'Benchmark the files generated by generate.py'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('--src', dest='src_dir', default='generated', help='The directory containing the sources to benchmark')
parser.add_argument('... |
def fromInputs(self, received):
"""
Convert some random strings received from a browser into structured
data, using a list of parameters.
@param received: a dict of lists of strings, i.e. the canonical Python
form of web form post.
@rtype: L{Deferred}
@retur... | def function[fromInputs, parameter[self, received]]:
constant[
Convert some random strings received from a browser into structured
data, using a list of parameters.
@param received: a dict of lists of strings, i.e. the canonical Python
form of web form post.
@rtype:... | keyword[def] identifier[fromInputs] ( identifier[self] , identifier[received] ):
literal[string]
identifier[results] =[]
keyword[for] identifier[parameter] keyword[in] identifier[self] . identifier[parameters] :
identifier[name] = identifier[parameter] . identifier[name] . ... | def fromInputs(self, received):
"""
Convert some random strings received from a browser into structured
data, using a list of parameters.
@param received: a dict of lists of strings, i.e. the canonical Python
form of web form post.
@rtype: L{Deferred}
@return: A... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.