code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def retrieve_candidate_values(self, service, operation, param):
"""Retrieve server side completions.
:type service: str
:param service: The service name, e.g. 'ec2', 'iam'.
:type operation: str
:param operation: The operation name, in the casing
used by the CLI (wor... | def function[retrieve_candidate_values, parameter[self, service, operation, param]]:
constant[Retrieve server side completions.
:type service: str
:param service: The service name, e.g. 'ec2', 'iam'.
:type operation: str
:param operation: The operation name, in the casing
... | keyword[def] identifier[retrieve_candidate_values] ( identifier[self] , identifier[service] , identifier[operation] , identifier[param] ):
literal[string]
keyword[if] identifier[service] keyword[not] keyword[in] identifier[self] . identifier[_describer_creato... | def retrieve_candidate_values(self, service, operation, param):
"""Retrieve server side completions.
:type service: str
:param service: The service name, e.g. 'ec2', 'iam'.
:type operation: str
:param operation: The operation name, in the casing
used by the CLI (words s... |
def _initialize_serialization(driver_id, worker=global_worker):
"""Initialize the serialization library.
This defines a custom serializer for object IDs and also tells ray to
serialize several exception classes that we define for error handling.
"""
serialization_context = pyarrow.default_serializa... | def function[_initialize_serialization, parameter[driver_id, worker]]:
constant[Initialize the serialization library.
This defines a custom serializer for object IDs and also tells ray to
serialize several exception classes that we define for error handling.
]
variable[serialization_context... | keyword[def] identifier[_initialize_serialization] ( identifier[driver_id] , identifier[worker] = identifier[global_worker] ):
literal[string]
identifier[serialization_context] = identifier[pyarrow] . identifier[default_serialization_context] ()
identifier[serialization_context] . identifier... | def _initialize_serialization(driver_id, worker=global_worker):
"""Initialize the serialization library.
This defines a custom serializer for object IDs and also tells ray to
serialize several exception classes that we define for error handling.
"""
serialization_context = pyarrow.default_serializa... |
def content_type(transformers, default=None):
"""Returns a different transformer depending on the content type passed in.
If none match and no default is given no transformation takes place.
should pass in a dict with the following format:
{'[content-type]': transformation_action,
... | def function[content_type, parameter[transformers, default]]:
constant[Returns a different transformer depending on the content type passed in.
If none match and no default is given no transformation takes place.
should pass in a dict with the following format:
{'[content-type]': tra... | keyword[def] identifier[content_type] ( identifier[transformers] , identifier[default] = keyword[None] ):
literal[string]
identifier[transformers] ={ identifier[content_type] : identifier[auto_kwargs] ( identifier[transformer] ) keyword[if] identifier[transformer] keyword[else] identifier[transformer]
... | def content_type(transformers, default=None):
"""Returns a different transformer depending on the content type passed in.
If none match and no default is given no transformation takes place.
should pass in a dict with the following format:
{'[content-type]': transformation_action,
... |
def download_data(self, configuration, output_file):
"""
Выполняет указанный в конфигурации запрос и отдает файл на скачивание
:param configuration: Конфгурация запроса
:param output_file: Место, куда надо скачать файл
:return:
"""
params = configuration
r... | def function[download_data, parameter[self, configuration, output_file]]:
constant[
Выполняет указанный в конфигурации запрос и отдает файл на скачивание
:param configuration: Конфгурация запроса
:param output_file: Место, куда надо скачать файл
:return:
]
variabl... | keyword[def] identifier[download_data] ( identifier[self] , identifier[configuration] , identifier[output_file] ):
literal[string]
identifier[params] = identifier[configuration]
identifier[response] = identifier[self] . identifier[__app] . identifier[native_api_call] ( literal[string] , l... | def download_data(self, configuration, output_file):
"""
Выполняет указанный в конфигурации запрос и отдает файл на скачивание
:param configuration: Конфгурация запроса
:param output_file: Место, куда надо скачать файл
:return:
"""
params = configuration
response = se... |
def qos_queue_scheduler_strict_priority_dwrr_traffic_class5(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos")
queue = ET.SubElement(qos, "queue")
scheduler = ET.SubElement... | def function[qos_queue_scheduler_strict_priority_dwrr_traffic_class5, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[qos] assign[=] call[name[ET].SubElement, parameter[name[config], constant[qos]]]
... | keyword[def] identifier[qos_queue_scheduler_strict_priority_dwrr_traffic_class5] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[qos] = identifier[ET] . identifier[SubElement] ( identifier... | def qos_queue_scheduler_strict_priority_dwrr_traffic_class5(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
qos = ET.SubElement(config, 'qos', xmlns='urn:brocade.com:mgmt:brocade-qos')
queue = ET.SubElement(qos, 'queue')
scheduler = ET.SubElement(queue, 'scheduler')... |
def load_remote(url, **kwargs):
"""
Load a mesh at a remote URL into a local trimesh object.
This must be called explicitly rather than automatically
from trimesh.load to ensure users don't accidentally make
network requests.
Parameters
------------
url : string
URL containing me... | def function[load_remote, parameter[url]]:
constant[
Load a mesh at a remote URL into a local trimesh object.
This must be called explicitly rather than automatically
from trimesh.load to ensure users don't accidentally make
network requests.
Parameters
------------
url : string
... | keyword[def] identifier[load_remote] ( identifier[url] ,** identifier[kwargs] ):
literal[string]
keyword[import] identifier[requests]
identifier[response] = identifier[requests] . identifier[get] ( identifier[url] )
identifier[file_obj] = identifier[util] . identifier[wrap_as_st... | def load_remote(url, **kwargs):
"""
Load a mesh at a remote URL into a local trimesh object.
This must be called explicitly rather than automatically
from trimesh.load to ensure users don't accidentally make
network requests.
Parameters
------------
url : string
URL containing me... |
def _power_mismatch_dc(self, buses, generators, B, Pbusinj, base_mva):
""" Returns the power mismatch constraint (B*Va + Pg = Pd).
"""
nb, ng = len(buses), len(generators)
# Negative bus-generator incidence matrix.
gen_bus = array([g.bus._i for g in generators])
neg_Cg = ... | def function[_power_mismatch_dc, parameter[self, buses, generators, B, Pbusinj, base_mva]]:
constant[ Returns the power mismatch constraint (B*Va + Pg = Pd).
]
<ast.Tuple object at 0x7da1b25194b0> assign[=] tuple[[<ast.Call object at 0x7da1b2518dc0>, <ast.Call object at 0x7da1b2519630>]]
... | keyword[def] identifier[_power_mismatch_dc] ( identifier[self] , identifier[buses] , identifier[generators] , identifier[B] , identifier[Pbusinj] , identifier[base_mva] ):
literal[string]
identifier[nb] , identifier[ng] = identifier[len] ( identifier[buses] ), identifier[len] ( identifier[generator... | def _power_mismatch_dc(self, buses, generators, B, Pbusinj, base_mva):
""" Returns the power mismatch constraint (B*Va + Pg = Pd).
"""
(nb, ng) = (len(buses), len(generators))
# Negative bus-generator incidence matrix.
gen_bus = array([g.bus._i for g in generators])
neg_Cg = csr_matrix((-one... |
def merge_base_attrs(attrs):
"""
:param dict attrs: If one of the attrs is named "base\_", assume that attribute is an instance of SimpleModel mapped on a Postgresql composite type, and that the base\_ instance is of a superclass of this class. Expand the attributes of the base\_ type and assign to clas... | def function[merge_base_attrs, parameter[attrs]]:
constant[
:param dict attrs: If one of the attrs is named "base\_", assume that attribute is an instance of SimpleModel mapped on a Postgresql composite type, and that the base\_ instance is of a superclass of this class. Expand the attributes of the bas... | keyword[def] identifier[merge_base_attrs] ( identifier[attrs] ):
literal[string]
identifier[base] = identifier[attrs] . identifier[pop] ( literal[string] , keyword[None] )
keyword[if] identifier[base] :
identifier[d_out] ( literal[string] . identifier[format] ( identifier[bas... | def merge_base_attrs(attrs):
"""
:param dict attrs: If one of the attrs is named "base\\_", assume that attribute is an instance of SimpleModel mapped on a Postgresql composite type, and that the base\\_ instance is of a superclass of this class. Expand the attributes of the base\\_ type and assign to class... |
async def getLaunchSpecs(self, *args, **kwargs):
"""
Get All Launch Specifications for WorkerType
This method returns a preview of all possible launch specifications
that this worker type definition could submit to EC2. It is used to
test worker types, nothing more
**T... | <ast.AsyncFunctionDef object at 0x7da18f722fb0> | keyword[async] keyword[def] identifier[getLaunchSpecs] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[return] keyword[await] identifier[self] . identifier[_makeApiCall] ( identifier[self] . identifier[funcinfo] [ literal[string] ],* identifier[args] ,**... | async def getLaunchSpecs(self, *args, **kwargs):
"""
Get All Launch Specifications for WorkerType
This method returns a preview of all possible launch specifications
that this worker type definition could submit to EC2. It is used to
test worker types, nothing more
**This ... |
def animate(self, **kwargs):
""" Animates the surface.
This function only animates the triangulated surface. There will be no other elements, such as control points
grid or bounding box.
Keyword arguments:
* ``colormap``: applies colormap to the surface
Colormaps a... | def function[animate, parameter[self]]:
constant[ Animates the surface.
This function only animates the triangulated surface. There will be no other elements, such as control points
grid or bounding box.
Keyword arguments:
* ``colormap``: applies colormap to the surface
... | keyword[def] identifier[animate] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[super] ( identifier[VisSurface] , identifier[self] ). identifier[render] (** identifier[kwargs] )
identifier[surf_cmaps] = identifier[kwargs] . identifier[get] ( lite... | def animate(self, **kwargs):
""" Animates the surface.
This function only animates the triangulated surface. There will be no other elements, such as control points
grid or bounding box.
Keyword arguments:
* ``colormap``: applies colormap to the surface
Colormaps are a... |
def fetch_defense_data(self):
"""Lazy initialization of data necessary to execute defenses."""
if self.defenses_data_initialized:
return
logging.info('Fetching defense data from datastore')
# init data from datastore
self.submissions.init_from_datastore()
self.dataset_batches.init_from_dat... | def function[fetch_defense_data, parameter[self]]:
constant[Lazy initialization of data necessary to execute defenses.]
if name[self].defenses_data_initialized begin[:]
return[None]
call[name[logging].info, parameter[constant[Fetching defense data from datastore]]]
call[name[self... | keyword[def] identifier[fetch_defense_data] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[defenses_data_initialized] :
keyword[return]
identifier[logging] . identifier[info] ( literal[string] )
identifier[self] . identifier[submissions] . identifier... | def fetch_defense_data(self):
"""Lazy initialization of data necessary to execute defenses."""
if self.defenses_data_initialized:
return # depends on [control=['if'], data=[]]
logging.info('Fetching defense data from datastore')
# init data from datastore
self.submissions.init_from_datastor... |
def binary_search(a, k):
"""
Do a binary search in an array of objects ordered by '.key'
returns the largest index for which: a[i].key <= k
like c++: a.upperbound(k)--
"""
first, last = 0, len(a)
while first < last:
mid = (first + last) >> 1
if k < a[mid].key:
... | def function[binary_search, parameter[a, k]]:
constant[
Do a binary search in an array of objects ordered by '.key'
returns the largest index for which: a[i].key <= k
like c++: a.upperbound(k)--
]
<ast.Tuple object at 0x7da20e9b0700> assign[=] tuple[[<ast.Constant object at 0x7da20e9b... | keyword[def] identifier[binary_search] ( identifier[a] , identifier[k] ):
literal[string]
identifier[first] , identifier[last] = literal[int] , identifier[len] ( identifier[a] )
keyword[while] identifier[first] < identifier[last] :
identifier[mid] =( identifier[first] + identifier[last] ... | def binary_search(a, k):
"""
Do a binary search in an array of objects ordered by '.key'
returns the largest index for which: a[i].key <= k
like c++: a.upperbound(k)--
"""
(first, last) = (0, len(a))
while first < last:
mid = first + last >> 1
if k < a[mid].key:
... |
def unpack_4to8(data):
""" Promote 2-bit unisgned data into 8-bit unsigned data.
Args:
data: Numpy array with dtype == uint8
Notes:
# The process is this:
# ABCDEFGH [Bits of one 4+4-bit value]
# 00000000ABCDEFGH [astype(uint16)]
# 0000ABCDEFGH0000 [<< 4]
# ... | def function[unpack_4to8, parameter[data]]:
constant[ Promote 2-bit unisgned data into 8-bit unsigned data.
Args:
data: Numpy array with dtype == uint8
Notes:
# The process is this:
# ABCDEFGH [Bits of one 4+4-bit value]
# 00000000ABCDEFGH [astype(uint16)]
# 000... | keyword[def] identifier[unpack_4to8] ( identifier[data] ):
literal[string]
identifier[tmpdata] = identifier[data] . identifier[astype] ( identifier[np] . identifier[int16] )
identifier[tmpdata] =( identifier[tmpdata] |( identifier[tmpdata] << literal[int] ))& literal[int]
identifier[updata... | def unpack_4to8(data):
""" Promote 2-bit unisgned data into 8-bit unsigned data.
Args:
data: Numpy array with dtype == uint8
Notes:
# The process is this:
# ABCDEFGH [Bits of one 4+4-bit value]
# 00000000ABCDEFGH [astype(uint16)]
# 0000ABCDEFGH0000 [<< 4]
# ... |
def hw(self, hw):
""" Hardware operations """
if hw.upper() == "INIT":
self._raw(HW_INIT)
elif hw.upper() == "SELECT":
self._raw(HW_SELECT)
elif hw.upper() == "RESET":
self._raw(HW_RESET)
else: # DEFAULT: DOES NOTHING
pass | def function[hw, parameter[self, hw]]:
constant[ Hardware operations ]
if compare[call[name[hw].upper, parameter[]] equal[==] constant[INIT]] begin[:]
call[name[self]._raw, parameter[name[HW_INIT]]] | keyword[def] identifier[hw] ( identifier[self] , identifier[hw] ):
literal[string]
keyword[if] identifier[hw] . identifier[upper] ()== literal[string] :
identifier[self] . identifier[_raw] ( identifier[HW_INIT] )
keyword[elif] identifier[hw] . identifier[upper] ()== literal[... | def hw(self, hw):
""" Hardware operations """
if hw.upper() == 'INIT':
self._raw(HW_INIT) # depends on [control=['if'], data=[]]
elif hw.upper() == 'SELECT':
self._raw(HW_SELECT) # depends on [control=['if'], data=[]]
elif hw.upper() == 'RESET':
self._raw(HW_RESET) # depends o... |
def run_script(scriptfile):
'''run a script file'''
try:
f = open(scriptfile, mode='r')
except Exception:
return
mpstate.console.writeln("Running script %s" % scriptfile)
for line in f:
line = line.strip()
if line == "" or line.startswith('#'):
continue
... | def function[run_script, parameter[scriptfile]]:
constant[run a script file]
<ast.Try object at 0x7da2041db7c0>
call[name[mpstate].console.writeln, parameter[binary_operation[constant[Running script %s] <ast.Mod object at 0x7da2590d6920> name[scriptfile]]]]
for taget[name[line]] in starred[n... | keyword[def] identifier[run_script] ( identifier[scriptfile] ):
literal[string]
keyword[try] :
identifier[f] = identifier[open] ( identifier[scriptfile] , identifier[mode] = literal[string] )
keyword[except] identifier[Exception] :
keyword[return]
identifier[mpstate] . identif... | def run_script(scriptfile):
"""run a script file"""
try:
f = open(scriptfile, mode='r') # depends on [control=['try'], data=[]]
except Exception:
return # depends on [control=['except'], data=[]]
mpstate.console.writeln('Running script %s' % scriptfile)
for line in f:
line ... |
def select_distinct_field(col, field_or_fields, filters=None):
"""Select distinct value or combination of values of
single or multiple fields.
:params fields: str or list of str.
:return data: list of list.
**中文文档**
选择多列中出现过的所有可能的排列组合。
"""
fields = _preprocess_field_or_fields(field_or... | def function[select_distinct_field, parameter[col, field_or_fields, filters]]:
constant[Select distinct value or combination of values of
single or multiple fields.
:params fields: str or list of str.
:return data: list of list.
**中文文档**
选择多列中出现过的所有可能的排列组合。
]
variable[fields] ... | keyword[def] identifier[select_distinct_field] ( identifier[col] , identifier[field_or_fields] , identifier[filters] = keyword[None] ):
literal[string]
identifier[fields] = identifier[_preprocess_field_or_fields] ( identifier[field_or_fields] )
keyword[if] identifier[filters] keyword[is] keyword[N... | def select_distinct_field(col, field_or_fields, filters=None):
"""Select distinct value or combination of values of
single or multiple fields.
:params fields: str or list of str.
:return data: list of list.
**中文文档**
选择多列中出现过的所有可能的排列组合。
"""
fields = _preprocess_field_or_fields(field_or... |
def patch_wave_header(body):
"""Patch header to the given wave body.
:param body: the wave content body, it should be bytearray.
"""
length = len(body)
padded = length + length % 2
total = WAVE_HEADER_LENGTH + padded
header = copy.copy(WAVE_HEADER)
# fill the total length position
... | def function[patch_wave_header, parameter[body]]:
constant[Patch header to the given wave body.
:param body: the wave content body, it should be bytearray.
]
variable[length] assign[=] call[name[len], parameter[name[body]]]
variable[padded] assign[=] binary_operation[name[length] + bina... | keyword[def] identifier[patch_wave_header] ( identifier[body] ):
literal[string]
identifier[length] = identifier[len] ( identifier[body] )
identifier[padded] = identifier[length] + identifier[length] % literal[int]
identifier[total] = identifier[WAVE_HEADER_LENGTH] + identifier[padded]
i... | def patch_wave_header(body):
"""Patch header to the given wave body.
:param body: the wave content body, it should be bytearray.
"""
length = len(body)
padded = length + length % 2
total = WAVE_HEADER_LENGTH + padded
header = copy.copy(WAVE_HEADER)
# fill the total length position
h... |
def XYZ_to_xyY(cobj, *args, **kwargs):
"""
Convert from XYZ to xyY.
"""
xyz_sum = cobj.xyz_x + cobj.xyz_y + cobj.xyz_z
# avoid division by zero
if xyz_sum == 0.0:
xyy_x = 0.0
xyy_y = 0.0
else:
xyy_x = cobj.xyz_x / xyz_sum
xyy_y = cobj.xyz_y / xyz_sum
xyy_Y... | def function[XYZ_to_xyY, parameter[cobj]]:
constant[
Convert from XYZ to xyY.
]
variable[xyz_sum] assign[=] binary_operation[binary_operation[name[cobj].xyz_x + name[cobj].xyz_y] + name[cobj].xyz_z]
if compare[name[xyz_sum] equal[==] constant[0.0]] begin[:]
variable[xyy_x... | keyword[def] identifier[XYZ_to_xyY] ( identifier[cobj] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[xyz_sum] = identifier[cobj] . identifier[xyz_x] + identifier[cobj] . identifier[xyz_y] + identifier[cobj] . identifier[xyz_z]
keyword[if] identifier[xyz_sum] == litera... | def XYZ_to_xyY(cobj, *args, **kwargs):
"""
Convert from XYZ to xyY.
"""
xyz_sum = cobj.xyz_x + cobj.xyz_y + cobj.xyz_z
# avoid division by zero
if xyz_sum == 0.0:
xyy_x = 0.0
xyy_y = 0.0 # depends on [control=['if'], data=[]]
else:
xyy_x = cobj.xyz_x / xyz_sum
... |
def check_duplicate_options(self, section1, section2, raise_error=False):
"""
Check for duplicate options in two sections, section1 and section2.
Will return a list of the duplicate options.
Parameters
----------
section1 : string
The name of the first sectio... | def function[check_duplicate_options, parameter[self, section1, section2, raise_error]]:
constant[
Check for duplicate options in two sections, section1 and section2.
Will return a list of the duplicate options.
Parameters
----------
section1 : string
The nam... | keyword[def] identifier[check_duplicate_options] ( identifier[self] , identifier[section1] , identifier[section2] , identifier[raise_error] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[has_section] ( identifier[section1] ):
keywo... | def check_duplicate_options(self, section1, section2, raise_error=False):
"""
Check for duplicate options in two sections, section1 and section2.
Will return a list of the duplicate options.
Parameters
----------
section1 : string
The name of the first section to... |
def resolve_reference(ref):
"""
Return the object pointed to by ``ref``.
If ``ref`` is not a string or does not contain ``:``, it is returned as is.
References must be in the form <modulename>:<varname> where <modulename> is the fully
qualified module name and varname is the path to the variable in... | def function[resolve_reference, parameter[ref]]:
constant[
Return the object pointed to by ``ref``.
If ``ref`` is not a string or does not contain ``:``, it is returned as is.
References must be in the form <modulename>:<varname> where <modulename> is the fully
qualified module name and varname... | keyword[def] identifier[resolve_reference] ( identifier[ref] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[ref] , identifier[str] ) keyword[or] literal[string] keyword[not] keyword[in] identifier[ref] :
keyword[return] identifier[ref]
identifier[modu... | def resolve_reference(ref):
"""
Return the object pointed to by ``ref``.
If ``ref`` is not a string or does not contain ``:``, it is returned as is.
References must be in the form <modulename>:<varname> where <modulename> is the fully
qualified module name and varname is the path to the variable in... |
def filter_only_significant(word):
"""Gets a word which removes insignificant letters at the end of the given
word::
>>> pick_significant(u'넥슨(코리아)')
넥슨
>>> pick_significant(u'메이플스토리...')
메이플스토리
"""
if not word:
return word
# Unwrap a complete parenthesis.
if word.start... | def function[filter_only_significant, parameter[word]]:
constant[Gets a word which removes insignificant letters at the end of the given
word::
>>> pick_significant(u'넥슨(코리아)')
넥슨
>>> pick_significant(u'메이플스토리...')
메이플스토리
]
if <ast.UnaryOp object at 0x7da1afe8b9d0> begin[:]
... | keyword[def] identifier[filter_only_significant] ( identifier[word] ):
literal[string]
keyword[if] keyword[not] identifier[word] :
keyword[return] identifier[word]
keyword[if] identifier[word] . identifier[startswith] ( literal[string] ) keyword[and] identifier[word] . identifi... | def filter_only_significant(word):
"""Gets a word which removes insignificant letters at the end of the given
word::
>>> pick_significant(u'넥슨(코리아)')
넥슨
>>> pick_significant(u'메이플스토리...')
메이플스토리
"""
if not word:
return word # depends on [control=['if'], data=[]]
# Unwrap a... |
def load_options():
"""Read various proselintrc files, allowing user overrides."""
possible_defaults = (
'/etc/proselintrc',
os.path.join(proselint_path, '.proselintrc'),
)
options = {}
has_overrides = False
for filename in possible_defaults:
try:
options = j... | def function[load_options, parameter[]]:
constant[Read various proselintrc files, allowing user overrides.]
variable[possible_defaults] assign[=] tuple[[<ast.Constant object at 0x7da1b065ceb0>, <ast.Call object at 0x7da1b065ce80>]]
variable[options] assign[=] dictionary[[], []]
variable[... | keyword[def] identifier[load_options] ():
literal[string]
identifier[possible_defaults] =(
literal[string] ,
identifier[os] . identifier[path] . identifier[join] ( identifier[proselint_path] , literal[string] ),
)
identifier[options] ={}
identifier[has_overrides] = keyword[False]
... | def load_options():
"""Read various proselintrc files, allowing user overrides."""
possible_defaults = ('/etc/proselintrc', os.path.join(proselint_path, '.proselintrc'))
options = {}
has_overrides = False
for filename in possible_defaults:
try:
options = json.load(open(filename))... |
def get_kerberos_subs(netid):
"""
Return a restclients.models.uwnetid.Subscription objects
on the given uwnetid
"""
subs = get_netid_subscriptions(netid, Subscription.SUBS_CODE_KERBEROS)
if subs is not None:
for subscription in subs:
if subscription.subscription_code == Subsc... | def function[get_kerberos_subs, parameter[netid]]:
constant[
Return a restclients.models.uwnetid.Subscription objects
on the given uwnetid
]
variable[subs] assign[=] call[name[get_netid_subscriptions], parameter[name[netid], name[Subscription].SUBS_CODE_KERBEROS]]
if compare[name[sub... | keyword[def] identifier[get_kerberos_subs] ( identifier[netid] ):
literal[string]
identifier[subs] = identifier[get_netid_subscriptions] ( identifier[netid] , identifier[Subscription] . identifier[SUBS_CODE_KERBEROS] )
keyword[if] identifier[subs] keyword[is] keyword[not] keyword[None] :
... | def get_kerberos_subs(netid):
"""
Return a restclients.models.uwnetid.Subscription objects
on the given uwnetid
"""
subs = get_netid_subscriptions(netid, Subscription.SUBS_CODE_KERBEROS)
if subs is not None:
for subscription in subs:
if subscription.subscription_code == Subsc... |
def get_bad_rows_and_cols(df, validation_names, type_col_names,
value_col_names, verbose=False):
"""
Input: validated DataFrame, all validation names, names of the type columns,
names of the value columns, verbose (True or False).
Output: list of rows with bad values, list of c... | def function[get_bad_rows_and_cols, parameter[df, validation_names, type_col_names, value_col_names, verbose]]:
constant[
Input: validated DataFrame, all validation names, names of the type columns,
names of the value columns, verbose (True or False).
Output: list of rows with bad values, list of co... | keyword[def] identifier[get_bad_rows_and_cols] ( identifier[df] , identifier[validation_names] , identifier[type_col_names] ,
identifier[value_col_names] , identifier[verbose] = keyword[False] ):
literal[string]
identifier[df] [ literal[string] ]= identifier[list] ( identifier[range] ( identifier[len] ( i... | def get_bad_rows_and_cols(df, validation_names, type_col_names, value_col_names, verbose=False):
"""
Input: validated DataFrame, all validation names, names of the type columns,
names of the value columns, verbose (True or False).
Output: list of rows with bad values, list of columns with bad values,
... |
def range(self, date1, date2):
"""
Generate business days between two dates, taking holidays into
consideration.
Args:
date1 (date, datetime or str): Date start of interval.
date2 (date, datetime or str): Date end of interval, not included.
Note... | def function[range, parameter[self, date1, date2]]:
constant[
Generate business days between two dates, taking holidays into
consideration.
Args:
date1 (date, datetime or str): Date start of interval.
date2 (date, datetime or str): Date end of interval, not inclu... | keyword[def] identifier[range] ( identifier[self] , identifier[date1] , identifier[date2] ):
literal[string]
identifier[date1] = identifier[self] . identifier[adjust] ( identifier[parsefun] ( identifier[date1] ), identifier[FOLLOWING] )
identifier[date2] = identifier[parsefun] ( identif... | def range(self, date1, date2):
"""
Generate business days between two dates, taking holidays into
consideration.
Args:
date1 (date, datetime or str): Date start of interval.
date2 (date, datetime or str): Date end of interval, not included.
Note:
... |
def get_factory_by_class(self, klass):
"""
Returns a custom factory for class. By default it will return the class itself.
:param klass: Class type
:type klass: type
:return: Class factory
:rtype: callable
"""
for check, factory in self._factories.items()... | def function[get_factory_by_class, parameter[self, klass]]:
constant[
Returns a custom factory for class. By default it will return the class itself.
:param klass: Class type
:type klass: type
:return: Class factory
:rtype: callable
]
for taget[tuple[[<as... | keyword[def] identifier[get_factory_by_class] ( identifier[self] , identifier[klass] ):
literal[string]
keyword[for] identifier[check] , identifier[factory] keyword[in] identifier[self] . identifier[_factories] . identifier[items] ():
keyword[if] identifier[klass] keyword[is] ide... | def get_factory_by_class(self, klass):
"""
Returns a custom factory for class. By default it will return the class itself.
:param klass: Class type
:type klass: type
:return: Class factory
:rtype: callable
"""
for (check, factory) in self._factories.items():
... |
def process_m2m_through_save(self, obj, created=False, **kwargs):
"""Process M2M post save for custom through model."""
# We are only interested in signals that establish relations.
if not created:
return
self._process_m2m_through(obj, 'post_add') | def function[process_m2m_through_save, parameter[self, obj, created]]:
constant[Process M2M post save for custom through model.]
if <ast.UnaryOp object at 0x7da1b1993fd0> begin[:]
return[None]
call[name[self]._process_m2m_through, parameter[name[obj], constant[post_add]]] | keyword[def] identifier[process_m2m_through_save] ( identifier[self] , identifier[obj] , identifier[created] = keyword[False] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[created] :
keyword[return]
identifier[self] . identifier[_pr... | def process_m2m_through_save(self, obj, created=False, **kwargs):
"""Process M2M post save for custom through model."""
# We are only interested in signals that establish relations.
if not created:
return # depends on [control=['if'], data=[]]
self._process_m2m_through(obj, 'post_add') |
def every_match(self, callback, **kwargs):
"""Invoke callback every time a matching message is received.
The callback will be invoked directly inside process_message so that
you can guarantee that it has been called by the time process_message
has returned.
The callback can be ... | def function[every_match, parameter[self, callback]]:
constant[Invoke callback every time a matching message is received.
The callback will be invoked directly inside process_message so that
you can guarantee that it has been called by the time process_message
has returned.
The... | keyword[def] identifier[every_match] ( identifier[self] , identifier[callback] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[len] ( identifier[kwargs] )== literal[int] :
keyword[raise] identifier[ArgumentError] ( literal[string] )
identifier[spec] = iden... | def every_match(self, callback, **kwargs):
"""Invoke callback every time a matching message is received.
The callback will be invoked directly inside process_message so that
you can guarantee that it has been called by the time process_message
has returned.
The callback can be remo... |
def signalStrength(self):
""" Checks the modem's cellular network signal strength
:raise CommandError: if an error occurs
:return: The network signal strength as an integer between 0 and 99, or -1 if it is unknown
:rtype: int
"""
csq = self.CSQ_REGEX.mat... | def function[signalStrength, parameter[self]]:
constant[ Checks the modem's cellular network signal strength
:raise CommandError: if an error occurs
:return: The network signal strength as an integer between 0 and 99, or -1 if it is unknown
:rtype: int
]
... | keyword[def] identifier[signalStrength] ( identifier[self] ):
literal[string]
identifier[csq] = identifier[self] . identifier[CSQ_REGEX] . identifier[match] ( identifier[self] . identifier[write] ( literal[string] )[ literal[int] ])
keyword[if] identifier[csq] :
identifier[ss... | def signalStrength(self):
""" Checks the modem's cellular network signal strength
:raise CommandError: if an error occurs
:return: The network signal strength as an integer between 0 and 99, or -1 if it is unknown
:rtype: int
"""
csq = self.CSQ_REGEX.match(self.... |
def cluster_application(self, application_id):
"""
An application resource contains information about a particular
application that was submitted to a cluster.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`y... | def function[cluster_application, parameter[self, application_id]]:
constant[
An application resource contains information about a particular
application that was submitted to a cluster.
:param str application_id: The application id
:returns: API response object with JSON data
... | keyword[def] identifier[cluster_application] ( identifier[self] , identifier[application_id] ):
literal[string]
identifier[path] = literal[string] . identifier[format] ( identifier[appid] = identifier[application_id] )
keyword[return] identifier[self] . identifier[request] ( identifier[p... | def cluster_application(self, application_id):
"""
An application resource contains information about a particular
application that was submitted to a cluster.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_... |
def open(self, number=0):
"""
Open the FaderPort and register a callback so we can send and
receive MIDI messages.
:param number: 0 unless you've got more than one FaderPort attached.
In which case 0 is the first, 1 is the second etc
I only h... | def function[open, parameter[self, number]]:
constant[
Open the FaderPort and register a callback so we can send and
receive MIDI messages.
:param number: 0 unless you've got more than one FaderPort attached.
In which case 0 is the first, 1 is the second etc
... | keyword[def] identifier[open] ( identifier[self] , identifier[number] = literal[int] ):
literal[string]
identifier[self] . identifier[inport] = identifier[mido] . identifier[open_input] ( identifier[find_faderport_input_name] ( identifier[number] ))
identifier[self] . identifier[outport] =... | def open(self, number=0):
"""
Open the FaderPort and register a callback so we can send and
receive MIDI messages.
:param number: 0 unless you've got more than one FaderPort attached.
In which case 0 is the first, 1 is the second etc
I only have ... |
def build(cls: Type[T], data: Generic) -> T:
"""Build objects from dictionaries, recursively."""
fields = fields_dict(cls)
kwargs: Dict[str, Any] = {}
for key, value in data.items():
if key in fields:
if isinstance(value, Mapping):
t = fiel... | def function[build, parameter[cls, data]]:
constant[Build objects from dictionaries, recursively.]
variable[fields] assign[=] call[name[fields_dict], parameter[name[cls]]]
<ast.AnnAssign object at 0x7da18f812890>
for taget[tuple[[<ast.Name object at 0x7da18f810f40>, <ast.Name object at 0x7da... | keyword[def] identifier[build] ( identifier[cls] : identifier[Type] [ identifier[T] ], identifier[data] : identifier[Generic] )-> identifier[T] :
literal[string]
identifier[fields] = identifier[fields_dict] ( identifier[cls] )
identifier[kwargs] : identifier[Dict] [ identifier[str] , ident... | def build(cls: Type[T], data: Generic) -> T:
"""Build objects from dictionaries, recursively."""
fields = fields_dict(cls)
kwargs: Dict[str, Any] = {}
for (key, value) in data.items():
if key in fields:
if isinstance(value, Mapping):
t = fields[key].type
... |
def _field_controller_generator(self):
"""
Generates the methods called by the injected controller
"""
# Local variable, to avoid messing with "self"
stored_instance = self._ipopo_instance
def get_value(self, name):
# pylint: disable=W0613
"""
... | def function[_field_controller_generator, parameter[self]]:
constant[
Generates the methods called by the injected controller
]
variable[stored_instance] assign[=] name[self]._ipopo_instance
def function[get_value, parameter[self, name]]:
constant[
Ret... | keyword[def] identifier[_field_controller_generator] ( identifier[self] ):
literal[string]
identifier[stored_instance] = identifier[self] . identifier[_ipopo_instance]
keyword[def] identifier[get_value] ( identifier[self] , identifier[name] ):
literal[stri... | def _field_controller_generator(self):
"""
Generates the methods called by the injected controller
"""
# Local variable, to avoid messing with "self"
stored_instance = self._ipopo_instance
def get_value(self, name):
# pylint: disable=W0613
'\n Retrieves the co... |
def addfield(self, pkt, s, val):
"""Add an internal value to a string"""
if self.adjust(pkt, self.length_of) == 2:
return s + struct.pack(self.fmt[0] + "H", val)
elif self.adjust(pkt, self.length_of) == 8:
return s + struct.pack(self.fmt[0] + "Q", val)
else:
... | def function[addfield, parameter[self, pkt, s, val]]:
constant[Add an internal value to a string]
if compare[call[name[self].adjust, parameter[name[pkt], name[self].length_of]] equal[==] constant[2]] begin[:]
return[binary_operation[name[s] + call[name[struct].pack, parameter[binary_operation[ca... | keyword[def] identifier[addfield] ( identifier[self] , identifier[pkt] , identifier[s] , identifier[val] ):
literal[string]
keyword[if] identifier[self] . identifier[adjust] ( identifier[pkt] , identifier[self] . identifier[length_of] )== literal[int] :
keyword[return] identifier[s] ... | def addfield(self, pkt, s, val):
"""Add an internal value to a string"""
if self.adjust(pkt, self.length_of) == 2:
return s + struct.pack(self.fmt[0] + 'H', val) # depends on [control=['if'], data=[]]
elif self.adjust(pkt, self.length_of) == 8:
return s + struct.pack(self.fmt[0] + 'Q', val)... |
def _read_config(correlation_id, path, parameters):
"""
Reads configuration from a file, parameterize it with given values and returns a new ConfigParams object.
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param path: a path to configuration... | def function[_read_config, parameter[correlation_id, path, parameters]]:
constant[
Reads configuration from a file, parameterize it with given values and returns a new ConfigParams object.
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param pa... | keyword[def] identifier[_read_config] ( identifier[correlation_id] , identifier[path] , identifier[parameters] ):
literal[string]
identifier[value] = identifier[YamlConfigReader] ( identifier[path] ). identifier[_read_object] ( identifier[correlation_id] , identifier[parameters] )
keyword[... | def _read_config(correlation_id, path, parameters):
"""
Reads configuration from a file, parameterize it with given values and returns a new ConfigParams object.
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param path: a path to configuration fil... |
def add_and_shuffle(self, peer):
"""Push a new peer into the heap and shuffle the heap"""
self.push_peer(peer)
r = random.randint(0, self.size() - 1)
self.swap_order(peer.index, r) | def function[add_and_shuffle, parameter[self, peer]]:
constant[Push a new peer into the heap and shuffle the heap]
call[name[self].push_peer, parameter[name[peer]]]
variable[r] assign[=] call[name[random].randint, parameter[constant[0], binary_operation[call[name[self].size, parameter[]] - const... | keyword[def] identifier[add_and_shuffle] ( identifier[self] , identifier[peer] ):
literal[string]
identifier[self] . identifier[push_peer] ( identifier[peer] )
identifier[r] = identifier[random] . identifier[randint] ( literal[int] , identifier[self] . identifier[size] ()- literal[int] )
... | def add_and_shuffle(self, peer):
"""Push a new peer into the heap and shuffle the heap"""
self.push_peer(peer)
r = random.randint(0, self.size() - 1)
self.swap_order(peer.index, r) |
def printAggregateJobStats(self, properties, childNumber):
"""Prints a job's ID, log file, remaining tries, and other properties."""
for job in self.jobsToReport:
lf = lambda x: "%s:%s" % (x, str(x in properties))
print("\t".join(("JOB:%s" % job,
"LOG... | def function[printAggregateJobStats, parameter[self, properties, childNumber]]:
constant[Prints a job's ID, log file, remaining tries, and other properties.]
for taget[name[job]] in starred[name[self].jobsToReport] begin[:]
variable[lf] assign[=] <ast.Lambda object at 0x7da18fe90af0>
... | keyword[def] identifier[printAggregateJobStats] ( identifier[self] , identifier[properties] , identifier[childNumber] ):
literal[string]
keyword[for] identifier[job] keyword[in] identifier[self] . identifier[jobsToReport] :
identifier[lf] = keyword[lambda] identifier[x] : literal[s... | def printAggregateJobStats(self, properties, childNumber):
"""Prints a job's ID, log file, remaining tries, and other properties."""
for job in self.jobsToReport:
lf = lambda x: '%s:%s' % (x, str(x in properties))
print('\t'.join(('JOB:%s' % job, 'LOG_FILE:%s' % job.logJobStoreFileID, 'TRYS_REMA... |
def fit(self, X, y=None, **kwargs):
"""
Fits the corpus to the appropriate tag map.
Text documents must be tokenized & tagged before passing to fit.
Parameters
----------
X : list or generator
Should be provided as a list of documents or a generator
... | def function[fit, parameter[self, X, y]]:
constant[
Fits the corpus to the appropriate tag map.
Text documents must be tokenized & tagged before passing to fit.
Parameters
----------
X : list or generator
Should be provided as a list of documents or a generat... | keyword[def] identifier[fit] ( identifier[self] , identifier[X] , identifier[y] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[self] . identifier[tagset] == literal[string] :
identifier[self] . identifier[pos_tag_counts_] = identifier[self] .... | def fit(self, X, y=None, **kwargs):
"""
Fits the corpus to the appropriate tag map.
Text documents must be tokenized & tagged before passing to fit.
Parameters
----------
X : list or generator
Should be provided as a list of documents or a generator
t... |
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
now, nxt = tee(iterable)
next(nxt, None)
return izip(now, nxt) | def function[pairwise, parameter[iterable]]:
constant[s -> (s0,s1), (s1,s2), (s2, s3), ...]
<ast.Tuple object at 0x7da1b05f0880> assign[=] call[name[tee], parameter[name[iterable]]]
call[name[next], parameter[name[nxt], constant[None]]]
return[call[name[izip], parameter[name[now], name[nxt]]... | keyword[def] identifier[pairwise] ( identifier[iterable] ):
literal[string]
identifier[now] , identifier[nxt] = identifier[tee] ( identifier[iterable] )
identifier[next] ( identifier[nxt] , keyword[None] )
keyword[return] identifier[izip] ( identifier[now] , identifier[nxt] ) | def pairwise(iterable):
"""s -> (s0,s1), (s1,s2), (s2, s3), ..."""
(now, nxt) = tee(iterable)
next(nxt, None)
return izip(now, nxt) |
def weld_str_upper(array):
"""Convert values to uppercase.
Parameters
----------
array : numpy.ndarray or WeldObject
Input data.
Returns
-------
WeldObject
Representation of this computation.
"""
obj_id, weld_obj = create_weld_object(array)
weld_template = """... | def function[weld_str_upper, parameter[array]]:
constant[Convert values to uppercase.
Parameters
----------
array : numpy.ndarray or WeldObject
Input data.
Returns
-------
WeldObject
Representation of this computation.
]
<ast.Tuple object at 0x7da1b0a71510>... | keyword[def] identifier[weld_str_upper] ( identifier[array] ):
literal[string]
identifier[obj_id] , identifier[weld_obj] = identifier[create_weld_object] ( identifier[array] )
identifier[weld_template] = literal[string]
identifier[weld_obj] . identifier[weld_code] = identifier[weld_template] .... | def weld_str_upper(array):
"""Convert values to uppercase.
Parameters
----------
array : numpy.ndarray or WeldObject
Input data.
Returns
-------
WeldObject
Representation of this computation.
"""
(obj_id, weld_obj) = create_weld_object(array)
weld_template = 'm... |
def delimit_words(string: str) -> Generator[str, None, None]:
"""
Delimit a string at word boundaries.
::
>>> import uqbar.strings
>>> list(uqbar.strings.delimit_words("i want to believe"))
['i', 'want', 'to', 'believe']
::
>>> list(uqbar.strings.delimit_words("S3Buck... | def function[delimit_words, parameter[string]]:
constant[
Delimit a string at word boundaries.
::
>>> import uqbar.strings
>>> list(uqbar.strings.delimit_words("i want to believe"))
['i', 'want', 'to', 'believe']
::
>>> list(uqbar.strings.delimit_words("S3Bucket")... | keyword[def] identifier[delimit_words] ( identifier[string] : identifier[str] )-> identifier[Generator] [ identifier[str] , keyword[None] , keyword[None] ]:
literal[string]
identifier[wordlike_characters] =( literal[string] , literal[string] , literal[string] )
identifier[current_word] = literal[... | def delimit_words(string: str) -> Generator[str, None, None]:
"""
Delimit a string at word boundaries.
::
>>> import uqbar.strings
>>> list(uqbar.strings.delimit_words("i want to believe"))
['i', 'want', 'to', 'believe']
::
>>> list(uqbar.strings.delimit_words("S3Buck... |
def generate_password_hash(password, digestmod='sha256', salt_length=8):
""" Hash a password with given method and salt length. """
salt = ''.join(random.sample(SALT_CHARS, salt_length))
signature = create_signature(salt, password, digestmod=digestmod)
return '$'.join((digestmod, salt, signature)) | def function[generate_password_hash, parameter[password, digestmod, salt_length]]:
constant[ Hash a password with given method and salt length. ]
variable[salt] assign[=] call[constant[].join, parameter[call[name[random].sample, parameter[name[SALT_CHARS], name[salt_length]]]]]
variable[signatur... | keyword[def] identifier[generate_password_hash] ( identifier[password] , identifier[digestmod] = literal[string] , identifier[salt_length] = literal[int] ):
literal[string]
identifier[salt] = literal[string] . identifier[join] ( identifier[random] . identifier[sample] ( identifier[SALT_CHARS] , identifier... | def generate_password_hash(password, digestmod='sha256', salt_length=8):
""" Hash a password with given method and salt length. """
salt = ''.join(random.sample(SALT_CHARS, salt_length))
signature = create_signature(salt, password, digestmod=digestmod)
return '$'.join((digestmod, salt, signature)) |
def visit_copy_command(element, compiler, **kw):
"""
Returns the actual sql query for the CopyCommand class.
"""
qs = """COPY {table}{columns} FROM :data_location
WITH CREDENTIALS AS :credentials
{format}
{parameters}"""
parameters = []
bindparams = [
sa.bindparam... | def function[visit_copy_command, parameter[element, compiler]]:
constant[
Returns the actual sql query for the CopyCommand class.
]
variable[qs] assign[=] constant[COPY {table}{columns} FROM :data_location
WITH CREDENTIALS AS :credentials
{format}
{parameters}]
va... | keyword[def] identifier[visit_copy_command] ( identifier[element] , identifier[compiler] ,** identifier[kw] ):
literal[string]
identifier[qs] = literal[string]
identifier[parameters] =[]
identifier[bindparams] =[
identifier[sa] . identifier[bindparam] (
literal[string] ,
identifie... | def visit_copy_command(element, compiler, **kw):
"""
Returns the actual sql query for the CopyCommand class.
"""
qs = 'COPY {table}{columns} FROM :data_location\n WITH CREDENTIALS AS :credentials\n {format}\n {parameters}'
parameters = []
bindparams = [sa.bindparam('data_loc... |
def _process_with_joblib(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray):
"""
Process calling of .calculate_gap() method using the joblib backend
"""
if Parallel is None:
raise EnvironmentError('joblib is not installed; cannot use joblib as t... | def function[_process_with_joblib, parameter[self, X, n_refs, cluster_array]]:
constant[
Process calling of .calculate_gap() method using the joblib backend
]
if compare[name[Parallel] is constant[None]] begin[:]
<ast.Raise object at 0x7da1b1034640>
with call[name[Paralle... | keyword[def] identifier[_process_with_joblib] ( identifier[self] , identifier[X] : identifier[Union] [ identifier[pd] . identifier[DataFrame] , identifier[np] . identifier[ndarray] ], identifier[n_refs] : identifier[int] , identifier[cluster_array] : identifier[np] . identifier[ndarray] ):
literal[string]
... | def _process_with_joblib(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray):
"""
Process calling of .calculate_gap() method using the joblib backend
"""
if Parallel is None:
raise EnvironmentError('joblib is not installed; cannot use joblib as the parallel ... |
def show_firmware_version_output_show_firmware_version_node_info_firmware_version_info_secondary_version(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_firmware_version = ET.Element("show_firmware_version")
config = show_firmware_version
ou... | def function[show_firmware_version_output_show_firmware_version_node_info_firmware_version_info_secondary_version, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[show_firmware_version] assign[=] cal... | keyword[def] identifier[show_firmware_version_output_show_firmware_version_node_info_firmware_version_info_secondary_version] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[show_firmware_... | def show_firmware_version_output_show_firmware_version_node_info_firmware_version_info_secondary_version(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
show_firmware_version = ET.Element('show_firmware_version')
config = show_firmware_version
output = ET.SubElement... |
def add_constraints(self):
"""
Set the base constraints of the relation query
"""
if self._constraints:
super(MorphOneOrMany, self).add_constraints()
self._query.where(self._morph_type, self._morph_name) | def function[add_constraints, parameter[self]]:
constant[
Set the base constraints of the relation query
]
if name[self]._constraints begin[:]
call[call[name[super], parameter[name[MorphOneOrMany], name[self]]].add_constraints, parameter[]]
call[name[self]... | keyword[def] identifier[add_constraints] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_constraints] :
identifier[super] ( identifier[MorphOneOrMany] , identifier[self] ). identifier[add_constraints] ()
identifier[self] . identifier[_que... | def add_constraints(self):
"""
Set the base constraints of the relation query
"""
if self._constraints:
super(MorphOneOrMany, self).add_constraints()
self._query.where(self._morph_type, self._morph_name) # depends on [control=['if'], data=[]] |
def print_env_info(key, out=sys.stderr):
"""If given environment key is defined, print it out."""
value = os.getenv(key)
if value is not None:
print(key, "=", repr(value), file=out) | def function[print_env_info, parameter[key, out]]:
constant[If given environment key is defined, print it out.]
variable[value] assign[=] call[name[os].getenv, parameter[name[key]]]
if compare[name[value] is_not constant[None]] begin[:]
call[name[print], parameter[name[key], cons... | keyword[def] identifier[print_env_info] ( identifier[key] , identifier[out] = identifier[sys] . identifier[stderr] ):
literal[string]
identifier[value] = identifier[os] . identifier[getenv] ( identifier[key] )
keyword[if] identifier[value] keyword[is] keyword[not] keyword[None] :
identifi... | def print_env_info(key, out=sys.stderr):
"""If given environment key is defined, print it out."""
value = os.getenv(key)
if value is not None:
print(key, '=', repr(value), file=out) # depends on [control=['if'], data=['value']] |
def set_vim_style(theme):
"""Add style and compatibility with vim notebook extension"""
vim_jupyter_nbext = os.path.join(jupyter_nbext, 'vim_binding')
if not os.path.isdir(vim_jupyter_nbext):
os.makedirs(vim_jupyter_nbext)
vim_less = '@import "styles{}";\n'.format(''.join([os.sep, theme]))
... | def function[set_vim_style, parameter[theme]]:
constant[Add style and compatibility with vim notebook extension]
variable[vim_jupyter_nbext] assign[=] call[name[os].path.join, parameter[name[jupyter_nbext], constant[vim_binding]]]
if <ast.UnaryOp object at 0x7da20c6c57e0> begin[:]
... | keyword[def] identifier[set_vim_style] ( identifier[theme] ):
literal[string]
identifier[vim_jupyter_nbext] = identifier[os] . identifier[path] . identifier[join] ( identifier[jupyter_nbext] , literal[string] )
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isdir] ( identi... | def set_vim_style(theme):
"""Add style and compatibility with vim notebook extension"""
vim_jupyter_nbext = os.path.join(jupyter_nbext, 'vim_binding')
if not os.path.isdir(vim_jupyter_nbext):
os.makedirs(vim_jupyter_nbext) # depends on [control=['if'], data=[]]
vim_less = '@import "styles{}";\n... |
def round(self, decimals=0, *args, **kwargs):
"""Round each element in the DataFrame.
Args:
decimals: The number of decimals to round to.
Returns:
A new DataFrame.
"""
return self.__constructor__(
query_compiler=self._query_compile... | def function[round, parameter[self, decimals]]:
constant[Round each element in the DataFrame.
Args:
decimals: The number of decimals to round to.
Returns:
A new DataFrame.
]
return[call[name[self].__constructor__, parameter[]]] | keyword[def] identifier[round] ( identifier[self] , identifier[decimals] = literal[int] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[__constructor__] (
identifier[query_compiler] = identifier[self] . identifier[_query_compi... | def round(self, decimals=0, *args, **kwargs):
"""Round each element in the DataFrame.
Args:
decimals: The number of decimals to round to.
Returns:
A new DataFrame.
"""
return self.__constructor__(query_compiler=self._query_compiler.round(decimals=decimals, **kw... |
def queue_declare(self, queue, durable, exclusive, auto_delete,
warn_if_exists=False, arguments=None):
"""Declare a named queue."""
return self.channel.queue_declare(queue=queue,
durable=durable,
exclusive=e... | def function[queue_declare, parameter[self, queue, durable, exclusive, auto_delete, warn_if_exists, arguments]]:
constant[Declare a named queue.]
return[call[name[self].channel.queue_declare, parameter[]]] | keyword[def] identifier[queue_declare] ( identifier[self] , identifier[queue] , identifier[durable] , identifier[exclusive] , identifier[auto_delete] ,
identifier[warn_if_exists] = keyword[False] , identifier[arguments] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identi... | def queue_declare(self, queue, durable, exclusive, auto_delete, warn_if_exists=False, arguments=None):
"""Declare a named queue."""
return self.channel.queue_declare(queue=queue, durable=durable, exclusive=exclusive, auto_delete=auto_delete, arguments=arguments) |
def delete_queue(name, region, opts=None, user=None):
'''
Deletes a queue in the region.
name
Name of the SQS queue to deletes
region
Name of the region to delete the queue from
opts : None
Any additional options to add to the command line
user : None
Run hg as... | def function[delete_queue, parameter[name, region, opts, user]]:
constant[
Deletes a queue in the region.
name
Name of the SQS queue to deletes
region
Name of the region to delete the queue from
opts : None
Any additional options to add to the command line
user : N... | keyword[def] identifier[delete_queue] ( identifier[name] , identifier[region] , identifier[opts] = keyword[None] , identifier[user] = keyword[None] ):
literal[string]
identifier[queues] = identifier[list_queues] ( identifier[region] , identifier[opts] , identifier[user] )
identifier[url_map] = identif... | def delete_queue(name, region, opts=None, user=None):
"""
Deletes a queue in the region.
name
Name of the SQS queue to deletes
region
Name of the region to delete the queue from
opts : None
Any additional options to add to the command line
user : None
Run hg as... |
def generate_proxy(
prefix, base_url='', verify_ssl=True, middleware=None,
append_middleware=None, cert=None, timeout=None):
"""Generate a ProxyClass based view that uses the passed base_url."""
middleware = list(middleware or HttpProxy.proxy_middleware)
middleware += list(append_middleware ... | def function[generate_proxy, parameter[prefix, base_url, verify_ssl, middleware, append_middleware, cert, timeout]]:
constant[Generate a ProxyClass based view that uses the passed base_url.]
variable[middleware] assign[=] call[name[list], parameter[<ast.BoolOp object at 0x7da18f58cbe0>]]
<ast.AugAss... | keyword[def] identifier[generate_proxy] (
identifier[prefix] , identifier[base_url] = literal[string] , identifier[verify_ssl] = keyword[True] , identifier[middleware] = keyword[None] ,
identifier[append_middleware] = keyword[None] , identifier[cert] = keyword[None] , identifier[timeout] = keyword[None] ):
lit... | def generate_proxy(prefix, base_url='', verify_ssl=True, middleware=None, append_middleware=None, cert=None, timeout=None):
"""Generate a ProxyClass based view that uses the passed base_url."""
middleware = list(middleware or HttpProxy.proxy_middleware)
middleware += list(append_middleware or [])
return... |
def main():
"""Connect to a McDevice"""
args = setup_parser().parse_args()
host = getattr(args, "host")
port = getattr(args, "port")
ipv4 = socket.gethostbyname(host)
interval = getattr(args, "interval")
receiver = McDevice(ipv4, udp_port=port, mc_interval=interval)
receiver.handle_stat... | def function[main, parameter[]]:
constant[Connect to a McDevice]
variable[args] assign[=] call[call[name[setup_parser], parameter[]].parse_args, parameter[]]
variable[host] assign[=] call[name[getattr], parameter[name[args], constant[host]]]
variable[port] assign[=] call[name[getattr], p... | keyword[def] identifier[main] ():
literal[string]
identifier[args] = identifier[setup_parser] (). identifier[parse_args] ()
identifier[host] = identifier[getattr] ( identifier[args] , literal[string] )
identifier[port] = identifier[getattr] ( identifier[args] , literal[string] )
identifier[i... | def main():
"""Connect to a McDevice"""
args = setup_parser().parse_args()
host = getattr(args, 'host')
port = getattr(args, 'port')
ipv4 = socket.gethostbyname(host)
interval = getattr(args, 'interval')
receiver = McDevice(ipv4, udp_port=port, mc_interval=interval)
receiver.handle_statu... |
def delete(self, workflow_id, email_id):
"""
Removes an individual Automation workflow email.
:param workflow_id: The unique id for the Automation workflow.
:type workflow_id: :py:class:`str`
:param email_id: The unique id for the Automation workflow email.
:type email_i... | def function[delete, parameter[self, workflow_id, email_id]]:
constant[
Removes an individual Automation workflow email.
:param workflow_id: The unique id for the Automation workflow.
:type workflow_id: :py:class:`str`
:param email_id: The unique id for the Automation workflow e... | keyword[def] identifier[delete] ( identifier[self] , identifier[workflow_id] , identifier[email_id] ):
literal[string]
identifier[self] . identifier[workflow_id] = identifier[workflow_id]
identifier[self] . identifier[email_id] = identifier[email_id]
keyword[return] identifier... | def delete(self, workflow_id, email_id):
"""
Removes an individual Automation workflow email.
:param workflow_id: The unique id for the Automation workflow.
:type workflow_id: :py:class:`str`
:param email_id: The unique id for the Automation workflow email.
:type email_id: :... |
def register_event(self):
"""
注册事件
"""
event_bus = Environment.get_instance().event_bus
event_bus.prepend_listener(EVENT.PRE_BEFORE_TRADING, self._pre_before_trading)
event_bus.prepend_listener(EVENT.POST_SETTLEMENT, self._post_settlement) | def function[register_event, parameter[self]]:
constant[
注册事件
]
variable[event_bus] assign[=] call[name[Environment].get_instance, parameter[]].event_bus
call[name[event_bus].prepend_listener, parameter[name[EVENT].PRE_BEFORE_TRADING, name[self]._pre_before_trading]]
call... | keyword[def] identifier[register_event] ( identifier[self] ):
literal[string]
identifier[event_bus] = identifier[Environment] . identifier[get_instance] (). identifier[event_bus]
identifier[event_bus] . identifier[prepend_listener] ( identifier[EVENT] . identifier[PRE_BEFORE_TRADING] , id... | def register_event(self):
"""
注册事件
"""
event_bus = Environment.get_instance().event_bus
event_bus.prepend_listener(EVENT.PRE_BEFORE_TRADING, self._pre_before_trading)
event_bus.prepend_listener(EVENT.POST_SETTLEMENT, self._post_settlement) |
def handle_get_token(self, req):
"""Handles the various `request for token and service end point(s)` calls.
There are various formats to support the various auth servers in the
past. Examples::
GET <auth-prefix>/v1/<act>/auth
X-Auth-User: <act>:<usr> or X-Storage-U... | def function[handle_get_token, parameter[self, req]]:
constant[Handles the various `request for token and service end point(s)` calls.
There are various formats to support the various auth servers in the
past. Examples::
GET <auth-prefix>/v1/<act>/auth
X-Auth-User: <... | keyword[def] identifier[handle_get_token] ( identifier[self] , identifier[req] ):
literal[string]
keyword[try] :
identifier[pathsegs] = identifier[split_path] ( identifier[req] . identifier[path_info] , identifier[minsegs] = literal[int] , identifier[maxsegs] = literal[int] ,
... | def handle_get_token(self, req):
"""Handles the various `request for token and service end point(s)` calls.
There are various formats to support the various auth servers in the
past. Examples::
GET <auth-prefix>/v1/<act>/auth
X-Auth-User: <act>:<usr> or X-Storage-User:... |
def aseg_on_mri(mri_spec,
aseg_spec,
alpha_mri=1.0,
alpha_seg=1.0,
num_rows=2,
num_cols=6,
rescale_method='global',
aseg_cmap='freesurfer',
sub_cortical=False,
annot=None,
... | def function[aseg_on_mri, parameter[mri_spec, aseg_spec, alpha_mri, alpha_seg, num_rows, num_cols, rescale_method, aseg_cmap, sub_cortical, annot, padding, bkground_thresh, output_path, figsize]]:
constant[Produces a collage of various slices from different orientations in the given 3D image]
<ast.Tuple... | keyword[def] identifier[aseg_on_mri] ( identifier[mri_spec] ,
identifier[aseg_spec] ,
identifier[alpha_mri] = literal[int] ,
identifier[alpha_seg] = literal[int] ,
identifier[num_rows] = literal[int] ,
identifier[num_cols] = literal[int] ,
identifier[rescale_method] = literal[string] ,
identifier[aseg_cmap] = ... | def aseg_on_mri(mri_spec, aseg_spec, alpha_mri=1.0, alpha_seg=1.0, num_rows=2, num_cols=6, rescale_method='global', aseg_cmap='freesurfer', sub_cortical=False, annot=None, padding=5, bkground_thresh=0.05, output_path=None, figsize=None, **kwargs):
"""Produces a collage of various slices from different orientations ... |
def kv(d):
"""Equivalent to dict.items().
Usage::
>>> for key, node in DictTree.kv(d):
>>> print(key, DictTree.getattr(node, "population"))
MD 200000
VA 100000
"""
return ((key, value) for key, value in iteritems(d) ... | def function[kv, parameter[d]]:
constant[Equivalent to dict.items().
Usage::
>>> for key, node in DictTree.kv(d):
>>> print(key, DictTree.getattr(node, "population"))
MD 200000
VA 100000
]
return[<ast.GeneratorExp object... | keyword[def] identifier[kv] ( identifier[d] ):
literal[string]
keyword[return] (( identifier[key] , identifier[value] ) keyword[for] identifier[key] , identifier[value] keyword[in] identifier[iteritems] ( identifier[d] ) keyword[if] identifier[key] != identifier[_meta] ) | def kv(d):
"""Equivalent to dict.items().
Usage::
>>> for key, node in DictTree.kv(d):
>>> print(key, DictTree.getattr(node, "population"))
MD 200000
VA 100000
"""
return ((key, value) for (key, value) in iteritems(d) if key... |
def _set_affected_target_count_in_runtracker(self):
"""Sets the realized target count in the run tracker's daemon stats object."""
target_count = len(self.build_graph)
self.run_tracker.pantsd_stats.set_affected_targets_size(target_count)
return target_count | def function[_set_affected_target_count_in_runtracker, parameter[self]]:
constant[Sets the realized target count in the run tracker's daemon stats object.]
variable[target_count] assign[=] call[name[len], parameter[name[self].build_graph]]
call[name[self].run_tracker.pantsd_stats.set_affected_ta... | keyword[def] identifier[_set_affected_target_count_in_runtracker] ( identifier[self] ):
literal[string]
identifier[target_count] = identifier[len] ( identifier[self] . identifier[build_graph] )
identifier[self] . identifier[run_tracker] . identifier[pantsd_stats] . identifier[set_affected_targets_size... | def _set_affected_target_count_in_runtracker(self):
"""Sets the realized target count in the run tracker's daemon stats object."""
target_count = len(self.build_graph)
self.run_tracker.pantsd_stats.set_affected_targets_size(target_count)
return target_count |
def dest(self):
"""Create link destination details."""
if hasattr(self, "parent") and self.parent is None:
raise ValueError("orphaned object: parent is None")
if self.parent.parent.isClosed or self.parent.parent.isEncrypted:
raise ValueError("operation illegal for closed ... | def function[dest, parameter[self]]:
constant[Create link destination details.]
if <ast.BoolOp object at 0x7da18c4cd9c0> begin[:]
<ast.Raise object at 0x7da1b26acc10>
if <ast.BoolOp object at 0x7da1b26ac6a0> begin[:]
<ast.Raise object at 0x7da1b26ad3c0>
variable[doc] assi... | keyword[def] identifier[dest] ( identifier[self] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ) keyword[and] identifier[self] . identifier[parent] keyword[is] keyword[None] :
keyword[raise] identifier[ValueError] ( literal[string] )
... | def dest(self):
"""Create link destination details."""
if hasattr(self, 'parent') and self.parent is None:
raise ValueError('orphaned object: parent is None') # depends on [control=['if'], data=[]]
if self.parent.parent.isClosed or self.parent.parent.isEncrypted:
raise ValueError('operation... |
def get_qr(self, filename=None):
"""Get pairing QR code from client"""
if "Click to reload QR code" in self.driver.page_source:
self.reload_qr()
qr = self.driver.find_element_by_css_selector(self._SELECTORS['qrCode'])
if filename is None:
fd, fn_png = tempfile.mks... | def function[get_qr, parameter[self, filename]]:
constant[Get pairing QR code from client]
if compare[constant[Click to reload QR code] in name[self].driver.page_source] begin[:]
call[name[self].reload_qr, parameter[]]
variable[qr] assign[=] call[name[self].driver.find_element_by... | keyword[def] identifier[get_qr] ( identifier[self] , identifier[filename] = keyword[None] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[self] . identifier[driver] . identifier[page_source] :
identifier[self] . identifier[reload_qr] ()
identifier[qr] ... | def get_qr(self, filename=None):
"""Get pairing QR code from client"""
if 'Click to reload QR code' in self.driver.page_source:
self.reload_qr() # depends on [control=['if'], data=[]]
qr = self.driver.find_element_by_css_selector(self._SELECTORS['qrCode'])
if filename is None:
(fd, fn_p... |
def add_aliases(self_or_cls, **kwargs):
"""
Conveniently add new aliases as keyword arguments. For instance
you can add a new alias with add_aliases(short='Longer string')
"""
self_or_cls.aliases.update({v:k for k,v in kwargs.items()}) | def function[add_aliases, parameter[self_or_cls]]:
constant[
Conveniently add new aliases as keyword arguments. For instance
you can add a new alias with add_aliases(short='Longer string')
]
call[name[self_or_cls].aliases.update, parameter[<ast.DictComp object at 0x7da18dc06a40>]... | keyword[def] identifier[add_aliases] ( identifier[self_or_cls] ,** identifier[kwargs] ):
literal[string]
identifier[self_or_cls] . identifier[aliases] . identifier[update] ({ identifier[v] : identifier[k] keyword[for] identifier[k] , identifier[v] keyword[in] identifier[kwargs] . identifier[ite... | def add_aliases(self_or_cls, **kwargs):
"""
Conveniently add new aliases as keyword arguments. For instance
you can add a new alias with add_aliases(short='Longer string')
"""
self_or_cls.aliases.update({v: k for (k, v) in kwargs.items()}) |
def std(self, ddof=1, *args, **kwargs):
"""
Compute standard deviation of groups, excluding missing values.
Parameters
----------
ddof : integer, default 1
Degrees of freedom.
"""
nv.validate_resampler_func('std', args, kwargs)
return self._do... | def function[std, parameter[self, ddof]]:
constant[
Compute standard deviation of groups, excluding missing values.
Parameters
----------
ddof : integer, default 1
Degrees of freedom.
]
call[name[nv].validate_resampler_func, parameter[constant[std], n... | keyword[def] identifier[std] ( identifier[self] , identifier[ddof] = literal[int] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[nv] . identifier[validate_resampler_func] ( literal[string] , identifier[args] , identifier[kwargs] )
keyword[return] identifier[self]... | def std(self, ddof=1, *args, **kwargs):
"""
Compute standard deviation of groups, excluding missing values.
Parameters
----------
ddof : integer, default 1
Degrees of freedom.
"""
nv.validate_resampler_func('std', args, kwargs)
return self._downsample('st... |
def set_label(self, label, lang=None):
"""Sets the `label` metadata property on your Thing/Point. Only one label is allowed per language, so any
other labels in this language are removed before adding this one
Raises `ValueError` containing an error message if the parameters fail validation
... | def function[set_label, parameter[self, label, lang]]:
constant[Sets the `label` metadata property on your Thing/Point. Only one label is allowed per language, so any
other labels in this language are removed before adding this one
Raises `ValueError` containing an error message if the paramet... | keyword[def] identifier[set_label] ( identifier[self] , identifier[label] , identifier[lang] = keyword[None] ):
literal[string]
identifier[label] = identifier[Validation] . identifier[label_check_convert] ( identifier[label] )
identifier[lang] = identifier[Validation] . identifier[lang_che... | def set_label(self, label, lang=None):
"""Sets the `label` metadata property on your Thing/Point. Only one label is allowed per language, so any
other labels in this language are removed before adding this one
Raises `ValueError` containing an error message if the parameters fail validation
... |
def search_media(self, mq={}, rq={}, limit=100, offset=0, sort=None,
fields=None, fields_exclude=FIELDS_EXCLUDE_DEFAULT):
"""
mq Search Query in iDigBio Query Format, using Media Query Fields
rq Search Query in iDigBio Query Format, using Record Query Fields
... | def function[search_media, parameter[self, mq, rq, limit, offset, sort, fields, fields_exclude]]:
constant[
mq Search Query in iDigBio Query Format, using Media Query Fields
rq Search Query in iDigBio Query Format, using Record Query Fields
sort field to sort on, pick fr... | keyword[def] identifier[search_media] ( identifier[self] , identifier[mq] ={}, identifier[rq] ={}, identifier[limit] = literal[int] , identifier[offset] = literal[int] , identifier[sort] = keyword[None] ,
identifier[fields] = keyword[None] , identifier[fields_exclude] = identifier[FIELDS_EXCLUDE_DEFAULT] ):
... | def search_media(self, mq={}, rq={}, limit=100, offset=0, sort=None, fields=None, fields_exclude=FIELDS_EXCLUDE_DEFAULT):
"""
mq Search Query in iDigBio Query Format, using Media Query Fields
rq Search Query in iDigBio Query Format, using Record Query Fields
sort field to so... |
def defer(self, timeout_seconds, callback):
"""This method allows to invoke the callback with specified arguments once the specified amount of time.
:returns: EventHandle object. Call .remove() on it to cancel the event.
"""
priority = 1
event = self._scheduler.enter(timeout_seco... | def function[defer, parameter[self, timeout_seconds, callback]]:
constant[This method allows to invoke the callback with specified arguments once the specified amount of time.
:returns: EventHandle object. Call .remove() on it to cancel the event.
]
variable[priority] assign[=] constant[... | keyword[def] identifier[defer] ( identifier[self] , identifier[timeout_seconds] , identifier[callback] ):
literal[string]
identifier[priority] = literal[int]
identifier[event] = identifier[self] . identifier[_scheduler] . identifier[enter] ( identifier[timeout_seconds] , identifier[priori... | def defer(self, timeout_seconds, callback):
"""This method allows to invoke the callback with specified arguments once the specified amount of time.
:returns: EventHandle object. Call .remove() on it to cancel the event.
"""
priority = 1
event = self._scheduler.enter(timeout_seconds, priorit... |
def startDrag(self, dropActions):
"""Reimplement Qt Method - handle drag event"""
data = QMimeData()
data.setUrls([QUrl(fname) for fname in self.get_selected_filenames()])
drag = QDrag(self)
drag.setMimeData(data)
drag.exec_() | def function[startDrag, parameter[self, dropActions]]:
constant[Reimplement Qt Method - handle drag event]
variable[data] assign[=] call[name[QMimeData], parameter[]]
call[name[data].setUrls, parameter[<ast.ListComp object at 0x7da18f00c2b0>]]
variable[drag] assign[=] call[name[QDrag], p... | keyword[def] identifier[startDrag] ( identifier[self] , identifier[dropActions] ):
literal[string]
identifier[data] = identifier[QMimeData] ()
identifier[data] . identifier[setUrls] ([ identifier[QUrl] ( identifier[fname] ) keyword[for] identifier[fname] keyword[in] identifier[self] ... | def startDrag(self, dropActions):
"""Reimplement Qt Method - handle drag event"""
data = QMimeData()
data.setUrls([QUrl(fname) for fname in self.get_selected_filenames()])
drag = QDrag(self)
drag.setMimeData(data)
drag.exec_() |
def paramiko_tunnel(lport, rport, server, remoteip='127.0.0.1', keyfile=None, password=None, timeout=60):
"""launch a tunner with paramiko in a subprocess. This should only be used
when shell ssh is unavailable (e.g. Windows).
This creates a tunnel redirecting `localhost:lport` to `remoteip:rport`,
as ... | def function[paramiko_tunnel, parameter[lport, rport, server, remoteip, keyfile, password, timeout]]:
constant[launch a tunner with paramiko in a subprocess. This should only be used
when shell ssh is unavailable (e.g. Windows).
This creates a tunnel redirecting `localhost:lport` to `remoteip:rport`,
... | keyword[def] identifier[paramiko_tunnel] ( identifier[lport] , identifier[rport] , identifier[server] , identifier[remoteip] = literal[string] , identifier[keyfile] = keyword[None] , identifier[password] = keyword[None] , identifier[timeout] = literal[int] ):
literal[string]
keyword[if] identifier[paramik... | def paramiko_tunnel(lport, rport, server, remoteip='127.0.0.1', keyfile=None, password=None, timeout=60):
"""launch a tunner with paramiko in a subprocess. This should only be used
when shell ssh is unavailable (e.g. Windows).
This creates a tunnel redirecting `localhost:lport` to `remoteip:rport`,
as ... |
def p_measure(self, program):
"""
measure : MEASURE primary ASSIGN primary
"""
program[0] = node.Measure([program[2], program[4]])
self.verify_reg(program[2], 'qreg')
self.verify_reg(program[4], 'creg') | def function[p_measure, parameter[self, program]]:
constant[
measure : MEASURE primary ASSIGN primary
]
call[name[program]][constant[0]] assign[=] call[name[node].Measure, parameter[list[[<ast.Subscript object at 0x7da1b03821a0>, <ast.Subscript object at 0x7da1b0381ed0>]]]]
ca... | keyword[def] identifier[p_measure] ( identifier[self] , identifier[program] ):
literal[string]
identifier[program] [ literal[int] ]= identifier[node] . identifier[Measure] ([ identifier[program] [ literal[int] ], identifier[program] [ literal[int] ]])
identifier[self] . identifier[verify_r... | def p_measure(self, program):
"""
measure : MEASURE primary ASSIGN primary
"""
program[0] = node.Measure([program[2], program[4]])
self.verify_reg(program[2], 'qreg')
self.verify_reg(program[4], 'creg') |
def visit_and_update(self, visitor_fn):
"""Create an updated version (if needed) of BetweenClause via the visitor pattern."""
new_lower_bound = self.lower_bound.visit_and_update(visitor_fn)
new_upper_bound = self.upper_bound.visit_and_update(visitor_fn)
if new_lower_bound is not self.lo... | def function[visit_and_update, parameter[self, visitor_fn]]:
constant[Create an updated version (if needed) of BetweenClause via the visitor pattern.]
variable[new_lower_bound] assign[=] call[name[self].lower_bound.visit_and_update, parameter[name[visitor_fn]]]
variable[new_upper_bound] assign[=... | keyword[def] identifier[visit_and_update] ( identifier[self] , identifier[visitor_fn] ):
literal[string]
identifier[new_lower_bound] = identifier[self] . identifier[lower_bound] . identifier[visit_and_update] ( identifier[visitor_fn] )
identifier[new_upper_bound] = identifier[self] . ident... | def visit_and_update(self, visitor_fn):
"""Create an updated version (if needed) of BetweenClause via the visitor pattern."""
new_lower_bound = self.lower_bound.visit_and_update(visitor_fn)
new_upper_bound = self.upper_bound.visit_and_update(visitor_fn)
if new_lower_bound is not self.lower_bound or new_... |
def _cleanup_api(self):
'''
Helper method to clean up resources and models if we detected a change in the swagger file
for a stage
'''
resources = __salt__['boto_apigateway.describe_api_resources'](restApiId=self.restApiId,
... | def function[_cleanup_api, parameter[self]]:
constant[
Helper method to clean up resources and models if we detected a change in the swagger file
for a stage
]
variable[resources] assign[=] call[call[name[__salt__]][constant[boto_apigateway.describe_api_resources]], parameter[]]
... | keyword[def] identifier[_cleanup_api] ( identifier[self] ):
literal[string]
identifier[resources] = identifier[__salt__] [ literal[string] ]( identifier[restApiId] = identifier[self] . identifier[restApiId] ,
** identifier[self] . identifier[_common_aws_args] )
keyword[if] identif... | def _cleanup_api(self):
"""
Helper method to clean up resources and models if we detected a change in the swagger file
for a stage
"""
resources = __salt__['boto_apigateway.describe_api_resources'](restApiId=self.restApiId, **self._common_aws_args)
if resources.get('resources'):
... |
def subst_dict(target, source):
"""Create a dictionary for substitution of special
construction variables.
This translates the following special arguments:
target - the target (object or array of objects),
used to generate the TARGET and TARGETS
construction variables
so... | def function[subst_dict, parameter[target, source]]:
constant[Create a dictionary for substitution of special
construction variables.
This translates the following special arguments:
target - the target (object or array of objects),
used to generate the TARGET and TARGETS
... | keyword[def] identifier[subst_dict] ( identifier[target] , identifier[source] ):
literal[string]
identifier[dict] ={}
keyword[if] identifier[target] :
keyword[def] identifier[get_tgt_subst_proxy] ( identifier[thing] ):
keyword[try] :
identifier[subst_proxy] = ... | def subst_dict(target, source):
"""Create a dictionary for substitution of special
construction variables.
This translates the following special arguments:
target - the target (object or array of objects),
used to generate the TARGET and TARGETS
construction variables
so... |
def _get_upload_cmd(self, mirror=False):
"""Generate the S3 CLI upload command
Args:
mirror (bool): If true, uses a flat directory structure instead of nesting under a version.
Returns:
str: The full CLI command to run.
"""
if mirror:
dest_ur... | def function[_get_upload_cmd, parameter[self, mirror]]:
constant[Generate the S3 CLI upload command
Args:
mirror (bool): If true, uses a flat directory structure instead of nesting under a version.
Returns:
str: The full CLI command to run.
]
if name[mir... | keyword[def] identifier[_get_upload_cmd] ( identifier[self] , identifier[mirror] = keyword[False] ):
literal[string]
keyword[if] identifier[mirror] :
identifier[dest_uri] = identifier[self] . identifier[s3_mirror_uri]
keyword[else] :
identifier[dest_uri] = ident... | def _get_upload_cmd(self, mirror=False):
"""Generate the S3 CLI upload command
Args:
mirror (bool): If true, uses a flat directory structure instead of nesting under a version.
Returns:
str: The full CLI command to run.
"""
if mirror:
dest_uri = self.s3_... |
def main(commit_only=True):
"""
Run the configured code checks.
Return system exit code.
1 - reject commit
0 - accept commit
"""
global TEMP_FOLDER
exit_code = 0
hook_checks = HookConfig(get_config_file())
with files_to_check(commit_only) as files:
for name, mod ... | def function[main, parameter[commit_only]]:
constant[
Run the configured code checks.
Return system exit code.
1 - reject commit
0 - accept commit
]
<ast.Global object at 0x7da1b0fa7e50>
variable[exit_code] assign[=] constant[0]
variable[hook_checks] assign[=] ca... | keyword[def] identifier[main] ( identifier[commit_only] = keyword[True] ):
literal[string]
keyword[global] identifier[TEMP_FOLDER]
identifier[exit_code] = literal[int]
identifier[hook_checks] = identifier[HookConfig] ( identifier[get_config_file] ())
keyword[with] identifier[files_to_che... | def main(commit_only=True):
"""
Run the configured code checks.
Return system exit code.
1 - reject commit
0 - accept commit
"""
global TEMP_FOLDER
exit_code = 0
hook_checks = HookConfig(get_config_file())
with files_to_check(commit_only) as files:
for (name, mod... |
def move_todo_item(self, item_id, to):
"""
Changes the position of an item within its parent list. It does not
currently support reparenting an item. Position 1 is at the top of the
list. Moving an item beyond the end of the list puts it at the bottom
of the list.
"""
... | def function[move_todo_item, parameter[self, item_id, to]]:
constant[
Changes the position of an item within its parent list. It does not
currently support reparenting an item. Position 1 is at the top of the
list. Moving an item beyond the end of the list puts it at the bottom
o... | keyword[def] identifier[move_todo_item] ( identifier[self] , identifier[item_id] , identifier[to] ):
literal[string]
identifier[path] = literal[string] % identifier[item_id]
identifier[req] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[ET] . identifier[Sub... | def move_todo_item(self, item_id, to):
"""
Changes the position of an item within its parent list. It does not
currently support reparenting an item. Position 1 is at the top of the
list. Moving an item beyond the end of the list puts it at the bottom
of the list.
"""
pat... |
def log(level, msg, *args, **kwargs):
"""Logs 'msg % args' at absl logging level 'level'.
If no args are given just print msg, ignoring any interpolation specifiers.
Args:
level: int, the absl logging level at which to log the message
(logging.DEBUG|INFO|WARNING|ERROR|FATAL). While some C++ verbose ... | def function[log, parameter[level, msg]]:
constant[Logs 'msg % args' at absl logging level 'level'.
If no args are given just print msg, ignoring any interpolation specifiers.
Args:
level: int, the absl logging level at which to log the message
(logging.DEBUG|INFO|WARNING|ERROR|FATAL). While s... | keyword[def] identifier[log] ( identifier[level] , identifier[msg] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[level] > identifier[converter] . identifier[ABSL_DEBUG] :
identifier[standard_level] = identifier[converter] . identifier[STANDARD_DEBUG] -( ide... | def log(level, msg, *args, **kwargs):
"""Logs 'msg % args' at absl logging level 'level'.
If no args are given just print msg, ignoring any interpolation specifiers.
Args:
level: int, the absl logging level at which to log the message
(logging.DEBUG|INFO|WARNING|ERROR|FATAL). While some C++ verbos... |
def DbGetAttributeAlias2(self, argin):
""" Get the attribute alias from the attribute name.
Returns one empty string if nothing found in database
:param argin: The attribute name (dev_name/att_name)
:type: tango.DevString
:return: The attribute alias name (or empty string)
... | def function[DbGetAttributeAlias2, parameter[self, argin]]:
constant[ Get the attribute alias from the attribute name.
Returns one empty string if nothing found in database
:param argin: The attribute name (dev_name/att_name)
:type: tango.DevString
:return: The attribute alias n... | keyword[def] identifier[DbGetAttributeAlias2] ( identifier[self] , identifier[argin] ):
literal[string]
identifier[self] . identifier[_log] . identifier[debug] ( literal[string] )
identifier[attr_name] = identifier[argin] [ literal[int] ]
keyword[return] identifier[self] . identi... | def DbGetAttributeAlias2(self, argin):
""" Get the attribute alias from the attribute name.
Returns one empty string if nothing found in database
:param argin: The attribute name (dev_name/att_name)
:type: tango.DevString
:return: The attribute alias name (or empty string)
:... |
def generate(args=None, namespace=None, file=None):
"""
Genereate DDL from data sources named.
:args: String or list of strings to be parsed for arguments
:namespace: Namespace to extract arguments from
:file: Write to this open file object (default stdout)
"""
if hasattr(args, 's... | def function[generate, parameter[args, namespace, file]]:
constant[
Genereate DDL from data sources named.
:args: String or list of strings to be parsed for arguments
:namespace: Namespace to extract arguments from
:file: Write to this open file object (default stdout)
]
i... | keyword[def] identifier[generate] ( identifier[args] = keyword[None] , identifier[namespace] = keyword[None] , identifier[file] = keyword[None] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[args] , literal[string] ):
identifier[args] = identifier[args] . identifier[split] ()
... | def generate(args=None, namespace=None, file=None):
"""
Genereate DDL from data sources named.
:args: String or list of strings to be parsed for arguments
:namespace: Namespace to extract arguments from
:file: Write to this open file object (default stdout)
"""
if hasattr(args, 's... |
def create_type_variant(cls, type_name, type_converter):
"""
Create type variants for types with a cardinality field.
The new type converters are based on the type converter with
cardinality=1.
.. code-block:: python
import parse
@parse.with_pattern(r'\... | def function[create_type_variant, parameter[cls, type_name, type_converter]]:
constant[
Create type variants for types with a cardinality field.
The new type converters are based on the type converter with
cardinality=1.
.. code-block:: python
import parse
... | keyword[def] identifier[create_type_variant] ( identifier[cls] , identifier[type_name] , identifier[type_converter] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[type_name] , identifier[six] . identifier[string_types] )
keyword[if] keyword[not] identifier[Cardin... | def create_type_variant(cls, type_name, type_converter):
"""
Create type variants for types with a cardinality field.
The new type converters are based on the type converter with
cardinality=1.
.. code-block:: python
import parse
@parse.with_pattern(r'\\d+'... |
def get_hotp(
secret,
intervals_no,
as_string=False,
casefold=True,
digest_method=hashlib.sha1,
token_length=6,
):
"""
Get HMAC-based one-time password on the basis of given secret and
interval number.
:param secret: the base32-encoded string acting as se... | def function[get_hotp, parameter[secret, intervals_no, as_string, casefold, digest_method, token_length]]:
constant[
Get HMAC-based one-time password on the basis of given secret and
interval number.
:param secret: the base32-encoded string acting as secret key
:type secret: str or unicode
... | keyword[def] identifier[get_hotp] (
identifier[secret] ,
identifier[intervals_no] ,
identifier[as_string] = keyword[False] ,
identifier[casefold] = keyword[True] ,
identifier[digest_method] = identifier[hashlib] . identifier[sha1] ,
identifier[token_length] = literal[int] ,
):
literal[string]
keyword... | def get_hotp(secret, intervals_no, as_string=False, casefold=True, digest_method=hashlib.sha1, token_length=6):
"""
Get HMAC-based one-time password on the basis of given secret and
interval number.
:param secret: the base32-encoded string acting as secret key
:type secret: str or unicode
:para... |
def global_fixes():
"""Yield multiple (code, function) tuples."""
for function in list(globals().values()):
if inspect.isfunction(function):
arguments = _get_parameters(function)
if arguments[:1] != ['source']:
continue
code = extract_code_from_functi... | def function[global_fixes, parameter[]]:
constant[Yield multiple (code, function) tuples.]
for taget[name[function]] in starred[call[name[list], parameter[call[call[name[globals], parameter[]].values, parameter[]]]]] begin[:]
if call[name[inspect].isfunction, parameter[name[function]]] b... | keyword[def] identifier[global_fixes] ():
literal[string]
keyword[for] identifier[function] keyword[in] identifier[list] ( identifier[globals] (). identifier[values] ()):
keyword[if] identifier[inspect] . identifier[isfunction] ( identifier[function] ):
identifier[arguments] = ide... | def global_fixes():
"""Yield multiple (code, function) tuples."""
for function in list(globals().values()):
if inspect.isfunction(function):
arguments = _get_parameters(function)
if arguments[:1] != ['source']:
continue # depends on [control=['if'], data=[]]
... |
def add_aggregation_columns(
df, *,
group_cols: Union[str, List[str]],
aggregations: Dict[str, Agg]
):
"""
Add new columns containing aggregations values on existing columns
---
### Parameters
*mandatory :*
- `group_cols` (*str* or *list*): columns used to aggregate th... | def function[add_aggregation_columns, parameter[df]]:
constant[
Add new columns containing aggregations values on existing columns
---
### Parameters
*mandatory :*
- `group_cols` (*str* or *list*): columns used to aggregate the data
- `aggregations` (*dict*): keys are name of new colu... | keyword[def] identifier[add_aggregation_columns] (
identifier[df] ,*,
identifier[group_cols] : identifier[Union] [ identifier[str] , identifier[List] [ identifier[str] ]],
identifier[aggregations] : identifier[Dict] [ identifier[str] , identifier[Agg] ]
):
literal[string]
identifier[group] = identifier[... | def add_aggregation_columns(df, *, group_cols: Union[str, List[str]], aggregations: Dict[str, Agg]):
"""
Add new columns containing aggregations values on existing columns
---
### Parameters
*mandatory :*
- `group_cols` (*str* or *list*): columns used to aggregate the data
- `aggregations... |
def is_prime(n, mr_rounds=25):
"""Test whether n is probably prime
See <https://en.wikipedia.org/wiki/Primality_test#Probabilistic_tests>
Arguments:
n (int): the number to be tested
mr_rounds (int, optional): number of Miller-Rabin iterations to run;
defaults to 25 iterations, ... | def function[is_prime, parameter[n, mr_rounds]]:
constant[Test whether n is probably prime
See <https://en.wikipedia.org/wiki/Primality_test#Probabilistic_tests>
Arguments:
n (int): the number to be tested
mr_rounds (int, optional): number of Miller-Rabin iterations to run;
... | keyword[def] identifier[is_prime] ( identifier[n] , identifier[mr_rounds] = literal[int] ):
literal[string]
keyword[if] identifier[n] <= identifier[first_primes] [- literal[int] ]:
keyword[return] identifier[n] keyword[in] identifier[first_primes]
keyword[for] identifier[p... | def is_prime(n, mr_rounds=25):
"""Test whether n is probably prime
See <https://en.wikipedia.org/wiki/Primality_test#Probabilistic_tests>
Arguments:
n (int): the number to be tested
mr_rounds (int, optional): number of Miller-Rabin iterations to run;
defaults to 25 iterations, ... |
def calculate_total_amt(self, items={}):
"""Returns the total amount/cost of items in the current invoice"""
_items = items.items() or self.items.items()
return sum(float(x[1].total_price) for x in _items) | def function[calculate_total_amt, parameter[self, items]]:
constant[Returns the total amount/cost of items in the current invoice]
variable[_items] assign[=] <ast.BoolOp object at 0x7da1b10d6d10>
return[call[name[sum], parameter[<ast.GeneratorExp object at 0x7da1b10d6da0>]]] | keyword[def] identifier[calculate_total_amt] ( identifier[self] , identifier[items] ={}):
literal[string]
identifier[_items] = identifier[items] . identifier[items] () keyword[or] identifier[self] . identifier[items] . identifier[items] ()
keyword[return] identifier[sum] ( identifier[flo... | def calculate_total_amt(self, items={}):
"""Returns the total amount/cost of items in the current invoice"""
_items = items.items() or self.items.items()
return sum((float(x[1].total_price) for x in _items)) |
def fromLink(self, link):
"""
Factory Method. Fetches article data from given link and builds the object
"""
soup = get_article_soup(link)
head = soup.find_all('article',class_='')[0]
parts = link.split('/')
id = '%s-%s'%(parts[0],parts[-1])
issue = parts[0].split('-')[-1]
#fetching head
title =... | def function[fromLink, parameter[self, link]]:
constant[
Factory Method. Fetches article data from given link and builds the object
]
variable[soup] assign[=] call[name[get_article_soup], parameter[name[link]]]
variable[head] assign[=] call[call[name[soup].find_all, parameter[constant[artic... | keyword[def] identifier[fromLink] ( identifier[self] , identifier[link] ):
literal[string]
identifier[soup] = identifier[get_article_soup] ( identifier[link] )
identifier[head] = identifier[soup] . identifier[find_all] ( literal[string] , identifier[class_] = literal[string] )[ literal[int] ]
identifier[... | def fromLink(self, link):
"""
Factory Method. Fetches article data from given link and builds the object
"""
soup = get_article_soup(link)
head = soup.find_all('article', class_='')[0]
parts = link.split('/')
id = '%s-%s' % (parts[0], parts[-1])
issue = parts[0].split('-')[-1] #fetching he... |
def white_move(self):
"""
Calls the white player's ``generate_move()``
method and updates the board with the move returned.
"""
move = self.player_white.generate_move(self.position)
move = make_legal(move, self.position)
self.position.update(move) | def function[white_move, parameter[self]]:
constant[
Calls the white player's ``generate_move()``
method and updates the board with the move returned.
]
variable[move] assign[=] call[name[self].player_white.generate_move, parameter[name[self].position]]
variable[move] ass... | keyword[def] identifier[white_move] ( identifier[self] ):
literal[string]
identifier[move] = identifier[self] . identifier[player_white] . identifier[generate_move] ( identifier[self] . identifier[position] )
identifier[move] = identifier[make_legal] ( identifier[move] , identifier[self] .... | def white_move(self):
"""
Calls the white player's ``generate_move()``
method and updates the board with the move returned.
"""
move = self.player_white.generate_move(self.position)
move = make_legal(move, self.position)
self.position.update(move) |
def load_mode_validator(obs_mode, node):
"""Load observing mode validator"""
nval = node.get('validator')
if nval is None:
pass
elif isinstance(nval, str):
# load function
obs_mode.validator = import_object(nval)
else:
raise TypeError('validator must be None or a st... | def function[load_mode_validator, parameter[obs_mode, node]]:
constant[Load observing mode validator]
variable[nval] assign[=] call[name[node].get, parameter[constant[validator]]]
if compare[name[nval] is constant[None]] begin[:]
pass
return[name[obs_mode]] | keyword[def] identifier[load_mode_validator] ( identifier[obs_mode] , identifier[node] ):
literal[string]
identifier[nval] = identifier[node] . identifier[get] ( literal[string] )
keyword[if] identifier[nval] keyword[is] keyword[None] :
keyword[pass]
keyword[elif] identifier[isins... | def load_mode_validator(obs_mode, node):
"""Load observing mode validator"""
nval = node.get('validator')
if nval is None:
pass # depends on [control=['if'], data=[]]
elif isinstance(nval, str):
# load function
obs_mode.validator = import_object(nval) # depends on [control=['if... |
def nodeprep(string, allow_unassigned=False):
"""
Process the given `string` using the Nodeprep (`RFC 6122`_) profile. In the
error cases defined in `RFC 3454`_ (stringprep), a :class:`ValueError` is
raised.
"""
chars = list(string)
_nodeprep_do_mapping(chars)
do_normalization(chars)
... | def function[nodeprep, parameter[string, allow_unassigned]]:
constant[
Process the given `string` using the Nodeprep (`RFC 6122`_) profile. In the
error cases defined in `RFC 3454`_ (stringprep), a :class:`ValueError` is
raised.
]
variable[chars] assign[=] call[name[list], parameter[name... | keyword[def] identifier[nodeprep] ( identifier[string] , identifier[allow_unassigned] = keyword[False] ):
literal[string]
identifier[chars] = identifier[list] ( identifier[string] )
identifier[_nodeprep_do_mapping] ( identifier[chars] )
identifier[do_normalization] ( identifier[chars] )
ide... | def nodeprep(string, allow_unassigned=False):
"""
Process the given `string` using the Nodeprep (`RFC 6122`_) profile. In the
error cases defined in `RFC 3454`_ (stringprep), a :class:`ValueError` is
raised.
"""
chars = list(string)
_nodeprep_do_mapping(chars)
do_normalization(chars)
... |
def build_object(self, obj):
"""Override django-bakery to skip profiles that raise 404"""
try:
build_path = self.get_build_path(obj)
self.request = self.create_request(build_path)
self.request.user = AnonymousUser()
self.set_kwargs(obj)
self.bu... | def function[build_object, parameter[self, obj]]:
constant[Override django-bakery to skip profiles that raise 404]
<ast.Try object at 0x7da1b0eb9600> | keyword[def] identifier[build_object] ( identifier[self] , identifier[obj] ):
literal[string]
keyword[try] :
identifier[build_path] = identifier[self] . identifier[get_build_path] ( identifier[obj] )
identifier[self] . identifier[request] = identifier[self] . identifier[cr... | def build_object(self, obj):
"""Override django-bakery to skip profiles that raise 404"""
try:
build_path = self.get_build_path(obj)
self.request = self.create_request(build_path)
self.request.user = AnonymousUser()
self.set_kwargs(obj)
self.build_file(build_path, self.ge... |
def hash(self):
"""
Returns a hash of this render configuration from the variable, renderer, and time_index parameters. Used for
caching the full-extent, native projection render so that subsequent requests can be served by a warp
operation only.
"""
renderer_str = "{}|{... | def function[hash, parameter[self]]:
constant[
Returns a hash of this render configuration from the variable, renderer, and time_index parameters. Used for
caching the full-extent, native projection render so that subsequent requests can be served by a warp
operation only.
]
... | keyword[def] identifier[hash] ( identifier[self] ):
literal[string]
identifier[renderer_str] = literal[string] . identifier[format] (
identifier[self] . identifier[renderer] . identifier[__class__] . identifier[__name__] , identifier[self] . identifier[renderer] . identifier[colormap] , i... | def hash(self):
"""
Returns a hash of this render configuration from the variable, renderer, and time_index parameters. Used for
caching the full-extent, native projection render so that subsequent requests can be served by a warp
operation only.
"""
renderer_str = '{}|{}|{}|{}'.... |
def build_sample_smoother_problem_friedman82(N=200):
"""Sample problem from supersmoother publication."""
x = numpy.random.uniform(size=N)
err = numpy.random.standard_normal(N)
y = numpy.sin(2 * math.pi * (1 - x) ** 2) + x * err
return x, y | def function[build_sample_smoother_problem_friedman82, parameter[N]]:
constant[Sample problem from supersmoother publication.]
variable[x] assign[=] call[name[numpy].random.uniform, parameter[]]
variable[err] assign[=] call[name[numpy].random.standard_normal, parameter[name[N]]]
variable... | keyword[def] identifier[build_sample_smoother_problem_friedman82] ( identifier[N] = literal[int] ):
literal[string]
identifier[x] = identifier[numpy] . identifier[random] . identifier[uniform] ( identifier[size] = identifier[N] )
identifier[err] = identifier[numpy] . identifier[random] . identifier[st... | def build_sample_smoother_problem_friedman82(N=200):
"""Sample problem from supersmoother publication."""
x = numpy.random.uniform(size=N)
err = numpy.random.standard_normal(N)
y = numpy.sin(2 * math.pi * (1 - x) ** 2) + x * err
return (x, y) |
def disconnect(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Close proxy connection to a device's management interface.
:param id: Device ID as an int.
"""
return self.service.post(self.base+str(id)+'/disconnect/') | def function[disconnect, parameter[self, id]]:
constant[Close proxy connection to a device's management interface.
:param id: Device ID as an int.
]
return[call[name[self].service.post, parameter[binary_operation[binary_operation[name[self].base + call[name[str], parameter[name[id]]]] + con... | keyword[def] identifier[disconnect] ( identifier[self] , identifier[id] ):
literal[string]
keyword[return] identifier[self] . identifier[service] . identifier[post] ( identifier[self] . identifier[base] + identifier[str] ( identifier[id] )+ literal[string] ) | def disconnect(self, id): # pylint: disable=invalid-name,redefined-builtin
"Close proxy connection to a device's management interface.\n\n :param id: Device ID as an int.\n "
return self.service.post(self.base + str(id) + '/disconnect/') |
def write_extra_data(self, stream: WriteStream) -> None:
"""Writes the param container and string pointer arrays.
Unlike other write_extra_data functions, this can be called before write()."""
if self.params:
stream.align(8)
if self._params_offset_writer:
... | def function[write_extra_data, parameter[self, stream]]:
constant[Writes the param container and string pointer arrays.
Unlike other write_extra_data functions, this can be called before write().]
if name[self].params begin[:]
call[name[stream].align, parameter[constant[8]]]
... | keyword[def] identifier[write_extra_data] ( identifier[self] , identifier[stream] : identifier[WriteStream] )-> keyword[None] :
literal[string]
keyword[if] identifier[self] . identifier[params] :
identifier[stream] . identifier[align] ( literal[int] )
keyword[if] identif... | def write_extra_data(self, stream: WriteStream) -> None:
"""Writes the param container and string pointer arrays.
Unlike other write_extra_data functions, this can be called before write()."""
if self.params:
stream.align(8)
if self._params_offset_writer:
self._params_offset_... |
def serialize_operator_equal(self, op):
"""
Serializer for :meth:`SpiffWorkflow.operators.Equal`.
Example::
<equals>
<value>text</value>
<value><attribute>foobar</attribute></value>
<value><path>foobar</path></value>
</equ... | def function[serialize_operator_equal, parameter[self, op]]:
constant[
Serializer for :meth:`SpiffWorkflow.operators.Equal`.
Example::
<equals>
<value>text</value>
<value><attribute>foobar</attribute></value>
<value><path>foobar</path... | keyword[def] identifier[serialize_operator_equal] ( identifier[self] , identifier[op] ):
literal[string]
identifier[elem] = identifier[etree] . identifier[Element] ( literal[string] )
keyword[return] identifier[self] . identifier[serialize_value_list] ( identifier[elem] , identifier[op] .... | def serialize_operator_equal(self, op):
"""
Serializer for :meth:`SpiffWorkflow.operators.Equal`.
Example::
<equals>
<value>text</value>
<value><attribute>foobar</attribute></value>
<value><path>foobar</path></value>
</equals>... |
def read(file, system):
"""Parse an ANDES card file into internal variables"""
try:
fid = open(file, 'r')
raw_file = fid.readlines()
except IOError:
print('* IOError while reading input card file.')
return
ret_dict = dict()
ret_dict['outfile'] = file.split('.')[0].lo... | def function[read, parameter[file, system]]:
constant[Parse an ANDES card file into internal variables]
<ast.Try object at 0x7da207f9bca0>
variable[ret_dict] assign[=] call[name[dict], parameter[]]
call[name[ret_dict]][constant[outfile]] assign[=] binary_operation[call[call[call[name[file].s... | keyword[def] identifier[read] ( identifier[file] , identifier[system] ):
literal[string]
keyword[try] :
identifier[fid] = identifier[open] ( identifier[file] , literal[string] )
identifier[raw_file] = identifier[fid] . identifier[readlines] ()
keyword[except] identifier[IOError] :
... | def read(file, system):
"""Parse an ANDES card file into internal variables"""
try:
fid = open(file, 'r')
raw_file = fid.readlines() # depends on [control=['try'], data=[]]
except IOError:
print('* IOError while reading input card file.')
return # depends on [control=['exce... |
def timer(func):
"""Time a method and print its duration after return
"""
name = func.__name__
@wraps(func)
def timed_func(self, *args, **kwargs): # pylint: disable=missing-docstring
_start = time.time()
out = func(self, *args, **kwargs)
self.log(2, '{0} took {1:.1f} sec'.f... | def function[timer, parameter[func]]:
constant[Time a method and print its duration after return
]
variable[name] assign[=] name[func].__name__
def function[timed_func, parameter[self]]:
variable[_start] assign[=] call[name[time].time, parameter[]]
variable[ou... | keyword[def] identifier[timer] ( identifier[func] ):
literal[string]
identifier[name] = identifier[func] . identifier[__name__]
@ identifier[wraps] ( identifier[func] )
keyword[def] identifier[timed_func] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
identifier[_star... | def timer(func):
"""Time a method and print its duration after return
"""
name = func.__name__
@wraps(func)
def timed_func(self, *args, **kwargs): # pylint: disable=missing-docstring
_start = time.time()
out = func(self, *args, **kwargs)
self.log(2, '{0} took {1:.1f} sec'.f... |
def delete_snapshot(snapshots_ids=None, config="root"):
'''
Deletes an snapshot
config
Configuration name. (Default: root)
snapshots_ids
List of the snapshots IDs to be deleted.
CLI example:
.. code-block:: bash
salt '*' snapper.delete_snapshot 54
salt '*' sn... | def function[delete_snapshot, parameter[snapshots_ids, config]]:
constant[
Deletes an snapshot
config
Configuration name. (Default: root)
snapshots_ids
List of the snapshots IDs to be deleted.
CLI example:
.. code-block:: bash
salt '*' snapper.delete_snapshot 54
... | keyword[def] identifier[delete_snapshot] ( identifier[snapshots_ids] = keyword[None] , identifier[config] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[snapshots_ids] :
keyword[raise] identifier[CommandExecutionError] ( literal[string] )
keyword[try] :
i... | def delete_snapshot(snapshots_ids=None, config='root'):
"""
Deletes an snapshot
config
Configuration name. (Default: root)
snapshots_ids
List of the snapshots IDs to be deleted.
CLI example:
.. code-block:: bash
salt '*' snapper.delete_snapshot 54
salt '*' sn... |
def _LookUpSeasonDirectory(self, showID, showDir, seasonNum):
"""
Look up season directory. First attempt to find match from database,
otherwise search TV show directory. If no match is found in the database
the user can choose to accept a match from the TV show directory, enter
a new directory name... | def function[_LookUpSeasonDirectory, parameter[self, showID, showDir, seasonNum]]:
constant[
Look up season directory. First attempt to find match from database,
otherwise search TV show directory. If no match is found in the database
the user can choose to accept a match from the TV show directory,... | keyword[def] identifier[_LookUpSeasonDirectory] ( identifier[self] , identifier[showID] , identifier[showDir] , identifier[seasonNum] ):
literal[string]
identifier[goodlogging] . identifier[Log] . identifier[Info] ( literal[string] , literal[string] . identifier[format] ( identifier[showID] ))
identif... | def _LookUpSeasonDirectory(self, showID, showDir, seasonNum):
"""
Look up season directory. First attempt to find match from database,
otherwise search TV show directory. If no match is found in the database
the user can choose to accept a match from the TV show directory, enter
a new directory name... |
def make_entry_point(patches, original_entry_point):
"""Use this to make a console_script entry point for your application
which applies patches.
:param patches: iterable of pymonkey patches to apply. Ex: ('my-patch,)
:param original_entry_point: Such as 'pip'
"""
def entry(argv=None):
... | def function[make_entry_point, parameter[patches, original_entry_point]]:
constant[Use this to make a console_script entry point for your application
which applies patches.
:param patches: iterable of pymonkey patches to apply. Ex: ('my-patch,)
:param original_entry_point: Such as 'pip'
]
... | keyword[def] identifier[make_entry_point] ( identifier[patches] , identifier[original_entry_point] ):
literal[string]
keyword[def] identifier[entry] ( identifier[argv] = keyword[None] ):
identifier[argv] = identifier[argv] keyword[if] identifier[argv] keyword[is] keyword[not] keyword[None] ... | def make_entry_point(patches, original_entry_point):
"""Use this to make a console_script entry point for your application
which applies patches.
:param patches: iterable of pymonkey patches to apply. Ex: ('my-patch,)
:param original_entry_point: Such as 'pip'
"""
def entry(argv=None):
... |
def CREATE(self, value, offset, size):
"""Create a new account with associated code"""
tx = self.world.last_transaction # At this point last and current tx are the same.
address = tx.address
if tx.result == 'RETURN':
self.world.set_code(tx.address, tx.return_data)
el... | def function[CREATE, parameter[self, value, offset, size]]:
constant[Create a new account with associated code]
variable[tx] assign[=] name[self].world.last_transaction
variable[address] assign[=] name[tx].address
if compare[name[tx].result equal[==] constant[RETURN]] begin[:]
... | keyword[def] identifier[CREATE] ( identifier[self] , identifier[value] , identifier[offset] , identifier[size] ):
literal[string]
identifier[tx] = identifier[self] . identifier[world] . identifier[last_transaction]
identifier[address] = identifier[tx] . identifier[address]
keywo... | def CREATE(self, value, offset, size):
"""Create a new account with associated code"""
tx = self.world.last_transaction # At this point last and current tx are the same.
address = tx.address
if tx.result == 'RETURN':
self.world.set_code(tx.address, tx.return_data) # depends on [control=['if'],... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.