code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _wrap_client_error(e):
"""
Wrap botocore ClientError exception into ServerlessRepoClientError.
:param e: botocore exception
:type e: ClientError
:return: S3PermissionsRequired or InvalidS3UriError or general ServerlessRepoClientError
"""
error_code = e.response['Error']['Code']
mess... | def function[_wrap_client_error, parameter[e]]:
constant[
Wrap botocore ClientError exception into ServerlessRepoClientError.
:param e: botocore exception
:type e: ClientError
:return: S3PermissionsRequired or InvalidS3UriError or general ServerlessRepoClientError
]
variable[error_c... | keyword[def] identifier[_wrap_client_error] ( identifier[e] ):
literal[string]
identifier[error_code] = identifier[e] . identifier[response] [ literal[string] ][ literal[string] ]
identifier[message] = identifier[e] . identifier[response] [ literal[string] ][ literal[string] ]
keyword[if] ident... | def _wrap_client_error(e):
"""
Wrap botocore ClientError exception into ServerlessRepoClientError.
:param e: botocore exception
:type e: ClientError
:return: S3PermissionsRequired or InvalidS3UriError or general ServerlessRepoClientError
"""
error_code = e.response['Error']['Code']
mess... |
def get_airports(self, country):
"""Returns a list of all the airports
For a given country this returns a list of dicts, one for each airport, with information like the iata code of the airport etc
Args:
country (str): The country for which the airports will be fetched
Exam... | def function[get_airports, parameter[self, country]]:
constant[Returns a list of all the airports
For a given country this returns a list of dicts, one for each airport, with information like the iata code of the airport etc
Args:
country (str): The country for which the airports wi... | keyword[def] identifier[get_airports] ( identifier[self] , identifier[country] ):
literal[string]
identifier[url] = identifier[AIRPORT_BASE] . identifier[format] ( identifier[country] . identifier[replace] ( literal[string] , literal[string] ))
keyword[return] identifier[self] . identifie... | def get_airports(self, country):
"""Returns a list of all the airports
For a given country this returns a list of dicts, one for each airport, with information like the iata code of the airport etc
Args:
country (str): The country for which the airports will be fetched
Example:... |
def directory_complete(self, text, line, begidx, endidx):
"""Figure out what directories match the completion."""
return [filename for filename in self.filename_complete(text, line, begidx, endidx) if filename[-1] == '/'] | def function[directory_complete, parameter[self, text, line, begidx, endidx]]:
constant[Figure out what directories match the completion.]
return[<ast.ListComp object at 0x7da207f035e0>] | keyword[def] identifier[directory_complete] ( identifier[self] , identifier[text] , identifier[line] , identifier[begidx] , identifier[endidx] ):
literal[string]
keyword[return] [ identifier[filename] keyword[for] identifier[filename] keyword[in] identifier[self] . identifier[filename_complete]... | def directory_complete(self, text, line, begidx, endidx):
"""Figure out what directories match the completion."""
return [filename for filename in self.filename_complete(text, line, begidx, endidx) if filename[-1] == '/'] |
def status_icon(self):
'glyphicon for task status; requires bootstrap'
icon = self.status_icon_map.get(self.status.lower(),
self.unknown_icon)
style = self.status_style.get(self.status.lower(), '')
return mark_safe(
'<span class="glyphi... | def function[status_icon, parameter[self]]:
constant[glyphicon for task status; requires bootstrap]
variable[icon] assign[=] call[name[self].status_icon_map.get, parameter[call[name[self].status.lower, parameter[]], name[self].unknown_icon]]
variable[style] assign[=] call[name[self].status_style... | keyword[def] identifier[status_icon] ( identifier[self] ):
literal[string]
identifier[icon] = identifier[self] . identifier[status_icon_map] . identifier[get] ( identifier[self] . identifier[status] . identifier[lower] (),
identifier[self] . identifier[unknown_icon] )
identifier[s... | def status_icon(self):
"""glyphicon for task status; requires bootstrap"""
icon = self.status_icon_map.get(self.status.lower(), self.unknown_icon)
style = self.status_style.get(self.status.lower(), '')
return mark_safe('<span class="glyphicon %s %s" aria-hidden="true"></span>' % (icon, style)) |
def K_branch_diverging_Crane(D_run, D_branch, Q_run, Q_branch, angle=90):
r'''Returns the loss coefficient for the branch of a diverging tee or wye
according to the Crane method [1]_.
.. math::
K_{branch} = G\left[1 + H\left(\frac{Q_{branch}}{Q_{comb}
\beta_{branch}^2}\right)^2 - J\left... | def function[K_branch_diverging_Crane, parameter[D_run, D_branch, Q_run, Q_branch, angle]]:
constant[Returns the loss coefficient for the branch of a diverging tee or wye
according to the Crane method [1]_.
.. math::
K_{branch} = G\left[1 + H\left(\frac{Q_{branch}}{Q_{comb}
\beta_{b... | keyword[def] identifier[K_branch_diverging_Crane] ( identifier[D_run] , identifier[D_branch] , identifier[Q_run] , identifier[Q_branch] , identifier[angle] = literal[int] ):
literal[string]
identifier[beta] =( identifier[D_branch] / identifier[D_run] )
identifier[beta2] = identifier[beta] * identifier... | def K_branch_diverging_Crane(D_run, D_branch, Q_run, Q_branch, angle=90):
"""Returns the loss coefficient for the branch of a diverging tee or wye
according to the Crane method [1]_.
.. math::
K_{branch} = G\\left[1 + H\\left(\\frac{Q_{branch}}{Q_{comb}
\\beta_{branch}^2}\\right)^2 - J\... |
def _teardown(self):
"Handles the restoration of any potential global state set."
self.example.after(self.context)
if self.is_root_runner:
run.after_all.execute(self.context)
#self.context = self.context._parent
self.has_ran = True | def function[_teardown, parameter[self]]:
constant[Handles the restoration of any potential global state set.]
call[name[self].example.after, parameter[name[self].context]]
if name[self].is_root_runner begin[:]
call[name[run].after_all.execute, parameter[name[self].context]]
... | keyword[def] identifier[_teardown] ( identifier[self] ):
literal[string]
identifier[self] . identifier[example] . identifier[after] ( identifier[self] . identifier[context] )
keyword[if] identifier[self] . identifier[is_root_runner] :
identifier[run] . identifier[after_all] .... | def _teardown(self):
"""Handles the restoration of any potential global state set."""
self.example.after(self.context)
if self.is_root_runner:
run.after_all.execute(self.context) # depends on [control=['if'], data=[]]
#self.context = self.context._parent
self.has_ran = True |
def printWelcomeMessage(msg, place=10):
''' Print any welcome message '''
logging.debug('*' * 30)
welcome = ' ' * place
welcome+= msg
logging.debug(welcome)
logging.debug('*' * 30 + '\n') | def function[printWelcomeMessage, parameter[msg, place]]:
constant[ Print any welcome message ]
call[name[logging].debug, parameter[binary_operation[constant[*] * constant[30]]]]
variable[welcome] assign[=] binary_operation[constant[ ] * name[place]]
<ast.AugAssign object at 0x7da20c7c91e0>
... | keyword[def] identifier[printWelcomeMessage] ( identifier[msg] , identifier[place] = literal[int] ):
literal[string]
identifier[logging] . identifier[debug] ( literal[string] * literal[int] )
identifier[welcome] = literal[string] * identifier[place]
identifier[welcome] += identifier[msg]
i... | def printWelcomeMessage(msg, place=10):
""" Print any welcome message """
logging.debug('*' * 30)
welcome = ' ' * place
welcome += msg
logging.debug(welcome)
logging.debug('*' * 30 + '\n') |
def emboss_pepstats_on_fasta(infile, outfile='', outdir='', outext='.pepstats', force_rerun=False):
"""Run EMBOSS pepstats on a FASTA file.
Args:
infile: Path to FASTA file
outfile: Name of output file without extension
outdir: Path to output directory
outext: Extension of resul... | def function[emboss_pepstats_on_fasta, parameter[infile, outfile, outdir, outext, force_rerun]]:
constant[Run EMBOSS pepstats on a FASTA file.
Args:
infile: Path to FASTA file
outfile: Name of output file without extension
outdir: Path to output directory
outext: Extension o... | keyword[def] identifier[emboss_pepstats_on_fasta] ( identifier[infile] , identifier[outfile] = literal[string] , identifier[outdir] = literal[string] , identifier[outext] = literal[string] , identifier[force_rerun] = keyword[False] ):
literal[string]
identifier[outfile] = identifier[ssbio] . identifi... | def emboss_pepstats_on_fasta(infile, outfile='', outdir='', outext='.pepstats', force_rerun=False):
"""Run EMBOSS pepstats on a FASTA file.
Args:
infile: Path to FASTA file
outfile: Name of output file without extension
outdir: Path to output directory
outext: Extension of resul... |
def _load(self, load_dict):
"""Reconstructs the data and exploration array.
Checks if it can find the array identifier in the `load_dict`, i.e. '__rr__'.
If not calls :class:`~pypet.parameter.Parameter._load` of the parent class.
If the parameter is explored, the exploration range of a... | def function[_load, parameter[self, load_dict]]:
constant[Reconstructs the data and exploration array.
Checks if it can find the array identifier in the `load_dict`, i.e. '__rr__'.
If not calls :class:`~pypet.parameter.Parameter._load` of the parent class.
If the parameter is explored,... | keyword[def] identifier[_load] ( identifier[self] , identifier[load_dict] ):
literal[string]
keyword[if] identifier[self] . identifier[v_locked] :
keyword[raise] identifier[pex] . identifier[ParameterLockedException] ( literal[string] % identifier[self] . identifier[v_full_name] )
... | def _load(self, load_dict):
"""Reconstructs the data and exploration array.
Checks if it can find the array identifier in the `load_dict`, i.e. '__rr__'.
If not calls :class:`~pypet.parameter.Parameter._load` of the parent class.
If the parameter is explored, the exploration range of array... |
def _list_element_starts_with(items, needle):
"""True of any of the list elements starts with needle"""
for item in items:
if item.startswith(needle):
return True
return False | def function[_list_element_starts_with, parameter[items, needle]]:
constant[True of any of the list elements starts with needle]
for taget[name[item]] in starred[name[items]] begin[:]
if call[name[item].startswith, parameter[name[needle]]] begin[:]
return[constant[True]]
... | keyword[def] identifier[_list_element_starts_with] ( identifier[items] , identifier[needle] ):
literal[string]
keyword[for] identifier[item] keyword[in] identifier[items] :
keyword[if] identifier[item] . identifier[startswith] ( identifier[needle] ):
keyword[return... | def _list_element_starts_with(items, needle):
"""True of any of the list elements starts with needle"""
for item in items:
if item.startswith(needle):
return True # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['item']]
return False |
def formatted_str_to_val(data, format, enum_set=None):
""" Return an unsigned integer representation of the data given format specified.
:param data: a string holding the value to convert
:param format: a string holding a format which will be used to convert the data string
:param enum_set: an iterable... | def function[formatted_str_to_val, parameter[data, format, enum_set]]:
constant[ Return an unsigned integer representation of the data given format specified.
:param data: a string holding the value to convert
:param format: a string holding a format which will be used to convert the data string
:p... | keyword[def] identifier[formatted_str_to_val] ( identifier[data] , identifier[format] , identifier[enum_set] = keyword[None] ):
literal[string]
identifier[type] = identifier[format] [ literal[int] ]
identifier[bitwidth] = identifier[int] ( identifier[format] [ literal[int] :]. identifier[split] ( lite... | def formatted_str_to_val(data, format, enum_set=None):
""" Return an unsigned integer representation of the data given format specified.
:param data: a string holding the value to convert
:param format: a string holding a format which will be used to convert the data string
:param enum_set: an iterable... |
def add_walls(self):
"Put walls around the entire perimeter of the grid."
for x in range(self.width):
self.add_thing(Wall(), (x, 0))
self.add_thing(Wall(), (x, self.height-1))
for y in range(self.height):
self.add_thing(Wall(), (0, y))
self.add_thi... | def function[add_walls, parameter[self]]:
constant[Put walls around the entire perimeter of the grid.]
for taget[name[x]] in starred[call[name[range], parameter[name[self].width]]] begin[:]
call[name[self].add_thing, parameter[call[name[Wall], parameter[]], tuple[[<ast.Name object at 0x7... | keyword[def] identifier[add_walls] ( identifier[self] ):
literal[string]
keyword[for] identifier[x] keyword[in] identifier[range] ( identifier[self] . identifier[width] ):
identifier[self] . identifier[add_thing] ( identifier[Wall] (),( identifier[x] , literal[int] ))
i... | def add_walls(self):
"""Put walls around the entire perimeter of the grid."""
for x in range(self.width):
self.add_thing(Wall(), (x, 0))
self.add_thing(Wall(), (x, self.height - 1)) # depends on [control=['for'], data=['x']]
for y in range(self.height):
self.add_thing(Wall(), (0, y)... |
def prepare_replicant_order_object(manager, snapshot_schedule, location,
tier, volume, volume_type):
"""Prepare the order object which is submitted to the placeOrder() method
:param manager: The File or Block manager calling this function
:param snapshot_schedule: The pri... | def function[prepare_replicant_order_object, parameter[manager, snapshot_schedule, location, tier, volume, volume_type]]:
constant[Prepare the order object which is submitted to the placeOrder() method
:param manager: The File or Block manager calling this function
:param snapshot_schedule: The primary... | keyword[def] identifier[prepare_replicant_order_object] ( identifier[manager] , identifier[snapshot_schedule] , identifier[location] ,
identifier[tier] , identifier[volume] , identifier[volume_type] ):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[volume] keywor... | def prepare_replicant_order_object(manager, snapshot_schedule, location, tier, volume, volume_type):
"""Prepare the order object which is submitted to the placeOrder() method
:param manager: The File or Block manager calling this function
:param snapshot_schedule: The primary volume's snapshot
... |
def ahrs_encode(self, omegaIx, omegaIy, omegaIz, accel_weight, renorm_val, error_rp, error_yaw):
'''
Status of DCM attitude estimator
omegaIx : X gyro drift estimate rad/s (float)
omegaIy : Y gyro drift estimate rad/s (... | def function[ahrs_encode, parameter[self, omegaIx, omegaIy, omegaIz, accel_weight, renorm_val, error_rp, error_yaw]]:
constant[
Status of DCM attitude estimator
omegaIx : X gyro drift estimate rad/s (float)
omegaIy : Y gyro dri... | keyword[def] identifier[ahrs_encode] ( identifier[self] , identifier[omegaIx] , identifier[omegaIy] , identifier[omegaIz] , identifier[accel_weight] , identifier[renorm_val] , identifier[error_rp] , identifier[error_yaw] ):
literal[string]
keyword[return] identifier[MAVLink_ahrs_me... | def ahrs_encode(self, omegaIx, omegaIy, omegaIz, accel_weight, renorm_val, error_rp, error_yaw):
"""
Status of DCM attitude estimator
omegaIx : X gyro drift estimate rad/s (float)
omegaIy : Y gyro drift estimate rad/s (float)
... |
def filename_match(fsearch, filename, width, height):
'''
<nickname>@({width}x{height}|auto).(png|jpg|jpeg)
'''
fsearch = clean_path(fsearch)
filename = clean_path(filename)
if fsearch == filename:
return True
if fsearch.find('@') == -1:
return False
basename, fileext = ... | def function[filename_match, parameter[fsearch, filename, width, height]]:
constant[
<nickname>@({width}x{height}|auto).(png|jpg|jpeg)
]
variable[fsearch] assign[=] call[name[clean_path], parameter[name[fsearch]]]
variable[filename] assign[=] call[name[clean_path], parameter[name[filenam... | keyword[def] identifier[filename_match] ( identifier[fsearch] , identifier[filename] , identifier[width] , identifier[height] ):
literal[string]
identifier[fsearch] = identifier[clean_path] ( identifier[fsearch] )
identifier[filename] = identifier[clean_path] ( identifier[filename] )
keyword[if] ... | def filename_match(fsearch, filename, width, height):
"""
<nickname>@({width}x{height}|auto).(png|jpg|jpeg)
"""
fsearch = clean_path(fsearch)
filename = clean_path(filename)
if fsearch == filename:
return True # depends on [control=['if'], data=[]]
if fsearch.find('@') == -1:
... |
def up_to_date(self):
"""Check if Team Password Manager is up to date."""
VersionInfo = self.get_latest_version()
CurrentVersion = VersionInfo.get('version')
LatestVersion = VersionInfo.get('latest_version')
if CurrentVersion == LatestVersion:
log.info('TeamPasswordM... | def function[up_to_date, parameter[self]]:
constant[Check if Team Password Manager is up to date.]
variable[VersionInfo] assign[=] call[name[self].get_latest_version, parameter[]]
variable[CurrentVersion] assign[=] call[name[VersionInfo].get, parameter[constant[version]]]
variable[Latest... | keyword[def] identifier[up_to_date] ( identifier[self] ):
literal[string]
identifier[VersionInfo] = identifier[self] . identifier[get_latest_version] ()
identifier[CurrentVersion] = identifier[VersionInfo] . identifier[get] ( literal[string] )
identifier[LatestVersion] = identifie... | def up_to_date(self):
"""Check if Team Password Manager is up to date."""
VersionInfo = self.get_latest_version()
CurrentVersion = VersionInfo.get('version')
LatestVersion = VersionInfo.get('latest_version')
if CurrentVersion == LatestVersion:
log.info('TeamPasswordManager is up-to-date!')
... |
def write_table(page, headers, data, cl=''):
"""
Write table in html
"""
page.table(class_=cl)
# list
if cl=='list':
for i in range(len(headers)):
page.tr()
page.th()
page.add('%s' % headers[i])
page.th.close()
page.td()
... | def function[write_table, parameter[page, headers, data, cl]]:
constant[
Write table in html
]
call[name[page].table, parameter[]]
if compare[name[cl] equal[==] constant[list]] begin[:]
for taget[name[i]] in starred[call[name[range], parameter[call[name[len], parameter[na... | keyword[def] identifier[write_table] ( identifier[page] , identifier[headers] , identifier[data] , identifier[cl] = literal[string] ):
literal[string]
identifier[page] . identifier[table] ( identifier[class_] = identifier[cl] )
keyword[if] identifier[cl] == literal[string] :
keyword[... | def write_table(page, headers, data, cl=''):
"""
Write table in html
"""
page.table(class_=cl)
# list
if cl == 'list':
for i in range(len(headers)):
page.tr()
page.th()
page.add('%s' % headers[i])
page.th.close()
page.td()
... |
def qos_red_profile_drop_probability(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos")
red_profile = ET.SubElement(qos, "red-profile")
profile_id_key = ET.SubElement(red_p... | def function[qos_red_profile_drop_probability, 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]]]
variable[red_pr... | keyword[def] identifier[qos_red_profile_drop_probability] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[qos] = identifier[ET] . identifier[SubElement] ( identifier[config] , literal[stri... | def qos_red_profile_drop_probability(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
qos = ET.SubElement(config, 'qos', xmlns='urn:brocade.com:mgmt:brocade-qos')
red_profile = ET.SubElement(qos, 'red-profile')
profile_id_key = ET.SubElement(red_profile, 'profile-id'... |
def answers(self):
"""获取话题下所有答案(按时间降序排列)
:return: 话题下所有答案,返回生成器
:rtype: Answer.Iterable
"""
from .question import Question
from .answer import Answer
from .author import Author, ANONYMOUS
newest_url = Topic_Newest_Url.format(self.id)
params = {'s... | def function[answers, parameter[self]]:
constant[获取话题下所有答案(按时间降序排列)
:return: 话题下所有答案,返回生成器
:rtype: Answer.Iterable
]
from relative_module[question] import module[Question]
from relative_module[answer] import module[Answer]
from relative_module[author] import module[Author], ... | keyword[def] identifier[answers] ( identifier[self] ):
literal[string]
keyword[from] . identifier[question] keyword[import] identifier[Question]
keyword[from] . identifier[answer] keyword[import] identifier[Answer]
keyword[from] . identifier[author] keyword[import] identif... | def answers(self):
"""获取话题下所有答案(按时间降序排列)
:return: 话题下所有答案,返回生成器
:rtype: Answer.Iterable
"""
from .question import Question
from .answer import Answer
from .author import Author, ANONYMOUS
newest_url = Topic_Newest_Url.format(self.id)
params = {'start': 0, '_xsrf': self.x... |
def parse_dimension(self, node):
"""
Parses <Dimension>
@param node: Node containing the <Dimension> element
@type node: xml.etree.Element
@raise ParseError: When the name is not a string or if the
dimension is not a signed integer.
"""
try:
... | def function[parse_dimension, parameter[self, node]]:
constant[
Parses <Dimension>
@param node: Node containing the <Dimension> element
@type node: xml.etree.Element
@raise ParseError: When the name is not a string or if the
dimension is not a signed integer.
]
... | keyword[def] identifier[parse_dimension] ( identifier[self] , identifier[node] ):
literal[string]
keyword[try] :
identifier[name] = identifier[node] . identifier[lattrib] [ literal[string] ]
keyword[except] :
identifier[self] . identifier[raise_error] ( literal[s... | def parse_dimension(self, node):
"""
Parses <Dimension>
@param node: Node containing the <Dimension> element
@type node: xml.etree.Element
@raise ParseError: When the name is not a string or if the
dimension is not a signed integer.
"""
try:
name = node.... |
def _get_setup(self, result):
"""Internal method which process the results from the server."""
self.__devices = {}
if ('setup' not in result.keys() or
'devices' not in result['setup'].keys()):
raise Exception(
"Did not find device definition.")
... | def function[_get_setup, parameter[self, result]]:
constant[Internal method which process the results from the server.]
name[self].__devices assign[=] dictionary[[], []]
if <ast.BoolOp object at 0x7da1b0c14430> begin[:]
<ast.Raise object at 0x7da1b0c150c0>
for taget[name[device_d... | keyword[def] identifier[_get_setup] ( identifier[self] , identifier[result] ):
literal[string]
identifier[self] . identifier[__devices] ={}
keyword[if] ( literal[string] keyword[not] keyword[in] identifier[result] . identifier[keys] () keyword[or]
literal[string] keyword[not... | def _get_setup(self, result):
"""Internal method which process the results from the server."""
self.__devices = {}
if 'setup' not in result.keys() or 'devices' not in result['setup'].keys():
raise Exception('Did not find device definition.') # depends on [control=['if'], data=[]]
for device_dat... |
def get_object(self, view_kwargs, qs=None):
"""Retrieve an object through sqlalchemy
:params dict view_kwargs: kwargs from the resource view
:return DeclarativeMeta: an object from sqlalchemy
"""
self.before_get_object(view_kwargs)
id_field = getattr(self, 'id_field', i... | def function[get_object, parameter[self, view_kwargs, qs]]:
constant[Retrieve an object through sqlalchemy
:params dict view_kwargs: kwargs from the resource view
:return DeclarativeMeta: an object from sqlalchemy
]
call[name[self].before_get_object, parameter[name[view_kwargs]]... | keyword[def] identifier[get_object] ( identifier[self] , identifier[view_kwargs] , identifier[qs] = keyword[None] ):
literal[string]
identifier[self] . identifier[before_get_object] ( identifier[view_kwargs] )
identifier[id_field] = identifier[getattr] ( identifier[self] , literal[string]... | def get_object(self, view_kwargs, qs=None):
"""Retrieve an object through sqlalchemy
:params dict view_kwargs: kwargs from the resource view
:return DeclarativeMeta: an object from sqlalchemy
"""
self.before_get_object(view_kwargs)
id_field = getattr(self, 'id_field', inspect(self.m... |
def crud_mutation_name(action, model):
"""
This function returns the name of a mutation that performs the specified
crud action on the given model service
"""
model_string = get_model_string(model)
# make sure the mutation name is correctly camelcases
model_string = model_string[0].u... | def function[crud_mutation_name, parameter[action, model]]:
constant[
This function returns the name of a mutation that performs the specified
crud action on the given model service
]
variable[model_string] assign[=] call[name[get_model_string], parameter[name[model]]]
variab... | keyword[def] identifier[crud_mutation_name] ( identifier[action] , identifier[model] ):
literal[string]
identifier[model_string] = identifier[get_model_string] ( identifier[model] )
identifier[model_string] = identifier[model_string] [ literal[int] ]. identifier[upper] ()+ identifier[model_string... | def crud_mutation_name(action, model):
"""
This function returns the name of a mutation that performs the specified
crud action on the given model service
"""
model_string = get_model_string(model)
# make sure the mutation name is correctly camelcases
model_string = model_string[0].u... |
def _faster_to_representation(self, instance):
"""Modified to_representation with optimizations.
1) Returns a plain old dict as opposed to OrderedDict.
(Constructing ordered dict is ~100x slower than `{}`.)
2) Ensure we use a cached list of fields
(this optimization exis... | def function[_faster_to_representation, parameter[self, instance]]:
constant[Modified to_representation with optimizations.
1) Returns a plain old dict as opposed to OrderedDict.
(Constructing ordered dict is ~100x slower than `{}`.)
2) Ensure we use a cached list of fields
... | keyword[def] identifier[_faster_to_representation] ( identifier[self] , identifier[instance] ):
literal[string]
identifier[ret] ={}
identifier[fields] = identifier[self] . identifier[_readable_fields]
identifier[is_fast] = identifier[isinstance] ( identifier[instance] , identif... | def _faster_to_representation(self, instance):
"""Modified to_representation with optimizations.
1) Returns a plain old dict as opposed to OrderedDict.
(Constructing ordered dict is ~100x slower than `{}`.)
2) Ensure we use a cached list of fields
(this optimization exists i... |
def make_oracle(input_qubits,
output_qubit,
secret_factor_bits,
secret_bias_bit):
"""Gates implementing the function f(a) = a·factors + bias (mod 2)."""
if secret_bias_bit:
yield cirq.X(output_qubit)
for qubit, bit in zip(input_qubits, secret_factor_... | def function[make_oracle, parameter[input_qubits, output_qubit, secret_factor_bits, secret_bias_bit]]:
constant[Gates implementing the function f(a) = a·factors + bias (mod 2).]
if name[secret_bias_bit] begin[:]
<ast.Yield object at 0x7da1b1cc1ed0>
for taget[tuple[[<ast.Name obje... | keyword[def] identifier[make_oracle] ( identifier[input_qubits] ,
identifier[output_qubit] ,
identifier[secret_factor_bits] ,
identifier[secret_bias_bit] ):
literal[string]
keyword[if] identifier[secret_bias_bit] :
keyword[yield] identifier[cirq] . identifier[X] ( identifier[output_qubit] )
... | def make_oracle(input_qubits, output_qubit, secret_factor_bits, secret_bias_bit):
"""Gates implementing the function f(a) = a·factors + bias (mod 2)."""
if secret_bias_bit:
yield cirq.X(output_qubit) # depends on [control=['if'], data=[]]
for (qubit, bit) in zip(input_qubits, secret_factor_bits):
... |
def shared_memory(attrs=None, where=None):
'''
Return shared_memory information from osquery
CLI Example:
.. code-block:: bash
salt '*' osquery.shared_memory
'''
if __grains__['os_family'] in ['RedHat', 'Debian']:
return _osquery_cmd(table='shared_memory', attrs=attrs, where=w... | def function[shared_memory, parameter[attrs, where]]:
constant[
Return shared_memory information from osquery
CLI Example:
.. code-block:: bash
salt '*' osquery.shared_memory
]
if compare[call[name[__grains__]][constant[os_family]] in list[[<ast.Constant object at 0x7da1b20083... | keyword[def] identifier[shared_memory] ( identifier[attrs] = keyword[None] , identifier[where] = keyword[None] ):
literal[string]
keyword[if] identifier[__grains__] [ literal[string] ] keyword[in] [ literal[string] , literal[string] ]:
keyword[return] identifier[_osquery_cmd] ( identifier[table]... | def shared_memory(attrs=None, where=None):
"""
Return shared_memory information from osquery
CLI Example:
.. code-block:: bash
salt '*' osquery.shared_memory
"""
if __grains__['os_family'] in ['RedHat', 'Debian']:
return _osquery_cmd(table='shared_memory', attrs=attrs, where=w... |
def ui_open(*files):
"""Attempts to open the given files using the preferred desktop viewer or editor.
:raises :class:`OpenError`: if there is a problem opening any of the files.
"""
if files:
osname = get_os_name()
opener = _OPENER_BY_OS.get(osname)
if opener:
opener(files)
else:
r... | def function[ui_open, parameter[]]:
constant[Attempts to open the given files using the preferred desktop viewer or editor.
:raises :class:`OpenError`: if there is a problem opening any of the files.
]
if name[files] begin[:]
variable[osname] assign[=] call[name[get_os_name], parame... | keyword[def] identifier[ui_open] (* identifier[files] ):
literal[string]
keyword[if] identifier[files] :
identifier[osname] = identifier[get_os_name] ()
identifier[opener] = identifier[_OPENER_BY_OS] . identifier[get] ( identifier[osname] )
keyword[if] identifier[opener] :
identifier[op... | def ui_open(*files):
"""Attempts to open the given files using the preferred desktop viewer or editor.
:raises :class:`OpenError`: if there is a problem opening any of the files.
"""
if files:
osname = get_os_name()
opener = _OPENER_BY_OS.get(osname)
if opener:
opener(fi... |
def beta_code(self, text):
"""Replace method. Note: regex.subn() returns a tuple (new_string,
number_of_subs_made).
"""
text = text.upper().replace('-', '')
for (pattern, repl) in self.pattern1:
text = pattern.subn(repl, text)[0]
for (pattern, repl) in self.pa... | def function[beta_code, parameter[self, text]]:
constant[Replace method. Note: regex.subn() returns a tuple (new_string,
number_of_subs_made).
]
variable[text] assign[=] call[call[name[text].upper, parameter[]].replace, parameter[constant[-], constant[]]]
for taget[tuple[[<ast.Na... | keyword[def] identifier[beta_code] ( identifier[self] , identifier[text] ):
literal[string]
identifier[text] = identifier[text] . identifier[upper] (). identifier[replace] ( literal[string] , literal[string] )
keyword[for] ( identifier[pattern] , identifier[repl] ) keyword[in] identifier[... | def beta_code(self, text):
"""Replace method. Note: regex.subn() returns a tuple (new_string,
number_of_subs_made).
"""
text = text.upper().replace('-', '')
for (pattern, repl) in self.pattern1:
text = pattern.subn(repl, text)[0] # depends on [control=['for'], data=[]]
for (patt... |
def use_all_categories(self):
'''
Returns
-------
PriorFactory
'''
term_df = self.term_ranker.get_ranks()
self.priors += term_df.sum(axis=1).fillna(0.)
return self | def function[use_all_categories, parameter[self]]:
constant[
Returns
-------
PriorFactory
]
variable[term_df] assign[=] call[name[self].term_ranker.get_ranks, parameter[]]
<ast.AugAssign object at 0x7da1b1b84fd0>
return[name[self]] | keyword[def] identifier[use_all_categories] ( identifier[self] ):
literal[string]
identifier[term_df] = identifier[self] . identifier[term_ranker] . identifier[get_ranks] ()
identifier[self] . identifier[priors] += identifier[term_df] . identifier[sum] ( identifier[axis] = literal[int] ). identifier[fillna]... | def use_all_categories(self):
"""
Returns
-------
PriorFactory
"""
term_df = self.term_ranker.get_ranks()
self.priors += term_df.sum(axis=1).fillna(0.0)
return self |
def pre_save(sender, model):
""" Hash the password if being changed """
if isinstance(model, Model) and 'password' in model.dirty_fields:
model.salt, model.password = gen_salt_and_hash(model.password) | def function[pre_save, parameter[sender, model]]:
constant[ Hash the password if being changed ]
if <ast.BoolOp object at 0x7da2054a5840> begin[:]
<ast.Tuple object at 0x7da2054a7340> assign[=] call[name[gen_salt_and_hash], parameter[name[model].password]] | keyword[def] identifier[pre_save] ( identifier[sender] , identifier[model] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[model] , identifier[Model] ) keyword[and] literal[string] keyword[in] identifier[model] . identifier[dirty_fields] :
identifier[model] . identifier[sal... | def pre_save(sender, model):
""" Hash the password if being changed """
if isinstance(model, Model) and 'password' in model.dirty_fields:
(model.salt, model.password) = gen_salt_and_hash(model.password) # depends on [control=['if'], data=[]] |
def fold_text_ctx(self, line):
"""
Folds text, via :class:`DomTerm`, if available.
Notes that this temporarily overwrites self.lines.
:param str line: always visible
"""
if not self.dom_term:
self.__call__(line)
yield
return
se... | def function[fold_text_ctx, parameter[self, line]]:
constant[
Folds text, via :class:`DomTerm`, if available.
Notes that this temporarily overwrites self.lines.
:param str line: always visible
]
if <ast.UnaryOp object at 0x7da1b24fe830> begin[:]
call[name... | keyword[def] identifier[fold_text_ctx] ( identifier[self] , identifier[line] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[dom_term] :
identifier[self] . identifier[__call__] ( identifier[line] )
keyword[yield]
keyword[return]
... | def fold_text_ctx(self, line):
"""
Folds text, via :class:`DomTerm`, if available.
Notes that this temporarily overwrites self.lines.
:param str line: always visible
"""
if not self.dom_term:
self.__call__(line)
yield
return # depends on [control=['if'],... |
def pin(value):
'''A small pin that represents the result of the build process'''
if value is False:
return draw_pin('Build Failed', 'red')
elif value is True:
return draw_pin('Build Passed')
elif value is NOT_FOUND:
return draw_pin('Build N / A', 'lightGray', 'black')
return... | def function[pin, parameter[value]]:
constant[A small pin that represents the result of the build process]
if compare[name[value] is constant[False]] begin[:]
return[call[name[draw_pin], parameter[constant[Build Failed], constant[red]]]]
return[call[name[draw_pin], parameter[constant[In prog... | keyword[def] identifier[pin] ( identifier[value] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[False] :
keyword[return] identifier[draw_pin] ( literal[string] , literal[string] )
keyword[elif] identifier[value] keyword[is] keyword[True] :
keyword[return]... | def pin(value):
"""A small pin that represents the result of the build process"""
if value is False:
return draw_pin('Build Failed', 'red') # depends on [control=['if'], data=[]]
elif value is True:
return draw_pin('Build Passed') # depends on [control=['if'], data=[]]
elif value is NO... |
def set_hyperparams(self, new_params):
"""Set the (free) hyperparameters.
Parameters
----------
new_params : :py:class:`Array` or other Array-like
New values of the free parameters.
Raises
------
ValueError
If the length o... | def function[set_hyperparams, parameter[self, new_params]]:
constant[Set the (free) hyperparameters.
Parameters
----------
new_params : :py:class:`Array` or other Array-like
New values of the free parameters.
Raises
------
ValueError
... | keyword[def] identifier[set_hyperparams] ( identifier[self] , identifier[new_params] ):
literal[string]
identifier[new_params] = identifier[scipy] . identifier[asarray] ( identifier[new_params] , identifier[dtype] = identifier[float] )
keyword[if] identifier[len] ( identifier[new_params]... | def set_hyperparams(self, new_params):
"""Set the (free) hyperparameters.
Parameters
----------
new_params : :py:class:`Array` or other Array-like
New values of the free parameters.
Raises
------
ValueError
If the length of `n... |
def _get_admin_app_list_url(self, model, context):
"""
Returns the admin change url.
"""
app_label = model._meta.app_label
return reverse('%s:app_list' % get_admin_site_name(context),
args=(app_label,)) | def function[_get_admin_app_list_url, parameter[self, model, context]]:
constant[
Returns the admin change url.
]
variable[app_label] assign[=] name[model]._meta.app_label
return[call[name[reverse], parameter[binary_operation[constant[%s:app_list] <ast.Mod object at 0x7da2590d6920> c... | keyword[def] identifier[_get_admin_app_list_url] ( identifier[self] , identifier[model] , identifier[context] ):
literal[string]
identifier[app_label] = identifier[model] . identifier[_meta] . identifier[app_label]
keyword[return] identifier[reverse] ( literal[string] % identifier[get_ad... | def _get_admin_app_list_url(self, model, context):
"""
Returns the admin change url.
"""
app_label = model._meta.app_label
return reverse('%s:app_list' % get_admin_site_name(context), args=(app_label,)) |
def add_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass."""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None)
return metaclass(cls.__name__, cls.__bases__, orig_vars)
return wrap... | def function[add_metaclass, parameter[metaclass]]:
constant[Class decorator for creating a class with a metaclass.]
def function[wrapper, parameter[cls]]:
variable[orig_vars] assign[=] call[name[cls].__dict__.copy, parameter[]]
call[name[orig_vars].pop, parameter[constant... | keyword[def] identifier[add_metaclass] ( identifier[metaclass] ):
literal[string]
keyword[def] identifier[wrapper] ( identifier[cls] ):
identifier[orig_vars] = identifier[cls] . identifier[__dict__] . identifier[copy] ()
identifier[orig_vars] . identifier[pop] ( literal[string] , keyword... | def add_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass."""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None)
return metaclass(cls.__name__, cls.__bases__, orig_vars)
return wra... |
def write_table(self):
"""
|write_table|.
.. note::
- |None| values are written as an empty string.
"""
super(TextTableWriter, self).write_table()
if self.is_write_null_line_after_table:
self.write_null_line() | def function[write_table, parameter[self]]:
constant[
|write_table|.
.. note::
- |None| values are written as an empty string.
]
call[call[name[super], parameter[name[TextTableWriter], name[self]]].write_table, parameter[]]
if name[self].is_write_null_line_af... | keyword[def] identifier[write_table] ( identifier[self] ):
literal[string]
identifier[super] ( identifier[TextTableWriter] , identifier[self] ). identifier[write_table] ()
keyword[if] identifier[self] . identifier[is_write_null_line_after_table] :
identifier[self] . identifi... | def write_table(self):
"""
|write_table|.
.. note::
- |None| values are written as an empty string.
"""
super(TextTableWriter, self).write_table()
if self.is_write_null_line_after_table:
self.write_null_line() # depends on [control=['if'], data=[]] |
def _filter_values(vals, vlist=None, must=False):
""" Removes values from *vals* that does not appear in vlist
:param vals: The values that are to be filtered
:param vlist: required or optional value
:param must: Whether the allowed values must appear
:return: The set of values after filtering
... | def function[_filter_values, parameter[vals, vlist, must]]:
constant[ Removes values from *vals* that does not appear in vlist
:param vals: The values that are to be filtered
:param vlist: required or optional value
:param must: Whether the allowed values must appear
:return: The set of values ... | keyword[def] identifier[_filter_values] ( identifier[vals] , identifier[vlist] = keyword[None] , identifier[must] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[vlist] :
keyword[return] identifier[vals]
keyword[if] identifier[isinstance] ( identifier[vlist] , i... | def _filter_values(vals, vlist=None, must=False):
""" Removes values from *vals* that does not appear in vlist
:param vals: The values that are to be filtered
:param vlist: required or optional value
:param must: Whether the allowed values must appear
:return: The set of values after filtering
... |
def add_formats_by_name(self, rfmt_list):
"""
adds formats by short label descriptors, such as 'txt', 'json', or
'html'
"""
for fmt in rfmt_list:
if fmt == "json":
self.add_report_format(JSONReportFormat)
elif fmt in ("txt", "text"):
... | def function[add_formats_by_name, parameter[self, rfmt_list]]:
constant[
adds formats by short label descriptors, such as 'txt', 'json', or
'html'
]
for taget[name[fmt]] in starred[name[rfmt_list]] begin[:]
if compare[name[fmt] equal[==] constant[json]] begin[:]
... | keyword[def] identifier[add_formats_by_name] ( identifier[self] , identifier[rfmt_list] ):
literal[string]
keyword[for] identifier[fmt] keyword[in] identifier[rfmt_list] :
keyword[if] identifier[fmt] == literal[string] :
identifier[self] . identifier[add_report_fo... | def add_formats_by_name(self, rfmt_list):
"""
adds formats by short label descriptors, such as 'txt', 'json', or
'html'
"""
for fmt in rfmt_list:
if fmt == 'json':
self.add_report_format(JSONReportFormat) # depends on [control=['if'], data=[]]
elif fmt in ('t... |
def remove(self, key, value):
"""
Transactional implementation of :func:`MultiMap.remove(key, value)
<hazelcast.proxy.multi_map.MultiMap.remove>`
:param key: (object), the key of the entry to remove.
:param value: (object), the value of the entry to remove.
:return:
... | def function[remove, parameter[self, key, value]]:
constant[
Transactional implementation of :func:`MultiMap.remove(key, value)
<hazelcast.proxy.multi_map.MultiMap.remove>`
:param key: (object), the key of the entry to remove.
:param value: (object), the value of the entry to re... | keyword[def] identifier[remove] ( identifier[self] , identifier[key] , identifier[value] ):
literal[string]
identifier[check_not_none] ( identifier[key] , literal[string] )
identifier[check_not_none] ( identifier[value] , literal[string] )
keyword[return] identifier[self] . ident... | def remove(self, key, value):
"""
Transactional implementation of :func:`MultiMap.remove(key, value)
<hazelcast.proxy.multi_map.MultiMap.remove>`
:param key: (object), the key of the entry to remove.
:param value: (object), the value of the entry to remove.
:return:
... |
def transmit(self, what=None, to_whom=None):
"""Transmit one or more infos from one node to another.
"what" dictates which infos are sent, it can be:
(1) None (in which case the node's _what method is called).
(2) an Info (in which case the node transmits the info)
(... | def function[transmit, parameter[self, what, to_whom]]:
constant[Transmit one or more infos from one node to another.
"what" dictates which infos are sent, it can be:
(1) None (in which case the node's _what method is called).
(2) an Info (in which case the node transmits the in... | keyword[def] identifier[transmit] ( identifier[self] , identifier[what] = keyword[None] , identifier[to_whom] = keyword[None] ):
literal[string]
identifier[what] = identifier[self] . identifier[flatten] ([ identifier[what] ])
keyword[for] identifier[i] keyword[in] identifier[ra... | def transmit(self, what=None, to_whom=None):
"""Transmit one or more infos from one node to another.
"what" dictates which infos are sent, it can be:
(1) None (in which case the node's _what method is called).
(2) an Info (in which case the node transmits the info)
(3) a... |
def published(self, for_user=None):
"""
For non-staff users, return items with a published status and
whose publish and expiry dates fall before and after the
current date when specified.
"""
from yacms.core.models import CONTENT_STATUS_PUBLISHED
if for_user is no... | def function[published, parameter[self, for_user]]:
constant[
For non-staff users, return items with a published status and
whose publish and expiry dates fall before and after the
current date when specified.
]
from relative_module[yacms.core.models] import module[CONTENT_ST... | keyword[def] identifier[published] ( identifier[self] , identifier[for_user] = keyword[None] ):
literal[string]
keyword[from] identifier[yacms] . identifier[core] . identifier[models] keyword[import] identifier[CONTENT_STATUS_PUBLISHED]
keyword[if] identifier[for_user] keyword[is] k... | def published(self, for_user=None):
"""
For non-staff users, return items with a published status and
whose publish and expiry dates fall before and after the
current date when specified.
"""
from yacms.core.models import CONTENT_STATUS_PUBLISHED
if for_user is not None and f... |
def calc_buffered_bounds(
format, bounds, meters_per_pixel_dim, layer_name, geometry_type,
buffer_cfg):
"""
Calculate the buffered bounds per format per layer based on config.
"""
if not buffer_cfg:
return bounds
format_buffer_cfg = buffer_cfg.get(format.extension)
if f... | def function[calc_buffered_bounds, parameter[format, bounds, meters_per_pixel_dim, layer_name, geometry_type, buffer_cfg]]:
constant[
Calculate the buffered bounds per format per layer based on config.
]
if <ast.UnaryOp object at 0x7da20c6c65c0> begin[:]
return[name[bounds]]
vari... | keyword[def] identifier[calc_buffered_bounds] (
identifier[format] , identifier[bounds] , identifier[meters_per_pixel_dim] , identifier[layer_name] , identifier[geometry_type] ,
identifier[buffer_cfg] ):
literal[string]
keyword[if] keyword[not] identifier[buffer_cfg] :
keyword[return] identi... | def calc_buffered_bounds(format, bounds, meters_per_pixel_dim, layer_name, geometry_type, buffer_cfg):
"""
Calculate the buffered bounds per format per layer based on config.
"""
if not buffer_cfg:
return bounds # depends on [control=['if'], data=[]]
format_buffer_cfg = buffer_cfg.get(forma... |
def is_invalid_marker(cls, text):
"""
Validate text as a PEP 426 environment marker; return an exception
if invalid or False otherwise.
"""
try:
cls.evaluate_marker(text)
except SyntaxError as e:
return cls.normalize_exception(e)
return Fal... | def function[is_invalid_marker, parameter[cls, text]]:
constant[
Validate text as a PEP 426 environment marker; return an exception
if invalid or False otherwise.
]
<ast.Try object at 0x7da18f720070>
return[constant[False]] | keyword[def] identifier[is_invalid_marker] ( identifier[cls] , identifier[text] ):
literal[string]
keyword[try] :
identifier[cls] . identifier[evaluate_marker] ( identifier[text] )
keyword[except] identifier[SyntaxError] keyword[as] identifier[e] :
keyword[retu... | def is_invalid_marker(cls, text):
"""
Validate text as a PEP 426 environment marker; return an exception
if invalid or False otherwise.
"""
try:
cls.evaluate_marker(text) # depends on [control=['try'], data=[]]
except SyntaxError as e:
return cls.normalize_exception(... |
def write_byte(self, address, value):
"""Writes the byte to unaddressed register in a device. """
LOGGER.debug("Writing byte %s to device %s!", bin(value), hex(address))
return self.driver.write_byte(address, value) | def function[write_byte, parameter[self, address, value]]:
constant[Writes the byte to unaddressed register in a device. ]
call[name[LOGGER].debug, parameter[constant[Writing byte %s to device %s!], call[name[bin], parameter[name[value]]], call[name[hex], parameter[name[address]]]]]
return[call[name... | keyword[def] identifier[write_byte] ( identifier[self] , identifier[address] , identifier[value] ):
literal[string]
identifier[LOGGER] . identifier[debug] ( literal[string] , identifier[bin] ( identifier[value] ), identifier[hex] ( identifier[address] ))
keyword[return] identifier[self] .... | def write_byte(self, address, value):
"""Writes the byte to unaddressed register in a device. """
LOGGER.debug('Writing byte %s to device %s!', bin(value), hex(address))
return self.driver.write_byte(address, value) |
def params(dirnames, param_func, t_steady=None):
"""Calculate a parameter of a set of model output directories,
for a measure function which returns an associated uncertainty.
Parameters
----------
dirnames: list[str]
Model output directory paths.
param_func: function
Function w... | def function[params, parameter[dirnames, param_func, t_steady]]:
constant[Calculate a parameter of a set of model output directories,
for a measure function which returns an associated uncertainty.
Parameters
----------
dirnames: list[str]
Model output directory paths.
param_func: f... | keyword[def] identifier[params] ( identifier[dirnames] , identifier[param_func] , identifier[t_steady] = keyword[None] ):
literal[string]
keyword[return] identifier[np] . identifier[array] ([ identifier[param_func] ( identifier[get_recent_model] ( identifier[d] )) keyword[for] identifier[d] keyword[in] ... | def params(dirnames, param_func, t_steady=None):
"""Calculate a parameter of a set of model output directories,
for a measure function which returns an associated uncertainty.
Parameters
----------
dirnames: list[str]
Model output directory paths.
param_func: function
Function w... |
def find_vc_pdir_vswhere(msvc_version):
"""
Find the MSVC product directory using vswhere.exe .
Run it asking for specified version and get MSVS install location
:param msvc_version:
:return: MSVC install dir
"""
vswhere_path = os.path.join(
'C:\\',
'Program Files (x86)',
... | def function[find_vc_pdir_vswhere, parameter[msvc_version]]:
constant[
Find the MSVC product directory using vswhere.exe .
Run it asking for specified version and get MSVS install location
:param msvc_version:
:return: MSVC install dir
]
variable[vswhere_path] assign[=] call[name[os... | keyword[def] identifier[find_vc_pdir_vswhere] ( identifier[msvc_version] ):
literal[string]
identifier[vswhere_path] = identifier[os] . identifier[path] . identifier[join] (
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
literal[string]
)
identifi... | def find_vc_pdir_vswhere(msvc_version):
"""
Find the MSVC product directory using vswhere.exe .
Run it asking for specified version and get MSVS install location
:param msvc_version:
:return: MSVC install dir
"""
vswhere_path = os.path.join('C:\\', 'Program Files (x86)', 'Microsoft Visual S... |
def from_name(cls, name):
"""Create an author by name, automatically populating the hash."""
return Author(name=name, sha512=cls.hash_name(name)) | def function[from_name, parameter[cls, name]]:
constant[Create an author by name, automatically populating the hash.]
return[call[name[Author], parameter[]]] | keyword[def] identifier[from_name] ( identifier[cls] , identifier[name] ):
literal[string]
keyword[return] identifier[Author] ( identifier[name] = identifier[name] , identifier[sha512] = identifier[cls] . identifier[hash_name] ( identifier[name] )) | def from_name(cls, name):
"""Create an author by name, automatically populating the hash."""
return Author(name=name, sha512=cls.hash_name(name)) |
def add(env, securitygroup_id, remote_ip, remote_group,
direction, ethertype, port_max, port_min, protocol):
"""Add a security group rule to a security group.
\b
Examples:
# Add an SSH rule (TCP port 22) to a security group
slcli sg rule-add 384727 \\
--direction ingress... | def function[add, parameter[env, securitygroup_id, remote_ip, remote_group, direction, ethertype, port_max, port_min, protocol]]:
constant[Add a security group rule to a security group.
Examples:
# Add an SSH rule (TCP port 22) to a security group
slcli sg rule-add 384727 \
... | keyword[def] identifier[add] ( identifier[env] , identifier[securitygroup_id] , identifier[remote_ip] , identifier[remote_group] ,
identifier[direction] , identifier[ethertype] , identifier[port_max] , identifier[port_min] , identifier[protocol] ):
literal[string]
identifier[mgr] = identifier[SoftLayer] .... | def add(env, securitygroup_id, remote_ip, remote_group, direction, ethertype, port_max, port_min, protocol):
"""Add a security group rule to a security group.
\x08
Examples:
# Add an SSH rule (TCP port 22) to a security group
slcli sg rule-add 384727 \\
--direction ingress \\
... |
def make(parser):
"""
Prepare a data disk on remote host.
"""
sub_command_help = dedent("""
Create OSDs from a data disk on a remote host:
ceph-deploy osd create {node} --data /path/to/device
For bluestore, optional devices can be used::
ceph-deploy osd create {node} --data /p... | def function[make, parameter[parser]]:
constant[
Prepare a data disk on remote host.
]
variable[sub_command_help] assign[=] call[name[dedent], parameter[constant[
Create OSDs from a data disk on a remote host:
ceph-deploy osd create {node} --data /path/to/device
For bluestore, ... | keyword[def] identifier[make] ( identifier[parser] ):
literal[string]
identifier[sub_command_help] = identifier[dedent] ( literal[string]
)
identifier[parser] . identifier[formatter_class] = identifier[argparse] . identifier[RawDescriptionHelpFormatter]
identifier[parser] . identifier[descr... | def make(parser):
"""
Prepare a data disk on remote host.
"""
sub_command_help = dedent('\n Create OSDs from a data disk on a remote host:\n\n ceph-deploy osd create {node} --data /path/to/device\n\n For bluestore, optional devices can be used::\n\n ceph-deploy osd create {node} --da... |
async def get_active(self, *args, **kwargs):
"""
Get active users balance
Accepts:
- uid [integer] (users id)
- types [list | string] (array with needed types or "all")
Returns:
{
type [string] (blockchain type): amount
}
"""
# Get daya from request
coinids = kwargs.get("coinids")
uid... | <ast.AsyncFunctionDef object at 0x7da1b0915ae0> | keyword[async] keyword[def] identifier[get_active] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[coinids] = identifier[kwargs] . identifier[get] ( literal[string] )
identifier[uid] = identifier[kwargs] . identifier[get] ( literal[string] , literal[int] )
... | async def get_active(self, *args, **kwargs):
"""
Get active users balance
Accepts:
- uid [integer] (users id)
- types [list | string] (array with needed types or "all")
Returns:
{
type [string] (blockchain type): amount
}
""" # Get daya from request
coinids = kwargs.get('coinids')
... |
def calc_A_hat(A, S):
'''Return the A_hat matrix of A given the skew matrix S'''
return np.dot(S, np.dot(A, np.transpose(S))) | def function[calc_A_hat, parameter[A, S]]:
constant[Return the A_hat matrix of A given the skew matrix S]
return[call[name[np].dot, parameter[name[S], call[name[np].dot, parameter[name[A], call[name[np].transpose, parameter[name[S]]]]]]]] | keyword[def] identifier[calc_A_hat] ( identifier[A] , identifier[S] ):
literal[string]
keyword[return] identifier[np] . identifier[dot] ( identifier[S] , identifier[np] . identifier[dot] ( identifier[A] , identifier[np] . identifier[transpose] ( identifier[S] ))) | def calc_A_hat(A, S):
"""Return the A_hat matrix of A given the skew matrix S"""
return np.dot(S, np.dot(A, np.transpose(S))) |
def convert_conv(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert convolution layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary... | def function[convert_conv, parameter[params, w_name, scope_name, inputs, layers, weights, names]]:
constant[
Convert convolution layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node in... | keyword[def] identifier[convert_conv] ( identifier[params] , identifier[w_name] , identifier[scope_name] , identifier[inputs] , identifier[layers] , identifier[weights] , identifier[names] ):
literal[string]
identifier[print] ( literal[string] )
keyword[if] identifier[names] == literal[string] :
... | def convert_conv(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert convolution layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary... |
def create_indexes(self, indexes, session=None, **kwargs):
"""Create one or more indexes on this collection.
>>> from pymongo import IndexModel, ASCENDING, DESCENDING
>>> index1 = IndexModel([("hello", DESCENDING),
... ("world", ASCENDING)], name="hello_world"... | def function[create_indexes, parameter[self, indexes, session]]:
constant[Create one or more indexes on this collection.
>>> from pymongo import IndexModel, ASCENDING, DESCENDING
>>> index1 = IndexModel([("hello", DESCENDING),
... ("world", ASCENDING)], name="... | keyword[def] identifier[create_indexes] ( identifier[self] , identifier[indexes] , identifier[session] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[common] . identifier[validate_list] ( literal[string] , identifier[indexes] )
identifier[names] =[]
keyword[w... | def create_indexes(self, indexes, session=None, **kwargs):
"""Create one or more indexes on this collection.
>>> from pymongo import IndexModel, ASCENDING, DESCENDING
>>> index1 = IndexModel([("hello", DESCENDING),
... ("world", ASCENDING)], name="hello_world")
... |
async def get_instances(self, **kwargs) -> List[ApiResource]:
"""Returns a list of resource instances.
:raises PvApiError when a hub problem occurs."""
raw_resources = await self.get_resources(**kwargs)
_instances = [
self._resource_factory(_raw)
for _raw in self... | <ast.AsyncFunctionDef object at 0x7da20c795fc0> | keyword[async] keyword[def] identifier[get_instances] ( identifier[self] ,** identifier[kwargs] )-> identifier[List] [ identifier[ApiResource] ]:
literal[string]
identifier[raw_resources] = keyword[await] identifier[self] . identifier[get_resources] (** identifier[kwargs] )
identifier[_i... | async def get_instances(self, **kwargs) -> List[ApiResource]:
"""Returns a list of resource instances.
:raises PvApiError when a hub problem occurs."""
raw_resources = await self.get_resources(**kwargs)
_instances = [self._resource_factory(_raw) for _raw in self._loop_raw(raw_resources)]
return... |
def kill(restriction=None, connection=None): # pragma: no cover
"""
view and kill database connections.
:param restriction: restriction to be applied to processlist
:param connection: a datajoint.Connection object. Default calls datajoint.conn()
Restrictions are specified as strings and can involv... | def function[kill, parameter[restriction, connection]]:
constant[
view and kill database connections.
:param restriction: restriction to be applied to processlist
:param connection: a datajoint.Connection object. Default calls datajoint.conn()
Restrictions are specified as strings and can invol... | keyword[def] identifier[kill] ( identifier[restriction] = keyword[None] , identifier[connection] = keyword[None] ):
literal[string]
keyword[if] identifier[connection] keyword[is] keyword[None] :
identifier[connection] = identifier[conn] ()
identifier[query] = literal[string] +(
lite... | def kill(restriction=None, connection=None): # pragma: no cover
'\n view and kill database connections.\n :param restriction: restriction to be applied to processlist\n :param connection: a datajoint.Connection object. Default calls datajoint.conn()\n\n Restrictions are specified as strings and can inv... |
def init_reddit(generator):
"""
this is a hack to make sure the reddit object keeps track of a session
trough article scanning, speeding up networking as the connection can be
kept alive.
"""
auth_dict = generator.settings.get('REDDIT_POSTER_AUTH')
if auth_dict is None:
log.info("Co... | def function[init_reddit, parameter[generator]]:
constant[
this is a hack to make sure the reddit object keeps track of a session
trough article scanning, speeding up networking as the connection can be
kept alive.
]
variable[auth_dict] assign[=] call[name[generator].settings.get, param... | keyword[def] identifier[init_reddit] ( identifier[generator] ):
literal[string]
identifier[auth_dict] = identifier[generator] . identifier[settings] . identifier[get] ( literal[string] )
keyword[if] identifier[auth_dict] keyword[is] keyword[None] :
identifier[log] . identifier[info] ( lite... | def init_reddit(generator):
"""
this is a hack to make sure the reddit object keeps track of a session
trough article scanning, speeding up networking as the connection can be
kept alive.
"""
auth_dict = generator.settings.get('REDDIT_POSTER_AUTH')
if auth_dict is None:
log.info("Co... |
def scan(ctx, sources=None, endpoint=False, raw=False, extra=False):
"""SCAN: get ontology data from RDF source and print out a report.
"""
verbose = ctx.obj['VERBOSE']
sTime = ctx.obj['STIME']
print_opts = {
'labels': verbose,
'extra': extra,
}
if sources or (sources and end... | def function[scan, parameter[ctx, sources, endpoint, raw, extra]]:
constant[SCAN: get ontology data from RDF source and print out a report.
]
variable[verbose] assign[=] call[name[ctx].obj][constant[VERBOSE]]
variable[sTime] assign[=] call[name[ctx].obj][constant[STIME]]
variable[pri... | keyword[def] identifier[scan] ( identifier[ctx] , identifier[sources] = keyword[None] , identifier[endpoint] = keyword[False] , identifier[raw] = keyword[False] , identifier[extra] = keyword[False] ):
literal[string]
identifier[verbose] = identifier[ctx] . identifier[obj] [ literal[string] ]
identifie... | def scan(ctx, sources=None, endpoint=False, raw=False, extra=False):
"""SCAN: get ontology data from RDF source and print out a report.
"""
verbose = ctx.obj['VERBOSE']
sTime = ctx.obj['STIME']
print_opts = {'labels': verbose, 'extra': extra}
if sources or (sources and endpoint):
action_... |
def uploadCsvConfiguration(self, conf_filename):
"""
NOT NEEDED. JSON can be POSTed to IM instead of sending a CSV that is locally parsed and converted to JSON.
Remote Address:192.168.100.51:443
Request URL:https://192.168.100.51/types/Configuration/instances/actions/parseFromCS... | def function[uploadCsvConfiguration, parameter[self, conf_filename]]:
constant[
NOT NEEDED. JSON can be POSTed to IM instead of sending a CSV that is locally parsed and converted to JSON.
Remote Address:192.168.100.51:443
Request URL:https://192.168.100.51/types/Configuration/in... | keyword[def] identifier[uploadCsvConfiguration] ( identifier[self] , identifier[conf_filename] ):
literal[string]
identifier[parameters] ={ literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[string] : litera... | def uploadCsvConfiguration(self, conf_filename):
"""
NOT NEEDED. JSON can be POSTed to IM instead of sending a CSV that is locally parsed and converted to JSON.
Remote Address:192.168.100.51:443
Request URL:https://192.168.100.51/types/Configuration/instances/actions/parseFromCSV
... |
def expand_path(path):
"""Returns ``path`` as an absolute path with ~user and env var expansion applied.
:API: public
"""
return os.path.abspath(os.path.expandvars(os.path.expanduser(path))) | def function[expand_path, parameter[path]]:
constant[Returns ``path`` as an absolute path with ~user and env var expansion applied.
:API: public
]
return[call[name[os].path.abspath, parameter[call[name[os].path.expandvars, parameter[call[name[os].path.expanduser, parameter[name[path]]]]]]]] | keyword[def] identifier[expand_path] ( identifier[path] ):
literal[string]
keyword[return] identifier[os] . identifier[path] . identifier[abspath] ( identifier[os] . identifier[path] . identifier[expandvars] ( identifier[os] . identifier[path] . identifier[expanduser] ( identifier[path] ))) | def expand_path(path):
"""Returns ``path`` as an absolute path with ~user and env var expansion applied.
:API: public
"""
return os.path.abspath(os.path.expandvars(os.path.expanduser(path))) |
def from_prev_calc(cls, prev_calc_dir, copy_chgcar=True,
nbands_factor=1.2, standardize=False, sym_prec=0.1,
international_monoclinic=True, reciprocal_density=100,
small_gap_multiply=None, **kwargs):
"""
Generate a set of Vasp input fi... | def function[from_prev_calc, parameter[cls, prev_calc_dir, copy_chgcar, nbands_factor, standardize, sym_prec, international_monoclinic, reciprocal_density, small_gap_multiply]]:
constant[
Generate a set of Vasp input files for SOC calculations from a
directory of previous static Vasp run. SOC ca... | keyword[def] identifier[from_prev_calc] ( identifier[cls] , identifier[prev_calc_dir] , identifier[copy_chgcar] = keyword[True] ,
identifier[nbands_factor] = literal[int] , identifier[standardize] = keyword[False] , identifier[sym_prec] = literal[int] ,
identifier[international_monoclinic] = keyword[True] , identif... | def from_prev_calc(cls, prev_calc_dir, copy_chgcar=True, nbands_factor=1.2, standardize=False, sym_prec=0.1, international_monoclinic=True, reciprocal_density=100, small_gap_multiply=None, **kwargs):
"""
Generate a set of Vasp input files for SOC calculations from a
directory of previous static Vasp... |
def asISO8601TimeAndDate(self, includeDelimiters=True, tzinfo=None,
includeTimezone=True):
"""Return this time formatted as specified by ISO 8861.
ISO 8601 allows optional dashes to delimit dates and colons to delimit
times. The parameter includeDelimiters (default ... | def function[asISO8601TimeAndDate, parameter[self, includeDelimiters, tzinfo, includeTimezone]]:
constant[Return this time formatted as specified by ISO 8861.
ISO 8601 allows optional dashes to delimit dates and colons to delimit
times. The parameter includeDelimiters (default True) defines the... | keyword[def] identifier[asISO8601TimeAndDate] ( identifier[self] , identifier[includeDelimiters] = keyword[True] , identifier[tzinfo] = keyword[None] ,
identifier[includeTimezone] = keyword[True] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[isTimezoneDependent] ():
... | def asISO8601TimeAndDate(self, includeDelimiters=True, tzinfo=None, includeTimezone=True):
"""Return this time formatted as specified by ISO 8861.
ISO 8601 allows optional dashes to delimit dates and colons to delimit
times. The parameter includeDelimiters (default True) defines the
inclusi... |
def filter(self, *args):
'''
Returns a filtered subset of this collection of signatures, based on
a set of key/value tuples
This is useful when you only want a subset of the signatures in a project.
Example usage:
::
pc = PerfherderClient()
sign... | def function[filter, parameter[self]]:
constant[
Returns a filtered subset of this collection of signatures, based on
a set of key/value tuples
This is useful when you only want a subset of the signatures in a project.
Example usage:
::
pc = PerfherderClien... | keyword[def] identifier[filter] ( identifier[self] ,* identifier[args] ):
literal[string]
identifier[filtered_signatures] ={}
keyword[for] ( identifier[signature] , identifier[signature_value] ) keyword[in] identifier[self] . identifier[items] ():
identifier[skip] = keyword[F... | def filter(self, *args):
"""
Returns a filtered subset of this collection of signatures, based on
a set of key/value tuples
This is useful when you only want a subset of the signatures in a project.
Example usage:
::
pc = PerfherderClient()
signatur... |
def get_shard_iterator(self, *, stream_arn, shard_id, iterator_type, sequence_number=None):
"""Wraps :func:`boto3.DynamoDBStreams.Client.get_shard_iterator`.
:param str stream_arn: Stream arn. Usually :data:`Shard.stream_arn <bloop.stream.shard.Shard.stream_arn>`.
:param str shard_id: Shard id... | def function[get_shard_iterator, parameter[self]]:
constant[Wraps :func:`boto3.DynamoDBStreams.Client.get_shard_iterator`.
:param str stream_arn: Stream arn. Usually :data:`Shard.stream_arn <bloop.stream.shard.Shard.stream_arn>`.
:param str shard_id: Shard identifier. Usually :data:`Shard.sha... | keyword[def] identifier[get_shard_iterator] ( identifier[self] ,*, identifier[stream_arn] , identifier[shard_id] , identifier[iterator_type] , identifier[sequence_number] = keyword[None] ):
literal[string]
identifier[real_iterator_type] = identifier[validate_stream_iterator_type] ( identifier[itera... | def get_shard_iterator(self, *, stream_arn, shard_id, iterator_type, sequence_number=None):
"""Wraps :func:`boto3.DynamoDBStreams.Client.get_shard_iterator`.
:param str stream_arn: Stream arn. Usually :data:`Shard.stream_arn <bloop.stream.shard.Shard.stream_arn>`.
:param str shard_id: Shard identi... |
def count_lines_in_file(src_file ):
"""
test function.
"""
tot = 0
res = ''
try:
with open(src_file, 'r') as f:
for line in f:
tot += 1
res = str(tot) + ' recs read'
except:
res = 'ERROR -couldnt open file'
return res | def function[count_lines_in_file, parameter[src_file]]:
constant[
test function.
]
variable[tot] assign[=] constant[0]
variable[res] assign[=] constant[]
<ast.Try object at 0x7da18f00fe80>
return[name[res]] | keyword[def] identifier[count_lines_in_file] ( identifier[src_file] ):
literal[string]
identifier[tot] = literal[int]
identifier[res] = literal[string]
keyword[try] :
keyword[with] identifier[open] ( identifier[src_file] , literal[string] ) keyword[as] identifier[f] :
ke... | def count_lines_in_file(src_file):
"""
test function.
"""
tot = 0
res = ''
try:
with open(src_file, 'r') as f:
for line in f:
tot += 1 # depends on [control=['for'], data=[]]
res = str(tot) + ' recs read' # depends on [control=['with'], data=['f'... |
def touch_member(config, dcs):
''' Rip-off of the ha.touch_member without inter-class dependencies '''
p = Postgresql(config['postgresql'])
p.set_state('running')
p.set_role('master')
def restapi_connection_string(config):
protocol = 'https' if config.get('certfile') else 'http'
con... | def function[touch_member, parameter[config, dcs]]:
constant[ Rip-off of the ha.touch_member without inter-class dependencies ]
variable[p] assign[=] call[name[Postgresql], parameter[call[name[config]][constant[postgresql]]]]
call[name[p].set_state, parameter[constant[running]]]
call[nam... | keyword[def] identifier[touch_member] ( identifier[config] , identifier[dcs] ):
literal[string]
identifier[p] = identifier[Postgresql] ( identifier[config] [ literal[string] ])
identifier[p] . identifier[set_state] ( literal[string] )
identifier[p] . identifier[set_role] ( literal[string] )
... | def touch_member(config, dcs):
""" Rip-off of the ha.touch_member without inter-class dependencies """
p = Postgresql(config['postgresql'])
p.set_state('running')
p.set_role('master')
def restapi_connection_string(config):
protocol = 'https' if config.get('certfile') else 'http'
con... |
def sharing_agreements(self):
"""
| Comment: The ids of the sharing agreements used for this ticket
"""
if self.api and self.sharing_agreement_ids:
return self.api._get_sharing_agreements(self.sharing_agreement_ids) | def function[sharing_agreements, parameter[self]]:
constant[
| Comment: The ids of the sharing agreements used for this ticket
]
if <ast.BoolOp object at 0x7da204345630> begin[:]
return[call[name[self].api._get_sharing_agreements, parameter[name[self].sharing_agreement_ids]]] | keyword[def] identifier[sharing_agreements] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[api] keyword[and] identifier[self] . identifier[sharing_agreement_ids] :
keyword[return] identifier[self] . identifier[api] . identifier[_get_sharing_agreemen... | def sharing_agreements(self):
"""
| Comment: The ids of the sharing agreements used for this ticket
"""
if self.api and self.sharing_agreement_ids:
return self.api._get_sharing_agreements(self.sharing_agreement_ids) # depends on [control=['if'], data=[]] |
def empty_mets():
"""
Create an empty METS file from bundled template.
"""
tpl = METS_XML_EMPTY.decode('utf-8')
tpl = tpl.replace('{{ VERSION }}', VERSION)
tpl = tpl.replace('{{ NOW }}', '%s' % datetime.now())
return OcrdMets(content=tpl.encode('utf-8')) | def function[empty_mets, parameter[]]:
constant[
Create an empty METS file from bundled template.
]
variable[tpl] assign[=] call[name[METS_XML_EMPTY].decode, parameter[constant[utf-8]]]
variable[tpl] assign[=] call[name[tpl].replace, parameter[constant[{{ VERSION }}], name[VERSIO... | keyword[def] identifier[empty_mets] ():
literal[string]
identifier[tpl] = identifier[METS_XML_EMPTY] . identifier[decode] ( literal[string] )
identifier[tpl] = identifier[tpl] . identifier[replace] ( literal[string] , identifier[VERSION] )
identifier[tpl] = identifier[tpl] . ident... | def empty_mets():
"""
Create an empty METS file from bundled template.
"""
tpl = METS_XML_EMPTY.decode('utf-8')
tpl = tpl.replace('{{ VERSION }}', VERSION)
tpl = tpl.replace('{{ NOW }}', '%s' % datetime.now())
return OcrdMets(content=tpl.encode('utf-8')) |
def change_result(self, old_result_name, new_result_name, new_er_data=None,
new_pmag_data=None, spec_names=None, samp_names=None,
site_names=None, loc_names=None, replace_data=False):
"""
Find actual data object for result with old_result_name.
Then ca... | def function[change_result, parameter[self, old_result_name, new_result_name, new_er_data, new_pmag_data, spec_names, samp_names, site_names, loc_names, replace_data]]:
constant[
Find actual data object for result with old_result_name.
Then call Result class change method to update result name a... | keyword[def] identifier[change_result] ( identifier[self] , identifier[old_result_name] , identifier[new_result_name] , identifier[new_er_data] = keyword[None] ,
identifier[new_pmag_data] = keyword[None] , identifier[spec_names] = keyword[None] , identifier[samp_names] = keyword[None] ,
identifier[site_names] = key... | def change_result(self, old_result_name, new_result_name, new_er_data=None, new_pmag_data=None, spec_names=None, samp_names=None, site_names=None, loc_names=None, replace_data=False):
"""
Find actual data object for result with old_result_name.
Then call Result class change method to update result n... |
def register_dimension(self, name, dim_data, **kwargs):
"""
Registers a dimension on this cube.
.. code-block:: python
cube.register_dimension('ntime', 10000,
decription="Number of Timesteps",
lower_extent=100, upper_extent=200)
... | def function[register_dimension, parameter[self, name, dim_data]]:
constant[
Registers a dimension on this cube.
.. code-block:: python
cube.register_dimension('ntime', 10000,
decription="Number of Timesteps",
lower_extent=100, upper_... | keyword[def] identifier[register_dimension] ( identifier[self] , identifier[name] , identifier[dim_data] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[name] keyword[in] identifier[self] . identifier[_dims] :
keyword[raise] identifier[AttributeError] ((
... | def register_dimension(self, name, dim_data, **kwargs):
"""
Registers a dimension on this cube.
.. code-block:: python
cube.register_dimension('ntime', 10000,
decription="Number of Timesteps",
lower_extent=100, upper_extent=200)
... |
def multiply(self, other):
"""Return the QuantumChannel self + other.
Args:
other (complex): a complex number.
Returns:
Kraus: the scalar multiplication other * self as a Kraus object.
Raises:
QiskitError: if other is not a valid scalar.
"""... | def function[multiply, parameter[self, other]]:
constant[Return the QuantumChannel self + other.
Args:
other (complex): a complex number.
Returns:
Kraus: the scalar multiplication other * self as a Kraus object.
Raises:
QiskitError: if other is not ... | keyword[def] identifier[multiply] ( identifier[self] , identifier[other] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[other] , identifier[Number] ):
keyword[raise] identifier[QiskitError] ( literal[string] )
keywo... | def multiply(self, other):
"""Return the QuantumChannel self + other.
Args:
other (complex): a complex number.
Returns:
Kraus: the scalar multiplication other * self as a Kraus object.
Raises:
QiskitError: if other is not a valid scalar.
"""
... |
def execute(self, example_groups):
"""Runs the specs. Returns a tuple indicating the
number of (succeses, failures, skipped)>
"""
total_successes, total_errors, total_skipped = 0, 0, 0
for group in example_groups:
runner = ExampleRunner(group, self.formatter)
... | def function[execute, parameter[self, example_groups]]:
constant[Runs the specs. Returns a tuple indicating the
number of (succeses, failures, skipped)>
]
<ast.Tuple object at 0x7da1b1ff0fd0> assign[=] tuple[[<ast.Constant object at 0x7da1b1ff03d0>, <ast.Constant object at 0x7da1b1ff05e0... | keyword[def] identifier[execute] ( identifier[self] , identifier[example_groups] ):
literal[string]
identifier[total_successes] , identifier[total_errors] , identifier[total_skipped] = literal[int] , literal[int] , literal[int]
keyword[for] identifier[group] keyword[in] identifier[exam... | def execute(self, example_groups):
"""Runs the specs. Returns a tuple indicating the
number of (succeses, failures, skipped)>
"""
(total_successes, total_errors, total_skipped) = (0, 0, 0)
for group in example_groups:
runner = ExampleRunner(group, self.formatter)
(successes, ... |
def bisine_wave(frequency):
"""Emit two sine waves, in stereo at different octaves."""
#
# We can first our existing sine generator to generate two different
# waves.
f_hi = frequency
f_lo = frequency / 2.0
with tf.name_scope('hi'):
sine_hi = sine_wave(f_hi)
with tf.name_scope('lo'):
sine_lo = s... | def function[bisine_wave, parameter[frequency]]:
constant[Emit two sine waves, in stereo at different octaves.]
variable[f_hi] assign[=] name[frequency]
variable[f_lo] assign[=] binary_operation[name[frequency] / constant[2.0]]
with call[name[tf].name_scope, parameter[constant[hi]]] begi... | keyword[def] identifier[bisine_wave] ( identifier[frequency] ):
literal[string]
identifier[f_hi] = identifier[frequency]
identifier[f_lo] = identifier[frequency] / literal[int]
keyword[with] identifier[tf] . identifier[name_scope] ( literal[string] ):
identifier[sine_hi] = identifier[sin... | def bisine_wave(frequency):
"""Emit two sine waves, in stereo at different octaves."""
#
# We can first our existing sine generator to generate two different
# waves.
f_hi = frequency
f_lo = frequency / 2.0
with tf.name_scope('hi'):
sine_hi = sine_wave(f_hi) # depends on [control=['... |
def fetch(self):
"""
Fetch a FeedbackInstance
:returns: Fetched FeedbackInstance
:rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackInstance
"""
params = values.of({})
payload = self._version.fetch(
'GET',
self._uri,
... | def function[fetch, parameter[self]]:
constant[
Fetch a FeedbackInstance
:returns: Fetched FeedbackInstance
:rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackInstance
]
variable[params] assign[=] call[name[values].of, parameter[dictionary[[], []]]]
vari... | keyword[def] identifier[fetch] ( identifier[self] ):
literal[string]
identifier[params] = identifier[values] . identifier[of] ({})
identifier[payload] = identifier[self] . identifier[_version] . identifier[fetch] (
literal[string] ,
identifier[self] . identifier[_uri] ,
... | def fetch(self):
"""
Fetch a FeedbackInstance
:returns: Fetched FeedbackInstance
:rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackInstance
"""
params = values.of({})
payload = self._version.fetch('GET', self._uri, params=params)
return FeedbackInstance(self._v... |
def _clean_pending_exits(self):
"""
Remove those pending exits if:
a) they are the return exits of non-returning SimProcedures
b) they are the return exits of non-returning syscalls
c) they are the return exits of non-returning functions
:return: True if any pending exit... | def function[_clean_pending_exits, parameter[self]]:
constant[
Remove those pending exits if:
a) they are the return exits of non-returning SimProcedures
b) they are the return exits of non-returning syscalls
c) they are the return exits of non-returning functions
:retur... | keyword[def] identifier[_clean_pending_exits] ( identifier[self] ):
literal[string]
identifier[pending_exits_to_remove] =[]
keyword[for] identifier[block_id] , identifier[pe] keyword[in] identifier[self] . identifier[_pending_jobs] . identifier[items] ():
keyword[if] ide... | def _clean_pending_exits(self):
"""
Remove those pending exits if:
a) they are the return exits of non-returning SimProcedures
b) they are the return exits of non-returning syscalls
c) they are the return exits of non-returning functions
:return: True if any pending exits ar... |
def update_record(self, name, recordid, content, username, password):
''' Update record '''
# headers = {'key': username, 'secret': password}
req = requests.put(self.api_server + '/api/' + name + '/' +
str(recordid), data=json.dumps(content),
... | def function[update_record, parameter[self, name, recordid, content, username, password]]:
constant[ Update record ]
variable[req] assign[=] call[name[requests].put, parameter[binary_operation[binary_operation[binary_operation[binary_operation[name[self].api_server + constant[/api/]] + name[name]] + con... | keyword[def] identifier[update_record] ( identifier[self] , identifier[name] , identifier[recordid] , identifier[content] , identifier[username] , identifier[password] ):
literal[string]
identifier[req] = identifier[requests] . identifier[put] ( identifier[self] . identifier[api_server] + ... | def update_record(self, name, recordid, content, username, password):
""" Update record """
# headers = {'key': username, 'secret': password}
req = requests.put(self.api_server + '/api/' + name + '/' + str(recordid), data=json.dumps(content), auth=(username, password))
return req |
def _generateChildrenR(self, target=None):
"""Generator which recursively yields all AXChildren of the object."""
if target is None:
target = self
try:
children = target.AXChildren
except _a11y.Error:
return
if children:
for child i... | def function[_generateChildrenR, parameter[self, target]]:
constant[Generator which recursively yields all AXChildren of the object.]
if compare[name[target] is constant[None]] begin[:]
variable[target] assign[=] name[self]
<ast.Try object at 0x7da18f09e440>
if name[children]... | keyword[def] identifier[_generateChildrenR] ( identifier[self] , identifier[target] = keyword[None] ):
literal[string]
keyword[if] identifier[target] keyword[is] keyword[None] :
identifier[target] = identifier[self]
keyword[try] :
identifier[children] = identi... | def _generateChildrenR(self, target=None):
"""Generator which recursively yields all AXChildren of the object."""
if target is None:
target = self # depends on [control=['if'], data=['target']]
try:
children = target.AXChildren # depends on [control=['try'], data=[]]
except _a11y.Error... |
def executeBatch(cursor, sql,
regex=r"(?mx) ([^';]* (?:'[^']*'[^';]*)*)",
comment_regex=r"(?mx) (?:^\s*$)|(?:--.*$)"):
"""
Takes a SQL file and executes it as many separate statements.
TODO: replace regexes with something easier to grok and extend.
"""
# First, st... | def function[executeBatch, parameter[cursor, sql, regex, comment_regex]]:
constant[
Takes a SQL file and executes it as many separate statements.
TODO: replace regexes with something easier to grok and extend.
]
variable[sql] assign[=] call[constant[
].join, parameter[<ast.ListComp object ... | keyword[def] identifier[executeBatch] ( identifier[cursor] , identifier[sql] ,
identifier[regex] = literal[string] ,
identifier[comment_regex] = literal[string] ):
literal[string]
identifier[sql] = literal[string] . identifier[join] ([ identifier[x] . identifier[strip] (). identifier[replace] ( lite... | def executeBatch(cursor, sql, regex="(?mx) ([^';]* (?:'[^']*'[^';]*)*)", comment_regex='(?mx) (?:^\\s*$)|(?:--.*$)'):
"""
Takes a SQL file and executes it as many separate statements.
TODO: replace regexes with something easier to grok and extend.
"""
# First, strip comments
sql = '\n'.join([x... |
def get_active_length(self):
"""
Return the maximum active length (i.e., without trailing silence) among
the pianorolls of all tracks. The unit is time step.
Returns
-------
active_length : int
The maximum active length (i.e., without trailing silence) among ... | def function[get_active_length, parameter[self]]:
constant[
Return the maximum active length (i.e., without trailing silence) among
the pianorolls of all tracks. The unit is time step.
Returns
-------
active_length : int
The maximum active length (i.e., witho... | keyword[def] identifier[get_active_length] ( identifier[self] ):
literal[string]
identifier[active_length] = literal[int]
keyword[for] identifier[track] keyword[in] identifier[self] . identifier[tracks] :
identifier[now_length] = identifier[track] . identifier[get_active_l... | def get_active_length(self):
"""
Return the maximum active length (i.e., without trailing silence) among
the pianorolls of all tracks. The unit is time step.
Returns
-------
active_length : int
The maximum active length (i.e., without trailing silence) among the
... |
def on_start_scene(self, event: StartScene, signal: Callable[[Any], None]):
"""
Start a new scene. The current scene pauses.
"""
self.pause_scene()
self.start_scene(event.new_scene, event.kwargs) | def function[on_start_scene, parameter[self, event, signal]]:
constant[
Start a new scene. The current scene pauses.
]
call[name[self].pause_scene, parameter[]]
call[name[self].start_scene, parameter[name[event].new_scene, name[event].kwargs]] | keyword[def] identifier[on_start_scene] ( identifier[self] , identifier[event] : identifier[StartScene] , identifier[signal] : identifier[Callable] [[ identifier[Any] ], keyword[None] ]):
literal[string]
identifier[self] . identifier[pause_scene] ()
identifier[self] . identifier[start_scen... | def on_start_scene(self, event: StartScene, signal: Callable[[Any], None]):
"""
Start a new scene. The current scene pauses.
"""
self.pause_scene()
self.start_scene(event.new_scene, event.kwargs) |
def create_assignment( # pylint: disable=too-many-arguments
self,
name,
short_name,
weight,
max_points,
due_date_str,
gradebook_id='',
**kwargs
):
"""Create a new assignment.
Create a new assignment. By... | def function[create_assignment, parameter[self, name, short_name, weight, max_points, due_date_str, gradebook_id]]:
constant[Create a new assignment.
Create a new assignment. By default, assignments are created
under the `Uncategorized` category.
Args:
name (str): descripti... | keyword[def] identifier[create_assignment] (
identifier[self] ,
identifier[name] ,
identifier[short_name] ,
identifier[weight] ,
identifier[max_points] ,
identifier[due_date_str] ,
identifier[gradebook_id] = literal[string] ,
** identifier[kwargs]
):
literal[string]
identifier[data] ={
... | def create_assignment(self, name, short_name, weight, max_points, due_date_str, gradebook_id='', **kwargs): # pylint: disable=too-many-arguments
"Create a new assignment.\n\n Create a new assignment. By default, assignments are created\n under the `Uncategorized` category.\n\n Args:\n ... |
def get_output_dict(stack):
"""Returns a dict of key/values for the outputs for a given CF stack.
Args:
stack (dict): The stack object to get
outputs from.
Returns:
dict: A dictionary with key/values for each output on the stack.
"""
outputs = {}
if 'Outputs' not i... | def function[get_output_dict, parameter[stack]]:
constant[Returns a dict of key/values for the outputs for a given CF stack.
Args:
stack (dict): The stack object to get
outputs from.
Returns:
dict: A dictionary with key/values for each output on the stack.
]
va... | keyword[def] identifier[get_output_dict] ( identifier[stack] ):
literal[string]
identifier[outputs] ={}
keyword[if] literal[string] keyword[not] keyword[in] identifier[stack] :
keyword[return] identifier[outputs]
keyword[for] identifier[output] keyword[in] identifier[stack] [ l... | def get_output_dict(stack):
"""Returns a dict of key/values for the outputs for a given CF stack.
Args:
stack (dict): The stack object to get
outputs from.
Returns:
dict: A dictionary with key/values for each output on the stack.
"""
outputs = {}
if 'Outputs' not i... |
def restore_snapshot(self, context, snapshot_name):
"""
Restores virtual machine from a snapshot
:param context: resource context of the vCenterShell
:type context: models.QualiDriverModels.ResourceCommandContext
:param snapshot_name: snapshot name to save to
:type snapsh... | def function[restore_snapshot, parameter[self, context, snapshot_name]]:
constant[
Restores virtual machine from a snapshot
:param context: resource context of the vCenterShell
:type context: models.QualiDriverModels.ResourceCommandContext
:param snapshot_name: snapshot name to s... | keyword[def] identifier[restore_snapshot] ( identifier[self] , identifier[context] , identifier[snapshot_name] ):
literal[string]
identifier[resource_details] = identifier[self] . identifier[_parse_remote_model] ( identifier[context] )
identifier[self] . identifier[command_wrapper] . ident... | def restore_snapshot(self, context, snapshot_name):
"""
Restores virtual machine from a snapshot
:param context: resource context of the vCenterShell
:type context: models.QualiDriverModels.ResourceCommandContext
:param snapshot_name: snapshot name to save to
:type snapshot_n... |
def process_der(self, data, name):
"""
DER processing
:param data:
:param name:
:return:
"""
from cryptography.x509.base import load_der_x509_certificate
try:
x509 = load_der_x509_certificate(data, self.get_backend())
self.num_der_c... | def function[process_der, parameter[self, data, name]]:
constant[
DER processing
:param data:
:param name:
:return:
]
from relative_module[cryptography.x509.base] import module[load_der_x509_certificate]
<ast.Try object at 0x7da20c6c5cc0> | keyword[def] identifier[process_der] ( identifier[self] , identifier[data] , identifier[name] ):
literal[string]
keyword[from] identifier[cryptography] . identifier[x509] . identifier[base] keyword[import] identifier[load_der_x509_certificate]
keyword[try] :
identifier[x50... | def process_der(self, data, name):
"""
DER processing
:param data:
:param name:
:return:
"""
from cryptography.x509.base import load_der_x509_certificate
try:
x509 = load_der_x509_certificate(data, self.get_backend())
self.num_der_certs += 1
re... |
def can_update_topics_to_sticky_topics(self, forum, user):
""" Given a forum, checks whether the user can change its topic types to sticky topics. """
return (
self._perform_basic_permission_check(forum, user, 'can_edit_posts') and
self._perform_basic_permission_check(forum, user... | def function[can_update_topics_to_sticky_topics, parameter[self, forum, user]]:
constant[ Given a forum, checks whether the user can change its topic types to sticky topics. ]
return[<ast.BoolOp object at 0x7da207f9ad70>] | keyword[def] identifier[can_update_topics_to_sticky_topics] ( identifier[self] , identifier[forum] , identifier[user] ):
literal[string]
keyword[return] (
identifier[self] . identifier[_perform_basic_permission_check] ( identifier[forum] , identifier[user] , literal[string] ) keyword[and] ... | def can_update_topics_to_sticky_topics(self, forum, user):
""" Given a forum, checks whether the user can change its topic types to sticky topics. """
return self._perform_basic_permission_check(forum, user, 'can_edit_posts') and self._perform_basic_permission_check(forum, user, 'can_post_stickies') |
def replicate_with_dst_resource_provisioning(self, max_time_out_of_sync,
dst_pool_id,
dst_lun_name=None,
remote_system=None,
... | def function[replicate_with_dst_resource_provisioning, parameter[self, max_time_out_of_sync, dst_pool_id, dst_lun_name, remote_system, replication_name, dst_size, dst_sp, is_dst_thin, dst_tiering_policy, is_dst_compression]]:
constant[
Creates a replication session with destination lun provisioning.
... | keyword[def] identifier[replicate_with_dst_resource_provisioning] ( identifier[self] , identifier[max_time_out_of_sync] ,
identifier[dst_pool_id] ,
identifier[dst_lun_name] = keyword[None] ,
identifier[remote_system] = keyword[None] ,
identifier[replication_name] = keyword[None] ,
identifier[dst_size] = keyword[... | def replicate_with_dst_resource_provisioning(self, max_time_out_of_sync, dst_pool_id, dst_lun_name=None, remote_system=None, replication_name=None, dst_size=None, dst_sp=None, is_dst_thin=None, dst_tiering_policy=None, is_dst_compression=None):
"""
Creates a replication session with destination lun provisio... |
def get_string(self, **kwargs):
"""Return string representation of table in current state.
Arguments:
title - optional table title
start - index of first data row to include in output
end - index of last data row to include in output PLUS ONE (list slice style)
fields -... | def function[get_string, parameter[self]]:
constant[Return string representation of table in current state.
Arguments:
title - optional table title
start - index of first data row to include in output
end - index of last data row to include in output PLUS ONE (list slice style)... | keyword[def] identifier[get_string] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[options] = identifier[self] . identifier[_get_options] ( identifier[kwargs] )
identifier[lines] =[]
keyword[if] identifier[self] . identifier[... | def get_string(self, **kwargs):
"""Return string representation of table in current state.
Arguments:
title - optional table title
start - index of first data row to include in output
end - index of last data row to include in output PLUS ONE (list slice style)
fields - nam... |
def deserialize_tag(stream, header, verifier=None):
"""Deserialize the Tag value from a non-framed stream.
:param stream: Source data stream
:type stream: io.BytesIO
:param header: Deserialized header
:type header: aws_encryption_sdk.structures.MessageHeader
:param verifier: Signature verifier ... | def function[deserialize_tag, parameter[stream, header, verifier]]:
constant[Deserialize the Tag value from a non-framed stream.
:param stream: Source data stream
:type stream: io.BytesIO
:param header: Deserialized header
:type header: aws_encryption_sdk.structures.MessageHeader
:param ver... | keyword[def] identifier[deserialize_tag] ( identifier[stream] , identifier[header] , identifier[verifier] = keyword[None] ):
literal[string]
( identifier[data_tag] ,)= identifier[unpack_values] (
identifier[format_string] = literal[string] . identifier[format] ( identifier[auth_len] = identifier[header... | def deserialize_tag(stream, header, verifier=None):
"""Deserialize the Tag value from a non-framed stream.
:param stream: Source data stream
:type stream: io.BytesIO
:param header: Deserialized header
:type header: aws_encryption_sdk.structures.MessageHeader
:param verifier: Signature verifier ... |
def _BytesForNonRepeatedElement(value, field_number, field_type):
"""Returns the number of bytes needed to serialize a non-repeated element.
The returned byte count includes space for tag information and any
other additional space associated with serializing value.
Args:
value: Value we're serializing.
... | def function[_BytesForNonRepeatedElement, parameter[value, field_number, field_type]]:
constant[Returns the number of bytes needed to serialize a non-repeated element.
The returned byte count includes space for tag information and any
other additional space associated with serializing value.
Args:
va... | keyword[def] identifier[_BytesForNonRepeatedElement] ( identifier[value] , identifier[field_number] , identifier[field_type] ):
literal[string]
keyword[try] :
identifier[fn] = identifier[type_checkers] . identifier[TYPE_TO_BYTE_SIZE_FN] [ identifier[field_type] ]
keyword[return] identifier[fn] ( ide... | def _BytesForNonRepeatedElement(value, field_number, field_type):
"""Returns the number of bytes needed to serialize a non-repeated element.
The returned byte count includes space for tag information and any
other additional space associated with serializing value.
Args:
value: Value we're serializing.
... |
def init_device(self):
"""
Initializes the device with the proper keymaps and name
"""
try:
product_id = int(self._send_command('_d2', 1))
except ValueError:
product_id = self._send_command('_d2', 1)
if product_id == 0:
self._impl = Re... | def function[init_device, parameter[self]]:
constant[
Initializes the device with the proper keymaps and name
]
<ast.Try object at 0x7da18bc72350>
if compare[name[product_id] equal[==] constant[0]] begin[:]
name[self]._impl assign[=] call[name[ResponseDevice], paramet... | keyword[def] identifier[init_device] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[product_id] = identifier[int] ( identifier[self] . identifier[_send_command] ( literal[string] , literal[int] ))
keyword[except] identifier[ValueError] :
identifi... | def init_device(self):
"""
Initializes the device with the proper keymaps and name
"""
try:
product_id = int(self._send_command('_d2', 1)) # depends on [control=['try'], data=[]]
except ValueError:
product_id = self._send_command('_d2', 1) # depends on [control=['except'], ... |
def init_limit(self, key, lower=None, upper=None, limit=False):
""" check if data is within limits. reset if violates"""
above = agtb(self.__dict__[key], upper)
for idx, item in enumerate(above):
if item == 0.:
continue
maxval = upper[idx]
self... | def function[init_limit, parameter[self, key, lower, upper, limit]]:
constant[ check if data is within limits. reset if violates]
variable[above] assign[=] call[name[agtb], parameter[call[name[self].__dict__][name[key]], name[upper]]]
for taget[tuple[[<ast.Name object at 0x7da18fe91c30>, <ast.Na... | keyword[def] identifier[init_limit] ( identifier[self] , identifier[key] , identifier[lower] = keyword[None] , identifier[upper] = keyword[None] , identifier[limit] = keyword[False] ):
literal[string]
identifier[above] = identifier[agtb] ( identifier[self] . identifier[__dict__] [ identifier[key] ]... | def init_limit(self, key, lower=None, upper=None, limit=False):
""" check if data is within limits. reset if violates"""
above = agtb(self.__dict__[key], upper)
for (idx, item) in enumerate(above):
if item == 0.0:
continue # depends on [control=['if'], data=[]]
maxval = upper[id... |
def all_nodes_that_receive(service, service_configuration=None, run_only=False, deploy_to_only=False):
"""If run_only, returns only the services that are in the runs_on list.
If deploy_to_only, returns only the services in the deployed_to list.
If neither, both are returned, duplicates stripped.
Results... | def function[all_nodes_that_receive, parameter[service, service_configuration, run_only, deploy_to_only]]:
constant[If run_only, returns only the services that are in the runs_on list.
If deploy_to_only, returns only the services in the deployed_to list.
If neither, both are returned, duplicates strippe... | keyword[def] identifier[all_nodes_that_receive] ( identifier[service] , identifier[service_configuration] = keyword[None] , identifier[run_only] = keyword[False] , identifier[deploy_to_only] = keyword[False] ):
literal[string]
keyword[assert] keyword[not] ( identifier[run_only] keyword[and] identifier[d... | def all_nodes_that_receive(service, service_configuration=None, run_only=False, deploy_to_only=False):
"""If run_only, returns only the services that are in the runs_on list.
If deploy_to_only, returns only the services in the deployed_to list.
If neither, both are returned, duplicates stripped.
Results... |
def load_hypergraph_adjacency(hdf5_file_name):
"""
Parameters
----------
hdf5_file_name : file handle or string
Returns
-------
hypergraph_adjacency : compressed sparse row matrix
"""
with tables.open_file(hdf5_file_name, 'r+') as fileh:
pars = []
for par i... | def function[load_hypergraph_adjacency, parameter[hdf5_file_name]]:
constant[
Parameters
----------
hdf5_file_name : file handle or string
Returns
-------
hypergraph_adjacency : compressed sparse row matrix
]
with call[name[tables].open_file, parameter[name[hdf5_fil... | keyword[def] identifier[load_hypergraph_adjacency] ( identifier[hdf5_file_name] ):
literal[string]
keyword[with] identifier[tables] . identifier[open_file] ( identifier[hdf5_file_name] , literal[string] ) keyword[as] identifier[fileh] :
identifier[pars] =[]
keyword[for] identifier[par... | def load_hypergraph_adjacency(hdf5_file_name):
"""
Parameters
----------
hdf5_file_name : file handle or string
Returns
-------
hypergraph_adjacency : compressed sparse row matrix
"""
with tables.open_file(hdf5_file_name, 'r+') as fileh:
pars = []
for par in... |
def next(self):
"""Return the next match; raises Exception if no next match available"""
# Check the state and find the next match as a side-effect if necessary.
if not self.has_next():
raise StopIteration("No next match")
# Don't retain that memory any longer than necessary.... | def function[next, parameter[self]]:
constant[Return the next match; raises Exception if no next match available]
if <ast.UnaryOp object at 0x7da1b18a1e70> begin[:]
<ast.Raise object at 0x7da1b18a0a60>
variable[result] assign[=] name[self]._last_match
name[self]._last_match assig... | keyword[def] identifier[next] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[has_next] ():
keyword[raise] identifier[StopIteration] ( literal[string] )
identifier[result] = identifier[self] . identifier[_la... | def next(self):
"""Return the next match; raises Exception if no next match available"""
# Check the state and find the next match as a side-effect if necessary.
if not self.has_next():
raise StopIteration('No next match') # depends on [control=['if'], data=[]]
# Don't retain that memory any lo... |
def get(self, key, lang=None):
""" Returns triple related to this node. Can filter on lang
:param key: Predicate of the triple
:param lang: Language of the triple if applicable
:rtype: Literal or BNode or URIRef
"""
if lang is not None:
for o in self.graph.ob... | def function[get, parameter[self, key, lang]]:
constant[ Returns triple related to this node. Can filter on lang
:param key: Predicate of the triple
:param lang: Language of the triple if applicable
:rtype: Literal or BNode or URIRef
]
if compare[name[lang] is_not consta... | keyword[def] identifier[get] ( identifier[self] , identifier[key] , identifier[lang] = keyword[None] ):
literal[string]
keyword[if] identifier[lang] keyword[is] keyword[not] keyword[None] :
keyword[for] identifier[o] keyword[in] identifier[self] . identifier[graph] . identifier[... | def get(self, key, lang=None):
""" Returns triple related to this node. Can filter on lang
:param key: Predicate of the triple
:param lang: Language of the triple if applicable
:rtype: Literal or BNode or URIRef
"""
if lang is not None:
for o in self.graph.objects(self.a... |
def totp(key, format='dec6', period=30, t=None, hash=hashlib.sha1):
'''
Compute a TOTP value as prescribed by OATH specifications.
:param key:
the TOTP key given as an hexadecimal string
:param format:
the output format, can be:
- hex, for a variable length ... | def function[totp, parameter[key, format, period, t, hash]]:
constant[
Compute a TOTP value as prescribed by OATH specifications.
:param key:
the TOTP key given as an hexadecimal string
:param format:
the output format, can be:
- hex, for a variable leng... | keyword[def] identifier[totp] ( identifier[key] , identifier[format] = literal[string] , identifier[period] = literal[int] , identifier[t] = keyword[None] , identifier[hash] = identifier[hashlib] . identifier[sha1] ):
literal[string]
keyword[if] identifier[t] keyword[is] keyword[None] :
identif... | def totp(key, format='dec6', period=30, t=None, hash=hashlib.sha1):
"""
Compute a TOTP value as prescribed by OATH specifications.
:param key:
the TOTP key given as an hexadecimal string
:param format:
the output format, can be:
- hex, for a variable length ... |
def list_metrics(self, project, page_size=None, page_token=None):
"""List metrics for the project associated with this client.
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/list
:type project: str
:param project: ID of the project whose metrics... | def function[list_metrics, parameter[self, project, page_size, page_token]]:
constant[List metrics for the project associated with this client.
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/list
:type project: str
:param project: ID of the proj... | keyword[def] identifier[list_metrics] ( identifier[self] , identifier[project] , identifier[page_size] = keyword[None] , identifier[page_token] = keyword[None] ):
literal[string]
identifier[extra_params] ={}
keyword[if] identifier[page_size] keyword[is] keyword[not] keyword[None] :
... | def list_metrics(self, project, page_size=None, page_token=None):
"""List metrics for the project associated with this client.
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/list
:type project: str
:param project: ID of the project whose metrics are... |
def get_filename(self, checksum):
"""
:param checksum: checksum
:return: filename no storage base part
"""
filename = None
for _filename, metadata in self._log.items():
if metadata['checksum'] == checksum:
filename = _filename
b... | def function[get_filename, parameter[self, checksum]]:
constant[
:param checksum: checksum
:return: filename no storage base part
]
variable[filename] assign[=] constant[None]
for taget[tuple[[<ast.Name object at 0x7da1b1176260>, <ast.Name object at 0x7da1b11764d0>]]] in ... | keyword[def] identifier[get_filename] ( identifier[self] , identifier[checksum] ):
literal[string]
identifier[filename] = keyword[None]
keyword[for] identifier[_filename] , identifier[metadata] keyword[in] identifier[self] . identifier[_log] . identifier[items] ():
keyword... | def get_filename(self, checksum):
"""
:param checksum: checksum
:return: filename no storage base part
"""
filename = None
for (_filename, metadata) in self._log.items():
if metadata['checksum'] == checksum:
filename = _filename
break # depends on [co... |
def _p2_unicode_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
""" Encode Unicode as UTF-8 and parse as CSV.
This is needed since Python 2's `csv` doesn't do Unicode.
Kudos: https://docs.python.org/2/library/csv.html#examples
:param unicode_csv_data: The Unicode stream to parse.
... | def function[_p2_unicode_reader, parameter[unicode_csv_data, dialect]]:
constant[ Encode Unicode as UTF-8 and parse as CSV.
This is needed since Python 2's `csv` doesn't do Unicode.
Kudos: https://docs.python.org/2/library/csv.html#examples
:param unicode_csv_data: The Unicode stream ... | keyword[def] identifier[_p2_unicode_reader] ( identifier[unicode_csv_data] , identifier[dialect] = identifier[csv] . identifier[excel] ,** identifier[kwargs] ):
literal[string]
identifier[utf8_csv_data] = identifier[_utf_8_encoder] ( identifier[unicode_csv_data] )
identifier[csv_reader] = i... | def _p2_unicode_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
""" Encode Unicode as UTF-8 and parse as CSV.
This is needed since Python 2's `csv` doesn't do Unicode.
Kudos: https://docs.python.org/2/library/csv.html#examples
:param unicode_csv_data: The Unicode stream to parse.
... |
def set_table(self, schema, **kwargs):
"""
add the table to the db
schema -- Schema() -- contains all the information about the table
"""
with self.connection(**kwargs) as connection:
kwargs['connection'] = connection
if self.has_table(str(schema), **kwar... | def function[set_table, parameter[self, schema]]:
constant[
add the table to the db
schema -- Schema() -- contains all the information about the table
]
with call[name[self].connection, parameter[]] begin[:]
call[name[kwargs]][constant[connection]] assign[=] name... | keyword[def] identifier[set_table] ( identifier[self] , identifier[schema] ,** identifier[kwargs] ):
literal[string]
keyword[with] identifier[self] . identifier[connection] (** identifier[kwargs] ) keyword[as] identifier[connection] :
identifier[kwargs] [ literal[string] ]= identifie... | def set_table(self, schema, **kwargs):
"""
add the table to the db
schema -- Schema() -- contains all the information about the table
"""
with self.connection(**kwargs) as connection:
kwargs['connection'] = connection
if self.has_table(str(schema), **kwargs):
... |
def isEdgeCollection(cls, name) :
"""return true or false wether 'name' is the name of an edge collection."""
try :
col = cls.getCollectionClass(name)
return issubclass(col, Edges)
except KeyError :
return False | def function[isEdgeCollection, parameter[cls, name]]:
constant[return true or false wether 'name' is the name of an edge collection.]
<ast.Try object at 0x7da1b0f5a3e0> | keyword[def] identifier[isEdgeCollection] ( identifier[cls] , identifier[name] ):
literal[string]
keyword[try] :
identifier[col] = identifier[cls] . identifier[getCollectionClass] ( identifier[name] )
keyword[return] identifier[issubclass] ( identifier[col] , identifier[E... | def isEdgeCollection(cls, name):
"""return true or false wether 'name' is the name of an edge collection."""
try:
col = cls.getCollectionClass(name)
return issubclass(col, Edges) # depends on [control=['try'], data=[]]
except KeyError:
return False # depends on [control=['except'],... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.