code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _iterate_prefix(self, callsign, timestamp=timestamp_now):
"""truncate call until it corresponds to a Prefix in the database"""
prefix = callsign
if re.search('(VK|AX|VI)9[A-Z]{3}', callsign): #special rule for VK9 calls
if timestamp > datetime(2006,1,1, tzinfo=UTC):
... | def function[_iterate_prefix, parameter[self, callsign, timestamp]]:
constant[truncate call until it corresponds to a Prefix in the database]
variable[prefix] assign[=] name[callsign]
if call[name[re].search, parameter[constant[(VK|AX|VI)9[A-Z]{3}], name[callsign]]] begin[:]
if c... | keyword[def] identifier[_iterate_prefix] ( identifier[self] , identifier[callsign] , identifier[timestamp] = identifier[timestamp_now] ):
literal[string]
identifier[prefix] = identifier[callsign]
keyword[if] identifier[re] . identifier[search] ( literal[string] , identifier[callsign] ):... | def _iterate_prefix(self, callsign, timestamp=timestamp_now):
"""truncate call until it corresponds to a Prefix in the database"""
prefix = callsign
if re.search('(VK|AX|VI)9[A-Z]{3}', callsign): #special rule for VK9 calls
if timestamp > datetime(2006, 1, 1, tzinfo=UTC):
prefix = calls... |
def read_json_document(title):
"""
Reads in a json document and returns a native python
datastructure.
"""
if not title.endswith('.json'):
juicer.utils.Log.log_warn("File name (%s) does not end with '.json', appending it automatically." % title)
title += '.json'
if not os.path.e... | def function[read_json_document, parameter[title]]:
constant[
Reads in a json document and returns a native python
datastructure.
]
if <ast.UnaryOp object at 0x7da207f99cf0> begin[:]
call[name[juicer].utils.Log.log_warn, parameter[binary_operation[constant[File name (%s) does... | keyword[def] identifier[read_json_document] ( identifier[title] ):
literal[string]
keyword[if] keyword[not] identifier[title] . identifier[endswith] ( literal[string] ):
identifier[juicer] . identifier[utils] . identifier[Log] . identifier[log_warn] ( literal[string] % identifier[title] )
... | def read_json_document(title):
"""
Reads in a json document and returns a native python
datastructure.
"""
if not title.endswith('.json'):
juicer.utils.Log.log_warn("File name (%s) does not end with '.json', appending it automatically." % title)
title += '.json' # depends on [contro... |
def fastq_to_csv(in_file, fastq_format, work_dir):
"""Convert a fastq file into a CSV of phred quality scores.
"""
out_file = "%s.csv" % (os.path.splitext(os.path.basename(in_file))[0])
out_file = os.path.join(work_dir, out_file)
if not (os.path.exists(out_file) and os.path.getsize(out_file) > 0):
... | def function[fastq_to_csv, parameter[in_file, fastq_format, work_dir]]:
constant[Convert a fastq file into a CSV of phred quality scores.
]
variable[out_file] assign[=] binary_operation[constant[%s.csv] <ast.Mod object at 0x7da2590d6920> call[call[name[os].path.splitext, parameter[call[name[os].path... | keyword[def] identifier[fastq_to_csv] ( identifier[in_file] , identifier[fastq_format] , identifier[work_dir] ):
literal[string]
identifier[out_file] = literal[string] %( identifier[os] . identifier[path] . identifier[splitext] ( identifier[os] . identifier[path] . identifier[basename] ( identifier[in_file... | def fastq_to_csv(in_file, fastq_format, work_dir):
"""Convert a fastq file into a CSV of phred quality scores.
"""
out_file = '%s.csv' % os.path.splitext(os.path.basename(in_file))[0]
out_file = os.path.join(work_dir, out_file)
if not (os.path.exists(out_file) and os.path.getsize(out_file) > 0):
... |
def trim_field_key(document, field_key):
"""
Returns the smallest delimited version of field_key that
is an attribute on document.
return (key, left_over_array)
"""
trimming = True
left_over_key_values = []
current_key = field_key
while trimming and current_key:
if hasattr(d... | def function[trim_field_key, parameter[document, field_key]]:
constant[
Returns the smallest delimited version of field_key that
is an attribute on document.
return (key, left_over_array)
]
variable[trimming] assign[=] constant[True]
variable[left_over_key_values] assign[=] list... | keyword[def] identifier[trim_field_key] ( identifier[document] , identifier[field_key] ):
literal[string]
identifier[trimming] = keyword[True]
identifier[left_over_key_values] =[]
identifier[current_key] = identifier[field_key]
keyword[while] identifier[trimming] keyword[and] identifier... | def trim_field_key(document, field_key):
"""
Returns the smallest delimited version of field_key that
is an attribute on document.
return (key, left_over_array)
"""
trimming = True
left_over_key_values = []
current_key = field_key
while trimming and current_key:
if hasattr(d... |
def init_app(self, app):
"""Flask application initialization."""
state = _InvenioCSLRESTState(app)
app.extensions['invenio-csl-rest'] = state
return state | def function[init_app, parameter[self, app]]:
constant[Flask application initialization.]
variable[state] assign[=] call[name[_InvenioCSLRESTState], parameter[name[app]]]
call[name[app].extensions][constant[invenio-csl-rest]] assign[=] name[state]
return[name[state]] | keyword[def] identifier[init_app] ( identifier[self] , identifier[app] ):
literal[string]
identifier[state] = identifier[_InvenioCSLRESTState] ( identifier[app] )
identifier[app] . identifier[extensions] [ literal[string] ]= identifier[state]
keyword[return] identifier[state] | def init_app(self, app):
"""Flask application initialization."""
state = _InvenioCSLRESTState(app)
app.extensions['invenio-csl-rest'] = state
return state |
def send_handle_delete_request(self, **args):
'''
Send a HTTP DELETE request to the handle server to delete either an
entire handle or to some specified values from a handle record,
using the requests module.
:param handle: The handle.
:param indices: Optional. A... | def function[send_handle_delete_request, parameter[self]]:
constant[
Send a HTTP DELETE request to the handle server to delete either an
entire handle or to some specified values from a handle record,
using the requests module.
:param handle: The handle.
:param i... | keyword[def] identifier[send_handle_delete_request] ( identifier[self] ,** identifier[args] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[__has_write_access] :
keyword[raise] identifier[HandleAuthenticationError] ( identifier[msg] = identifier[s... | def send_handle_delete_request(self, **args):
"""
Send a HTTP DELETE request to the handle server to delete either an
entire handle or to some specified values from a handle record,
using the requests module.
:param handle: The handle.
:param indices: Optional. A lis... |
def hostname(self):
"""Get the hostname that this connection is associated with"""
from six.moves.urllib.parse import urlparse
return urlparse(self._base_url).netloc.split(':', 1)[0] | def function[hostname, parameter[self]]:
constant[Get the hostname that this connection is associated with]
from relative_module[six.moves.urllib.parse] import module[urlparse]
return[call[call[call[name[urlparse], parameter[name[self]._base_url]].netloc.split, parameter[constant[:], constant[1]]]][cons... | keyword[def] identifier[hostname] ( identifier[self] ):
literal[string]
keyword[from] identifier[six] . identifier[moves] . identifier[urllib] . identifier[parse] keyword[import] identifier[urlparse]
keyword[return] identifier[urlparse] ( identifier[self] . identifier[_base_url] ). id... | def hostname(self):
"""Get the hostname that this connection is associated with"""
from six.moves.urllib.parse import urlparse
return urlparse(self._base_url).netloc.split(':', 1)[0] |
def pad_sequences(sequences, maxlen=None, dtype='int32', padding='post', truncating='pre', value=0.):
"""Pads each sequence to the same length:
the length of the longest sequence.
If maxlen is provided, any sequence longer
than maxlen is truncated to maxlen.
Truncation happens off either the beginni... | def function[pad_sequences, parameter[sequences, maxlen, dtype, padding, truncating, value]]:
constant[Pads each sequence to the same length:
the length of the longest sequence.
If maxlen is provided, any sequence longer
than maxlen is truncated to maxlen.
Truncation happens off either the begin... | keyword[def] identifier[pad_sequences] ( identifier[sequences] , identifier[maxlen] = keyword[None] , identifier[dtype] = literal[string] , identifier[padding] = literal[string] , identifier[truncating] = literal[string] , identifier[value] = literal[int] ):
literal[string]
identifier[lengths] =[ identifie... | def pad_sequences(sequences, maxlen=None, dtype='int32', padding='post', truncating='pre', value=0.0):
"""Pads each sequence to the same length:
the length of the longest sequence.
If maxlen is provided, any sequence longer
than maxlen is truncated to maxlen.
Truncation happens off either the beginn... |
def addRasters(self,
rasterType,
itemIds=None,
serviceUrl=None,
computeStatistics=False,
buildPyramids=False,
buildThumbnail=False,
minimumCellSizeFactor=None,
maximumCellSizeFactor=None,
attributes=None,
... | def function[addRasters, parameter[self, rasterType, itemIds, serviceUrl, computeStatistics, buildPyramids, buildThumbnail, minimumCellSizeFactor, maximumCellSizeFactor, attributes, geodataTransforms, geodataTransformApplyMethod]]:
constant[
This operation is supported at 10.1 and later.
The Add... | keyword[def] identifier[addRasters] ( identifier[self] ,
identifier[rasterType] ,
identifier[itemIds] = keyword[None] ,
identifier[serviceUrl] = keyword[None] ,
identifier[computeStatistics] = keyword[False] ,
identifier[buildPyramids] = keyword[False] ,
identifier[buildThumbnail] = keyword[False] ,
identifier... | def addRasters(self, rasterType, itemIds=None, serviceUrl=None, computeStatistics=False, buildPyramids=False, buildThumbnail=False, minimumCellSizeFactor=None, maximumCellSizeFactor=None, attributes=None, geodataTransforms=None, geodataTransformApplyMethod='esriGeodataTransformApplyAppend'):
"""
This operat... |
def custom_display(lhs, rhs):
"""
lhs: left hand side
rhs: right hand side
This function serves to inject the string for the left hand side
of an assignment
"""
# This code is mainly copied from IPython/display.py
# (IPython version 2.3.0)
kwargs = {}
raw = kwargs.get('raw', Fa... | def function[custom_display, parameter[lhs, rhs]]:
constant[
lhs: left hand side
rhs: right hand side
This function serves to inject the string for the left hand side
of an assignment
]
variable[kwargs] assign[=] dictionary[[], []]
variable[raw] assign[=] call[name[kwargs].g... | keyword[def] identifier[custom_display] ( identifier[lhs] , identifier[rhs] ):
literal[string]
identifier[kwargs] ={}
identifier[raw] = identifier[kwargs] . identifier[get] ( literal[string] , keyword[False] )
identifier[include] = identifier[kwargs] . identifier[get] ( literal[string]... | def custom_display(lhs, rhs):
"""
lhs: left hand side
rhs: right hand side
This function serves to inject the string for the left hand side
of an assignment
"""
# This code is mainly copied from IPython/display.py
# (IPython version 2.3.0)
kwargs = {}
raw = kwargs.get('raw', Fal... |
def comic_archive_uncompress(filename, image_format):
"""
Uncompress comic archives.
Return the name of the working directory we uncompressed into.
"""
if not Settings.comics:
report = ['Skipping archive file: {}'.format(filename)]
return None, ReportStats(filename, report=report)
... | def function[comic_archive_uncompress, parameter[filename, image_format]]:
constant[
Uncompress comic archives.
Return the name of the working directory we uncompressed into.
]
if <ast.UnaryOp object at 0x7da1b19107c0> begin[:]
variable[report] assign[=] list[[<ast.Call obje... | keyword[def] identifier[comic_archive_uncompress] ( identifier[filename] , identifier[image_format] ):
literal[string]
keyword[if] keyword[not] identifier[Settings] . identifier[comics] :
identifier[report] =[ literal[string] . identifier[format] ( identifier[filename] )]
keyword[return... | def comic_archive_uncompress(filename, image_format):
"""
Uncompress comic archives.
Return the name of the working directory we uncompressed into.
"""
if not Settings.comics:
report = ['Skipping archive file: {}'.format(filename)]
return (None, ReportStats(filename, report=report))... |
def send_bounced_warning(person, leader_list):
"""Sends an email to each project leader for person
informing them that person's email has bounced"""
context = CONTEXT.copy()
context['person'] = person
for lp in leader_list:
leader = lp['leader']
context['project'] = lp['project']
... | def function[send_bounced_warning, parameter[person, leader_list]]:
constant[Sends an email to each project leader for person
informing them that person's email has bounced]
variable[context] assign[=] call[name[CONTEXT].copy, parameter[]]
call[name[context]][constant[person]] assign[=] name... | keyword[def] identifier[send_bounced_warning] ( identifier[person] , identifier[leader_list] ):
literal[string]
identifier[context] = identifier[CONTEXT] . identifier[copy] ()
identifier[context] [ literal[string] ]= identifier[person]
keyword[for] identifier[lp] keyword[in] identifier[leade... | def send_bounced_warning(person, leader_list):
"""Sends an email to each project leader for person
informing them that person's email has bounced"""
context = CONTEXT.copy()
context['person'] = person
for lp in leader_list:
leader = lp['leader']
context['project'] = lp['project']
... |
def create_attributes(klass, attributes, previous_object=None):
"""
Attributes for resource creation.
"""
return {
'name': attributes.get(
'name',
previous_object.name if previous_object is not None else ''
),
'descript... | def function[create_attributes, parameter[klass, attributes, previous_object]]:
constant[
Attributes for resource creation.
]
return[dictionary[[<ast.Constant object at 0x7da1b115eef0>, <ast.Constant object at 0x7da1b115e920>, <ast.Constant object at 0x7da1b115f490>], [<ast.Call object at 0x... | keyword[def] identifier[create_attributes] ( identifier[klass] , identifier[attributes] , identifier[previous_object] = keyword[None] ):
literal[string]
keyword[return] {
literal[string] : identifier[attributes] . identifier[get] (
literal[string] ,
identifier[previous_o... | def create_attributes(klass, attributes, previous_object=None):
"""
Attributes for resource creation.
""" # Will default to master if empty
return {'name': attributes.get('name', previous_object.name if previous_object is not None else ''), 'description': attributes.get('description', previous_... |
def create(dataset, target, feature=None, model = 'resnet-50',
l2_penalty=0.01,
l1_penalty=0.0,
solver='auto', feature_rescaling=True,
convergence_threshold = _DEFAULT_SOLVER_OPTIONS['convergence_threshold'],
step_size = _DEFAULT_SOLVER_OPTIONS['step_size'],
lbfgs_memory_level = _DEFAULT_SOLVER... | def function[create, parameter[dataset, target, feature, model, l2_penalty, l1_penalty, solver, feature_rescaling, convergence_threshold, step_size, lbfgs_memory_level, max_iterations, class_weights, validation_set, verbose, seed, batch_size]]:
constant[
Create a :class:`ImageClassifier` model.
Paramet... | keyword[def] identifier[create] ( identifier[dataset] , identifier[target] , identifier[feature] = keyword[None] , identifier[model] = literal[string] ,
identifier[l2_penalty] = literal[int] ,
identifier[l1_penalty] = literal[int] ,
identifier[solver] = literal[string] , identifier[feature_rescaling] = keyword[Tru... | def create(dataset, target, feature=None, model='resnet-50', l2_penalty=0.01, l1_penalty=0.0, solver='auto', feature_rescaling=True, convergence_threshold=_DEFAULT_SOLVER_OPTIONS['convergence_threshold'], step_size=_DEFAULT_SOLVER_OPTIONS['step_size'], lbfgs_memory_level=_DEFAULT_SOLVER_OPTIONS['lbfgs_memory_level'], m... |
def push(self, url, title=''):
"""
Pushes the url into the history stack at the current index.
:param url | <str>
:return <bool> | changed
"""
# ignore refreshes of the top level
if self.currentUrl() == url or self._blockStack:
... | def function[push, parameter[self, url, title]]:
constant[
Pushes the url into the history stack at the current index.
:param url | <str>
:return <bool> | changed
]
if <ast.BoolOp object at 0x7da20c795ea0> begin[:]
return[constant[False]... | keyword[def] identifier[push] ( identifier[self] , identifier[url] , identifier[title] = literal[string] ):
literal[string]
keyword[if] identifier[self] . identifier[currentUrl] ()== identifier[url] keyword[or] identifier[self] . identifier[_blockStack] :
keyword[return] k... | def push(self, url, title=''):
"""
Pushes the url into the history stack at the current index.
:param url | <str>
:return <bool> | changed
"""
# ignore refreshes of the top level
if self.currentUrl() == url or self._blockStack:
return False ... |
def newton_solver(f, x0, lb=None, ub=None, infos=False, verbose=False, maxit=50, tol=1e-8, eps=1e-5, numdiff=False):
'''Solves many independent systems f(x)=0 simultaneously using a simple gradient descent.
:param f: objective function to be solved with values p x N . The second output argument represents the d... | def function[newton_solver, parameter[f, x0, lb, ub, infos, verbose, maxit, tol, eps, numdiff]]:
constant[Solves many independent systems f(x)=0 simultaneously using a simple gradient descent.
:param f: objective function to be solved with values p x N . The second output argument represents the derivative ... | keyword[def] identifier[newton_solver] ( identifier[f] , identifier[x0] , identifier[lb] = keyword[None] , identifier[ub] = keyword[None] , identifier[infos] = keyword[False] , identifier[verbose] = keyword[False] , identifier[maxit] = literal[int] , identifier[tol] = literal[int] , identifier[eps] = literal[int] , i... | def newton_solver(f, x0, lb=None, ub=None, infos=False, verbose=False, maxit=50, tol=1e-08, eps=1e-05, numdiff=False):
"""Solves many independent systems f(x)=0 simultaneously using a simple gradient descent.
:param f: objective function to be solved with values p x N . The second output argument represents the... |
def create(self, trade_type, body, total_fee, notify_url, client_ip=None,
user_id=None, out_trade_no=None, detail=None, attach=None,
fee_type='CNY', time_start=None, time_expire=None, goods_tag=None,
product_id=None, device_info=None, limit_pay=None, scene_info=None, sub_use... | def function[create, parameter[self, trade_type, body, total_fee, notify_url, client_ip, user_id, out_trade_no, detail, attach, fee_type, time_start, time_expire, goods_tag, product_id, device_info, limit_pay, scene_info, sub_user_id]]:
constant[
统一下单接口
:param trade_type: 交易类型,取值如下:JSAPI,NATIVE... | keyword[def] identifier[create] ( identifier[self] , identifier[trade_type] , identifier[body] , identifier[total_fee] , identifier[notify_url] , identifier[client_ip] = keyword[None] ,
identifier[user_id] = keyword[None] , identifier[out_trade_no] = keyword[None] , identifier[detail] = keyword[None] , identifier[at... | def create(self, trade_type, body, total_fee, notify_url, client_ip=None, user_id=None, out_trade_no=None, detail=None, attach=None, fee_type='CNY', time_start=None, time_expire=None, goods_tag=None, product_id=None, device_info=None, limit_pay=None, scene_info=None, sub_user_id=None):
"""
统一下单接口
:... |
def clean_email_or_username(self):
"""
Clean email form field
Returns:
str: the cleaned value, converted to an email address (or an empty string)
"""
email_or_username = self.cleaned_data[self.Fields.EMAIL_OR_USERNAME].strip()
if not email_or_username:
... | def function[clean_email_or_username, parameter[self]]:
constant[
Clean email form field
Returns:
str: the cleaned value, converted to an email address (or an empty string)
]
variable[email_or_username] assign[=] call[call[name[self].cleaned_data][name[self].Fields.E... | keyword[def] identifier[clean_email_or_username] ( identifier[self] ):
literal[string]
identifier[email_or_username] = identifier[self] . identifier[cleaned_data] [ identifier[self] . identifier[Fields] . identifier[EMAIL_OR_USERNAME] ]. identifier[strip] ()
keyword[if] keyword[not] ide... | def clean_email_or_username(self):
"""
Clean email form field
Returns:
str: the cleaned value, converted to an email address (or an empty string)
"""
email_or_username = self.cleaned_data[self.Fields.EMAIL_OR_USERNAME].strip()
if not email_or_username:
# The fiel... |
def GetCBVs(campaign, model='nPLD', clobber=False, **kwargs):
'''
Computes the CBVs for a given campaign.
:param int campaign: The campaign number
:param str model: The name of the :py:obj:`everest` model. Default `nPLD`
:param bool clobber: Overwrite existing files? Default `False`
'''
#... | def function[GetCBVs, parameter[campaign, model, clobber]]:
constant[
Computes the CBVs for a given campaign.
:param int campaign: The campaign number
:param str model: The name of the :py:obj:`everest` model. Default `nPLD`
:param bool clobber: Overwrite existing files? Default `False`
]
... | keyword[def] identifier[GetCBVs] ( identifier[campaign] , identifier[model] = literal[string] , identifier[clobber] = keyword[False] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[len] ( identifier[logging] . identifier[getLogger] (). identifier[handlers] )== literal[int] :
... | def GetCBVs(campaign, model='nPLD', clobber=False, **kwargs):
"""
Computes the CBVs for a given campaign.
:param int campaign: The campaign number
:param str model: The name of the :py:obj:`everest` model. Default `nPLD`
:param bool clobber: Overwrite existing files? Default `False`
"""
# ... |
def plot_type(self, func, mins, maxs, precision, kind):
"""Plots function
:param func: function to plot
:param mins: minimum of values (x, y ...)
:param maxs: maximum of values (x, y ...)
:param precision: precision to plot
:param kind: kind of plot, "slice", "countour"
... | def function[plot_type, parameter[self, func, mins, maxs, precision, kind]]:
constant[Plots function
:param func: function to plot
:param mins: minimum of values (x, y ...)
:param maxs: maximum of values (x, y ...)
:param precision: precision to plot
:param kind: kind of... | keyword[def] identifier[plot_type] ( identifier[self] , identifier[func] , identifier[mins] , identifier[maxs] , identifier[precision] , identifier[kind] ):
literal[string]
identifier[min_x] , identifier[min_y] , identifier[min_z] = identifier[mins] [ literal[int] ], identifier[mins] [ literal[int... | def plot_type(self, func, mins, maxs, precision, kind):
"""Plots function
:param func: function to plot
:param mins: minimum of values (x, y ...)
:param maxs: maximum of values (x, y ...)
:param precision: precision to plot
:param kind: kind of plot, "slice", "countour"
... |
def __get_issue_assignees(self, raw_assignees):
"""Get issue assignees"""
assignees = []
for ra in raw_assignees:
assignees.append(self.__get_user(ra['login']))
return assignees | def function[__get_issue_assignees, parameter[self, raw_assignees]]:
constant[Get issue assignees]
variable[assignees] assign[=] list[[]]
for taget[name[ra]] in starred[name[raw_assignees]] begin[:]
call[name[assignees].append, parameter[call[name[self].__get_user, parameter[call... | keyword[def] identifier[__get_issue_assignees] ( identifier[self] , identifier[raw_assignees] ):
literal[string]
identifier[assignees] =[]
keyword[for] identifier[ra] keyword[in] identifier[raw_assignees] :
identifier[assignees] . identifier[append] ( identifier[self] . id... | def __get_issue_assignees(self, raw_assignees):
"""Get issue assignees"""
assignees = []
for ra in raw_assignees:
assignees.append(self.__get_user(ra['login'])) # depends on [control=['for'], data=['ra']]
return assignees |
def extract(self):
"""Extracts the raw firmware file from its compact format
Extracts the raw firmware file from its compact file format (already
set as attribute in FirmwareImageControllerBase constructor).
:raises: InvalidInputError, if raw firmware file not found
:raises: Ima... | def function[extract, parameter[self]]:
constant[Extracts the raw firmware file from its compact format
Extracts the raw firmware file from its compact file format (already
set as attribute in FirmwareImageControllerBase constructor).
:raises: InvalidInputError, if raw firmware file not... | keyword[def] identifier[extract] ( identifier[self] ):
literal[string]
identifier[target_file] = identifier[self] . identifier[fw_file]
identifier[common] . identifier[add_exec_permission_to] ( identifier[target_file] )
identifier[temp_dir] = identifier[tempfile] . ident... | def extract(self):
"""Extracts the raw firmware file from its compact format
Extracts the raw firmware file from its compact file format (already
set as attribute in FirmwareImageControllerBase constructor).
:raises: InvalidInputError, if raw firmware file not found
:raises: ImageEx... |
def badge_width(self):
"""The total width of badge.
>>> badge = Badge('pylint', '5', font_name='DejaVu Sans,Verdana,Geneva,sans-serif',
... font_size=11)
>>> badge.badge_width
91
"""
return self.get_text_width(' ' + ' ' * int(float(self.num_paddin... | def function[badge_width, parameter[self]]:
constant[The total width of badge.
>>> badge = Badge('pylint', '5', font_name='DejaVu Sans,Verdana,Geneva,sans-serif',
... font_size=11)
>>> badge.badge_width
91
]
return[binary_operation[binary_operation[call... | keyword[def] identifier[badge_width] ( identifier[self] ):
literal[string]
keyword[return] identifier[self] . identifier[get_text_width] ( literal[string] + literal[string] * identifier[int] ( identifier[float] ( identifier[self] . identifier[num_padding_chars] )* literal[int] ))+ identifier[self]... | def badge_width(self):
"""The total width of badge.
>>> badge = Badge('pylint', '5', font_name='DejaVu Sans,Verdana,Geneva,sans-serif',
... font_size=11)
>>> badge.badge_width
91
"""
return self.get_text_width(' ' + ' ' * int(float(self.num_padding_chars)... |
def calc_environment_entropy(world, world_size=(60, 60),
exclude_desert=False):
"""
Calculate the Shannon entropy of a given environment, treating each niche
(where niches are defined by regions in which different sets of resources
are rewarded) as a category. The environmen... | def function[calc_environment_entropy, parameter[world, world_size, exclude_desert]]:
constant[
Calculate the Shannon entropy of a given environment, treating each niche
(where niches are defined by regions in which different sets of resources
are rewarded) as a category. The environment is specifie... | keyword[def] identifier[calc_environment_entropy] ( identifier[world] , identifier[world_size] =( literal[int] , literal[int] ),
identifier[exclude_desert] = keyword[False] ):
literal[string]
identifier[niches] = identifier[make_niche_dictionary] ( identifier[world] , identifier[world_size] )
keywo... | def calc_environment_entropy(world, world_size=(60, 60), exclude_desert=False):
"""
Calculate the Shannon entropy of a given environment, treating each niche
(where niches are defined by regions in which different sets of resources
are rewarded) as a category. The environment is specified with the
f... |
def add_code_cell(self, content, tags=None):
"""
Class method responsible for adding a code cell with content 'content' to the
Notebook object.
----------
Parameters
----------
content : str
Code in a string format to include in the cell (triple quote... | def function[add_code_cell, parameter[self, content, tags]]:
constant[
Class method responsible for adding a code cell with content 'content' to the
Notebook object.
----------
Parameters
----------
content : str
Code in a string format to include in ... | keyword[def] identifier[add_code_cell] ( identifier[self] , identifier[content] , identifier[tags] = keyword[None] ):
literal[string]
identifier[self] . identifier[notebook] [ literal[string] ]. identifier[append] ( identifier[nb] . identifier[v4] . identifier[new_code_cell] ( identifier[content] ,... | def add_code_cell(self, content, tags=None):
"""
Class method responsible for adding a code cell with content 'content' to the
Notebook object.
----------
Parameters
----------
content : str
Code in a string format to include in the cell (triple quote for... |
def calculate_bins(array, _=None, *args, **kwargs) -> BinningBase:
"""Find optimal binning from arguments.
Parameters
----------
array: arraylike
Data from which the bins should be decided (sometimes used, sometimes not)
_: int or str or Callable or arraylike or Iterable or BinningBase
... | def function[calculate_bins, parameter[array, _]]:
constant[Find optimal binning from arguments.
Parameters
----------
array: arraylike
Data from which the bins should be decided (sometimes used, sometimes not)
_: int or str or Callable or arraylike or Iterable or BinningBase
To... | keyword[def] identifier[calculate_bins] ( identifier[array] , identifier[_] = keyword[None] ,* identifier[args] ,** identifier[kwargs] )-> identifier[BinningBase] :
literal[string]
keyword[if] identifier[array] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[kwargs] . identifi... | def calculate_bins(array, _=None, *args, **kwargs) -> BinningBase:
"""Find optimal binning from arguments.
Parameters
----------
array: arraylike
Data from which the bins should be decided (sometimes used, sometimes not)
_: int or str or Callable or arraylike or Iterable or BinningBase
... |
def _get_dns_entry_trs(self):
"""
Return the TR elements holding the DNS entries.
"""
from bs4 import BeautifulSoup
dns_list_response = self.session.get(
self.URLS['dns'].format(self.domain_id))
self._log('DNS list', dns_list_response)
assert dns_list_... | def function[_get_dns_entry_trs, parameter[self]]:
constant[
Return the TR elements holding the DNS entries.
]
from relative_module[bs4] import module[BeautifulSoup]
variable[dns_list_response] assign[=] call[name[self].session.get, parameter[call[call[name[self].URLS][constant[dns]]... | keyword[def] identifier[_get_dns_entry_trs] ( identifier[self] ):
literal[string]
keyword[from] identifier[bs4] keyword[import] identifier[BeautifulSoup]
identifier[dns_list_response] = identifier[self] . identifier[session] . identifier[get] (
identifier[self] . identifier[UR... | def _get_dns_entry_trs(self):
"""
Return the TR elements holding the DNS entries.
"""
from bs4 import BeautifulSoup
dns_list_response = self.session.get(self.URLS['dns'].format(self.domain_id))
self._log('DNS list', dns_list_response)
assert dns_list_response.status_code == 200, 'Cou... |
def plot_pca_2d_projection(clf, X, y, title='PCA 2-D Projection',
biplot=False, feature_labels=None,
ax=None, figsize=None, cmap='Spectral',
title_fontsize="large", text_fontsize="medium"):
"""Plots the 2-dimensional projection of PCA ... | def function[plot_pca_2d_projection, parameter[clf, X, y, title, biplot, feature_labels, ax, figsize, cmap, title_fontsize, text_fontsize]]:
constant[Plots the 2-dimensional projection of PCA on a given dataset.
Args:
clf: Fitted PCA instance that can ``transform`` given data set into 2
... | keyword[def] identifier[plot_pca_2d_projection] ( identifier[clf] , identifier[X] , identifier[y] , identifier[title] = literal[string] ,
identifier[biplot] = keyword[False] , identifier[feature_labels] = keyword[None] ,
identifier[ax] = keyword[None] , identifier[figsize] = keyword[None] , identifier[cmap] = liter... | def plot_pca_2d_projection(clf, X, y, title='PCA 2-D Projection', biplot=False, feature_labels=None, ax=None, figsize=None, cmap='Spectral', title_fontsize='large', text_fontsize='medium'):
"""Plots the 2-dimensional projection of PCA on a given dataset.
Args:
clf: Fitted PCA instance that can ``transf... |
def create_pull_request(self, git_pull_request_to_create, repository_id, project=None, supports_iterations=None):
"""CreatePullRequest.
[Preview API] Create a pull request.
:param :class:`<GitPullRequest> <azure.devops.v5_1.git.models.GitPullRequest>` git_pull_request_to_create: The pull request... | def function[create_pull_request, parameter[self, git_pull_request_to_create, repository_id, project, supports_iterations]]:
constant[CreatePullRequest.
[Preview API] Create a pull request.
:param :class:`<GitPullRequest> <azure.devops.v5_1.git.models.GitPullRequest>` git_pull_request_to_create:... | keyword[def] identifier[create_pull_request] ( identifier[self] , identifier[git_pull_request_to_create] , identifier[repository_id] , identifier[project] = keyword[None] , identifier[supports_iterations] = keyword[None] ):
literal[string]
identifier[route_values] ={}
keyword[if] identifi... | def create_pull_request(self, git_pull_request_to_create, repository_id, project=None, supports_iterations=None):
"""CreatePullRequest.
[Preview API] Create a pull request.
:param :class:`<GitPullRequest> <azure.devops.v5_1.git.models.GitPullRequest>` git_pull_request_to_create: The pull request to ... |
def dispatch(self, block = False, timeout = None):
"""Get the next event from the queue and pass it to
the appropriate handlers.
:Parameters:
- `block`: wait for event if the queue is empty
- `timeout`: maximum time, in seconds, to wait if `block` is `True`
:Type... | def function[dispatch, parameter[self, block, timeout]]:
constant[Get the next event from the queue and pass it to
the appropriate handlers.
:Parameters:
- `block`: wait for event if the queue is empty
- `timeout`: maximum time, in seconds, to wait if `block` is `True`
... | keyword[def] identifier[dispatch] ( identifier[self] , identifier[block] = keyword[False] , identifier[timeout] = keyword[None] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] )
keyword[try] :
identifier[event] = identifier[self] . identifier[queue]... | def dispatch(self, block=False, timeout=None):
"""Get the next event from the queue and pass it to
the appropriate handlers.
:Parameters:
- `block`: wait for event if the queue is empty
- `timeout`: maximum time, in seconds, to wait if `block` is `True`
:Types:
... |
def _peersToDF(p):
'''internal'''
df = pd.DataFrame(p, columns=['symbol'])
_toDatetime(df)
_reindex(df, 'symbol')
df['peer'] = df.index
return df | def function[_peersToDF, parameter[p]]:
constant[internal]
variable[df] assign[=] call[name[pd].DataFrame, parameter[name[p]]]
call[name[_toDatetime], parameter[name[df]]]
call[name[_reindex], parameter[name[df], constant[symbol]]]
call[name[df]][constant[peer]] assign[=] name[df... | keyword[def] identifier[_peersToDF] ( identifier[p] ):
literal[string]
identifier[df] = identifier[pd] . identifier[DataFrame] ( identifier[p] , identifier[columns] =[ literal[string] ])
identifier[_toDatetime] ( identifier[df] )
identifier[_reindex] ( identifier[df] , literal[string] )
iden... | def _peersToDF(p):
"""internal"""
df = pd.DataFrame(p, columns=['symbol'])
_toDatetime(df)
_reindex(df, 'symbol')
df['peer'] = df.index
return df |
def stream(self):
"""Which stream, if any, the client is under"""
stream = self._p4dict.get('stream')
if stream:
return Stream(stream, self._connection) | def function[stream, parameter[self]]:
constant[Which stream, if any, the client is under]
variable[stream] assign[=] call[name[self]._p4dict.get, parameter[constant[stream]]]
if name[stream] begin[:]
return[call[name[Stream], parameter[name[stream], name[self]._connection]]] | keyword[def] identifier[stream] ( identifier[self] ):
literal[string]
identifier[stream] = identifier[self] . identifier[_p4dict] . identifier[get] ( literal[string] )
keyword[if] identifier[stream] :
keyword[return] identifier[Stream] ( identifier[stream] , identifier[self]... | def stream(self):
"""Which stream, if any, the client is under"""
stream = self._p4dict.get('stream')
if stream:
return Stream(stream, self._connection) # depends on [control=['if'], data=[]] |
def bytes(self):
r"""
Tuple with a CAPTCHA text and a BytesIO object.
Property calls self.image and saves image contents in a BytesIO
instance, returning CAPTCHA text and BytesIO as a tuple.
See: image.
:returns: ``tuple`` (CAPTCHA text, BytesIO object)
"""
... | def function[bytes, parameter[self]]:
constant[
Tuple with a CAPTCHA text and a BytesIO object.
Property calls self.image and saves image contents in a BytesIO
instance, returning CAPTCHA text and BytesIO as a tuple.
See: image.
:returns: ``tuple`` (CAPTCHA text, BytesI... | keyword[def] identifier[bytes] ( identifier[self] ):
literal[string]
identifier[text] , identifier[image] = identifier[self] . identifier[image]
identifier[bytes] = identifier[BytesIO] ()
identifier[image] . identifier[save] ( identifier[bytes] , identifier[format] = identifier[s... | def bytes(self):
"""
Tuple with a CAPTCHA text and a BytesIO object.
Property calls self.image and saves image contents in a BytesIO
instance, returning CAPTCHA text and BytesIO as a tuple.
See: image.
:returns: ``tuple`` (CAPTCHA text, BytesIO object)
"""
(text... |
def start (self):
'''
Starts (Subscribes) the client.
'''
self.sub = rospy.Subscriber(self.topic, ImageROS, self.__callback) | def function[start, parameter[self]]:
constant[
Starts (Subscribes) the client.
]
name[self].sub assign[=] call[name[rospy].Subscriber, parameter[name[self].topic, name[ImageROS], name[self].__callback]] | keyword[def] identifier[start] ( identifier[self] ):
literal[string]
identifier[self] . identifier[sub] = identifier[rospy] . identifier[Subscriber] ( identifier[self] . identifier[topic] , identifier[ImageROS] , identifier[self] . identifier[__callback] ) | def start(self):
"""
Starts (Subscribes) the client.
"""
self.sub = rospy.Subscriber(self.topic, ImageROS, self.__callback) |
def set_sail(self, angle):
'''
Set the angle of the sail to `angle` degrees
:param angle: sail angle
:type angle: float between -90 and 90
'''
angle = float(angle)
request = self.boatd.post({'value': float(angle)}, '/sail')
return request.get('result') | def function[set_sail, parameter[self, angle]]:
constant[
Set the angle of the sail to `angle` degrees
:param angle: sail angle
:type angle: float between -90 and 90
]
variable[angle] assign[=] call[name[float], parameter[name[angle]]]
variable[request] assign[=]... | keyword[def] identifier[set_sail] ( identifier[self] , identifier[angle] ):
literal[string]
identifier[angle] = identifier[float] ( identifier[angle] )
identifier[request] = identifier[self] . identifier[boatd] . identifier[post] ({ literal[string] : identifier[float] ( identifier[angle] )... | def set_sail(self, angle):
"""
Set the angle of the sail to `angle` degrees
:param angle: sail angle
:type angle: float between -90 and 90
"""
angle = float(angle)
request = self.boatd.post({'value': float(angle)}, '/sail')
return request.get('result') |
def _prepare_url_params(tile_id, bbox, end_date, start_date, absolute_orbit):
""" Constructs dict with URL params
:param tile_id: original tile identification string provided by ESA (e.g.
'S2A_OPER_MSI_L1C_TL_SGS__20160109T230542_A002870_T10UEV_N02.01')
:type tile_id: str
:param bbo... | def function[_prepare_url_params, parameter[tile_id, bbox, end_date, start_date, absolute_orbit]]:
constant[ Constructs dict with URL params
:param tile_id: original tile identification string provided by ESA (e.g.
'S2A_OPER_MSI_L1C_TL_SGS__20160109T230542_A002870_T10UEV_N02.01')
:t... | keyword[def] identifier[_prepare_url_params] ( identifier[tile_id] , identifier[bbox] , identifier[end_date] , identifier[start_date] , identifier[absolute_orbit] ):
literal[string]
identifier[url_params] ={
literal[string] : identifier[tile_id] ,
literal[string] : identifier[start_date] ,
l... | def _prepare_url_params(tile_id, bbox, end_date, start_date, absolute_orbit):
""" Constructs dict with URL params
:param tile_id: original tile identification string provided by ESA (e.g.
'S2A_OPER_MSI_L1C_TL_SGS__20160109T230542_A002870_T10UEV_N02.01')
:type tile_id: str
:param bbo... |
def scales(key=None, scales={}):
"""Creates and switches between context scales.
If no key is provided, a new blank context is created.
If a key is provided for which a context already exists, the existing
context is set as the current context.
If a key is provided and no corresponding context ex... | def function[scales, parameter[key, scales]]:
constant[Creates and switches between context scales.
If no key is provided, a new blank context is created.
If a key is provided for which a context already exists, the existing
context is set as the current context.
If a key is provided and no c... | keyword[def] identifier[scales] ( identifier[key] = keyword[None] , identifier[scales] ={}):
literal[string]
identifier[old_ctxt] = identifier[_context] [ literal[string] ]
keyword[if] identifier[key] keyword[is] keyword[None] :
identifier[_context] [ literal[string] ]={ identifier[_get_at... | def scales(key=None, scales={}):
"""Creates and switches between context scales.
If no key is provided, a new blank context is created.
If a key is provided for which a context already exists, the existing
context is set as the current context.
If a key is provided and no corresponding context ex... |
def generate_data(nitem, nfeat=2, dim=10, labeldim=1, base='item'):
"""Returns a randomly generated h5f.Data instance.
- nitem is the number of items to generate.
- nfeat is the number of features to generate for each item.
- dim is the dimension of the features vectors.
- base is the items basenam... | def function[generate_data, parameter[nitem, nfeat, dim, labeldim, base]]:
constant[Returns a randomly generated h5f.Data instance.
- nitem is the number of items to generate.
- nfeat is the number of features to generate for each item.
- dim is the dimension of the features vectors.
- base is ... | keyword[def] identifier[generate_data] ( identifier[nitem] , identifier[nfeat] = literal[int] , identifier[dim] = literal[int] , identifier[labeldim] = literal[int] , identifier[base] = literal[string] ):
literal[string]
keyword[import] identifier[numpy] keyword[as] identifier[np]
identifier... | def generate_data(nitem, nfeat=2, dim=10, labeldim=1, base='item'):
"""Returns a randomly generated h5f.Data instance.
- nitem is the number of items to generate.
- nfeat is the number of features to generate for each item.
- dim is the dimension of the features vectors.
- base is the items basenam... |
def register(self, user_dict):
"""Send an user_dict to NApps server using POST request.
Args:
user_dict(dict): Dictionary with user attributes.
Returns:
result(string): Return the response of Napps server.
"""
endpoint = os.path.join(self._config.get('n... | def function[register, parameter[self, user_dict]]:
constant[Send an user_dict to NApps server using POST request.
Args:
user_dict(dict): Dictionary with user attributes.
Returns:
result(string): Return the response of Napps server.
]
variable[endpoint]... | keyword[def] identifier[register] ( identifier[self] , identifier[user_dict] ):
literal[string]
identifier[endpoint] = identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[_config] . identifier[get] ( literal[string] , literal[string] ), literal[string] , literal[str... | def register(self, user_dict):
"""Send an user_dict to NApps server using POST request.
Args:
user_dict(dict): Dictionary with user attributes.
Returns:
result(string): Return the response of Napps server.
"""
endpoint = os.path.join(self._config.get('napps', '... |
def _preoptimize_model(self, initials, method):
""" Preoptimizes the model by estimating a static model, then a quick search of good AR/SC parameters
Parameters
----------
initials : np.array
A vector of inital values
method : str
One of 'MLE' or 'PML' (... | def function[_preoptimize_model, parameter[self, initials, method]]:
constant[ Preoptimizes the model by estimating a static model, then a quick search of good AR/SC parameters
Parameters
----------
initials : np.array
A vector of inital values
method : str
... | keyword[def] identifier[_preoptimize_model] ( identifier[self] , identifier[initials] , identifier[method] ):
literal[string]
identifier[random_starts] = identifier[np] . identifier[random] . identifier[normal] ( literal[int] , literal[int] ,[ literal[int] , literal[int] ])
identifier[be... | def _preoptimize_model(self, initials, method):
""" Preoptimizes the model by estimating a static model, then a quick search of good AR/SC parameters
Parameters
----------
initials : np.array
A vector of inital values
method : str
One of 'MLE' or 'PML' (the ... |
def delete(gandi, background, force, resource):
"""Delete a virtual machine.
Resource can be a Hostname or an ID
"""
output_keys = ['id', 'type', 'step']
resource = sorted(tuple(set(resource)))
possible_resources = gandi.iaas.resource_list()
for item in resource:
if item not in pos... | def function[delete, parameter[gandi, background, force, resource]]:
constant[Delete a virtual machine.
Resource can be a Hostname or an ID
]
variable[output_keys] assign[=] list[[<ast.Constant object at 0x7da18ede5120>, <ast.Constant object at 0x7da18ede4a60>, <ast.Constant object at 0x7da18ed... | keyword[def] identifier[delete] ( identifier[gandi] , identifier[background] , identifier[force] , identifier[resource] ):
literal[string]
identifier[output_keys] =[ literal[string] , literal[string] , literal[string] ]
identifier[resource] = identifier[sorted] ( identifier[tuple] ( identifier[set] (... | def delete(gandi, background, force, resource):
"""Delete a virtual machine.
Resource can be a Hostname or an ID
"""
output_keys = ['id', 'type', 'step']
resource = sorted(tuple(set(resource)))
possible_resources = gandi.iaas.resource_list()
for item in resource:
if item not in poss... |
def is_binary(self):
"""Return true if this is a binary file."""
with open(self.path, 'rb') as fin:
CHUNKSIZE = 1024
while 1:
chunk = fin.read(CHUNKSIZE)
if b'\0' in chunk:
return True
if len(chunk) < CHUNKSIZE:
... | def function[is_binary, parameter[self]]:
constant[Return true if this is a binary file.]
with call[name[open], parameter[name[self].path, constant[rb]]] begin[:]
variable[CHUNKSIZE] assign[=] constant[1024]
while constant[1] begin[:]
variable[chun... | keyword[def] identifier[is_binary] ( identifier[self] ):
literal[string]
keyword[with] identifier[open] ( identifier[self] . identifier[path] , literal[string] ) keyword[as] identifier[fin] :
identifier[CHUNKSIZE] = literal[int]
keyword[while] literal[int] :
... | def is_binary(self):
"""Return true if this is a binary file."""
with open(self.path, 'rb') as fin:
CHUNKSIZE = 1024
while 1:
chunk = fin.read(CHUNKSIZE)
if b'\x00' in chunk:
return True # depends on [control=['if'], data=[]]
if len(chunk) < C... |
def alternative_filename(filename, attempt=None):
'''
Generates an alternative version of given filename.
If an number attempt parameter is given, will be used on the alternative
name, a random value will be used otherwise.
:param filename: original filename
:param attempt: optional attempt nu... | def function[alternative_filename, parameter[filename, attempt]]:
constant[
Generates an alternative version of given filename.
If an number attempt parameter is given, will be used on the alternative
name, a random value will be used otherwise.
:param filename: original filename
:param at... | keyword[def] identifier[alternative_filename] ( identifier[filename] , identifier[attempt] = keyword[None] ):
literal[string]
identifier[filename_parts] = identifier[filename] . identifier[rsplit] ( literal[string] , literal[int] )
identifier[name] = identifier[filename_parts] [ literal[int] ]
id... | def alternative_filename(filename, attempt=None):
"""
Generates an alternative version of given filename.
If an number attempt parameter is given, will be used on the alternative
name, a random value will be used otherwise.
:param filename: original filename
:param attempt: optional attempt nu... |
def from_csvf(cls, fpath: str, fieldnames: Optional[Sequence[str]]=None, encoding: str='utf8',
force_snake_case: bool=True, restrict: bool=True) -> TList[T]:
"""From csv file path to list of instance
:param fpath: Csv file path
:param fieldnames: Specify csv header names if no... | def function[from_csvf, parameter[cls, fpath, fieldnames, encoding, force_snake_case, restrict]]:
constant[From csv file path to list of instance
:param fpath: Csv file path
:param fieldnames: Specify csv header names if not included in the file
:param encoding: Csv file encoding
... | keyword[def] identifier[from_csvf] ( identifier[cls] , identifier[fpath] : identifier[str] , identifier[fieldnames] : identifier[Optional] [ identifier[Sequence] [ identifier[str] ]]= keyword[None] , identifier[encoding] : identifier[str] = literal[string] ,
identifier[force_snake_case] : identifier[bool] = keyword[... | def from_csvf(cls, fpath: str, fieldnames: Optional[Sequence[str]]=None, encoding: str='utf8', force_snake_case: bool=True, restrict: bool=True) -> TList[T]:
"""From csv file path to list of instance
:param fpath: Csv file path
:param fieldnames: Specify csv header names if not included in the file... |
def list(self, name=None, all=False, filters=None):
"""
List images on the server.
Args:
name (str): Only show images belonging to the repository ``name``
all (bool): Show intermediate image layers. By default, these are
filtered out.
filters ... | def function[list, parameter[self, name, all, filters]]:
constant[
List images on the server.
Args:
name (str): Only show images belonging to the repository ``name``
all (bool): Show intermediate image layers. By default, these are
filtered out.
... | keyword[def] identifier[list] ( identifier[self] , identifier[name] = keyword[None] , identifier[all] = keyword[False] , identifier[filters] = keyword[None] ):
literal[string]
identifier[resp] = identifier[self] . identifier[client] . identifier[api] . identifier[images] ( identifier[name] = identi... | def list(self, name=None, all=False, filters=None):
"""
List images on the server.
Args:
name (str): Only show images belonging to the repository ``name``
all (bool): Show intermediate image layers. By default, these are
filtered out.
filters (dic... |
def solve(self):
""" Solves a DC power flow.
"""
case = self.case
logger.info("Starting DC power flow [%s]." % case.name)
t0 = time.time()
# Update bus indexes.
self.case.index_buses()
# Find the index of the refence bus.
ref_idx = self._get_refer... | def function[solve, parameter[self]]:
constant[ Solves a DC power flow.
]
variable[case] assign[=] name[self].case
call[name[logger].info, parameter[binary_operation[constant[Starting DC power flow [%s].] <ast.Mod object at 0x7da2590d6920> name[case].name]]]
variable[t0] assign[=... | keyword[def] identifier[solve] ( identifier[self] ):
literal[string]
identifier[case] = identifier[self] . identifier[case]
identifier[logger] . identifier[info] ( literal[string] % identifier[case] . identifier[name] )
identifier[t0] = identifier[time] . identifier[time] ()
... | def solve(self):
""" Solves a DC power flow.
"""
case = self.case
logger.info('Starting DC power flow [%s].' % case.name)
t0 = time.time()
# Update bus indexes.
self.case.index_buses()
# Find the index of the refence bus.
ref_idx = self._get_reference_index(case)
if ref_idx <... |
def import_shape_di(participants_dict, diagram_graph, shape_element):
"""
Adds Diagram Interchange information (information about rendering a diagram) to appropriate
BPMN diagram element in graph node.
We assume that those attributes are required for each BPMNShape:
- width - wi... | def function[import_shape_di, parameter[participants_dict, diagram_graph, shape_element]]:
constant[
Adds Diagram Interchange information (information about rendering a diagram) to appropriate
BPMN diagram element in graph node.
We assume that those attributes are required for each BPMNS... | keyword[def] identifier[import_shape_di] ( identifier[participants_dict] , identifier[diagram_graph] , identifier[shape_element] ):
literal[string]
identifier[element_id] = identifier[shape_element] . identifier[getAttribute] ( identifier[consts] . identifier[Consts] . identifier[bpmn_element] )
... | def import_shape_di(participants_dict, diagram_graph, shape_element):
"""
Adds Diagram Interchange information (information about rendering a diagram) to appropriate
BPMN diagram element in graph node.
We assume that those attributes are required for each BPMNShape:
- width - width ... |
def recover_public_key(digest, signature, i, message=None):
""" Recover the public key from the the signature
"""
# See http: //www.secg.org/download/aid-780/sec1-v2.pdf section 4.1.6 primarily
curve = ecdsa.SECP256k1.curve
G = ecdsa.SECP256k1.generator
order = ecdsa.SECP256k1.order
yp = i ... | def function[recover_public_key, parameter[digest, signature, i, message]]:
constant[ Recover the public key from the the signature
]
variable[curve] assign[=] name[ecdsa].SECP256k1.curve
variable[G] assign[=] name[ecdsa].SECP256k1.generator
variable[order] assign[=] name[ecdsa].SECP... | keyword[def] identifier[recover_public_key] ( identifier[digest] , identifier[signature] , identifier[i] , identifier[message] = keyword[None] ):
literal[string]
identifier[curve] = identifier[ecdsa] . identifier[SECP256k1] . identifier[curve]
identifier[G] = identifier[ecdsa] . identifier[SECP... | def recover_public_key(digest, signature, i, message=None):
""" Recover the public key from the the signature
"""
# See http: //www.secg.org/download/aid-780/sec1-v2.pdf section 4.1.6 primarily
curve = ecdsa.SECP256k1.curve
G = ecdsa.SECP256k1.generator
order = ecdsa.SECP256k1.order
yp = i %... |
def update_ca_bundle(target=None, source=None, merge_files=None):
'''
Update the local CA bundle file from a URL
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' http.update_ca_bundle
salt '*' http.update_ca_bundle target=/path/to/cacerts.pem
salt '*'... | def function[update_ca_bundle, parameter[target, source, merge_files]]:
constant[
Update the local CA bundle file from a URL
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' http.update_ca_bundle
salt '*' http.update_ca_bundle target=/path/to/cacerts.pem
... | keyword[def] identifier[update_ca_bundle] ( identifier[target] = keyword[None] , identifier[source] = keyword[None] , identifier[merge_files] = keyword[None] ):
literal[string]
keyword[if] identifier[target] keyword[is] keyword[None] :
identifier[target] = identifier[__salt__] [ literal[string]... | def update_ca_bundle(target=None, source=None, merge_files=None):
"""
Update the local CA bundle file from a URL
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' http.update_ca_bundle
salt '*' http.update_ca_bundle target=/path/to/cacerts.pem
salt '*'... |
def build_board_2048():
""" builds a 2048 starting board
Printing Grid
0 0 0 2
0 0 4 0
0 0 0 0
0 0 0 0
"""
grd = Grid(4,4, [2,4])
grd.new_tile()
grd.new_tile()
print(grd)
return grd | def function[build_board_2048, parameter[]]:
constant[ builds a 2048 starting board
Printing Grid
0 0 0 2
0 0 4 0
0 0 0 0
0 0 0 0
]
variable[grd] assign[=] call[name[Grid], parameter[constant[4], constant[4], list[[<ast.Consta... | keyword[def] identifier[build_board_2048] ():
literal[string]
identifier[grd] = identifier[Grid] ( literal[int] , literal[int] ,[ literal[int] , literal[int] ])
identifier[grd] . identifier[new_tile] ()
identifier[grd] . identifier[new_tile] ()
identifier[print] ( identifier[grd] )
keyw... | def build_board_2048():
""" builds a 2048 starting board
Printing Grid
0 0 0 2
0 0 4 0
0 0 0 0
0 0 0 0
"""
grd = Grid(4, 4, [2, 4])
grd.new_tile()
grd.new_tile()
print(grd)
return grd |
def all(self):
"""Get all ACLs for this instance."""
return self._instance._client.acls.all(self._instance.name) | def function[all, parameter[self]]:
constant[Get all ACLs for this instance.]
return[call[name[self]._instance._client.acls.all, parameter[name[self]._instance.name]]] | keyword[def] identifier[all] ( identifier[self] ):
literal[string]
keyword[return] identifier[self] . identifier[_instance] . identifier[_client] . identifier[acls] . identifier[all] ( identifier[self] . identifier[_instance] . identifier[name] ) | def all(self):
"""Get all ACLs for this instance."""
return self._instance._client.acls.all(self._instance.name) |
def asString(self, strict=False):
"""
Return the location as a string.
::
>>> l = Location(pop=1, snap=(-100.0, -200))
>>> l.asString()
'pop:1, snap:(-100.000,-200.000)'
"""
if len(self.keys())==0:
return "origin"
v... | def function[asString, parameter[self, strict]]:
constant[
Return the location as a string.
::
>>> l = Location(pop=1, snap=(-100.0, -200))
>>> l.asString()
'pop:1, snap:(-100.000,-200.000)'
]
if compare[call[name[len], parameter[call[... | keyword[def] identifier[asString] ( identifier[self] , identifier[strict] = keyword[False] ):
literal[string]
keyword[if] identifier[len] ( identifier[self] . identifier[keys] ())== literal[int] :
keyword[return] literal[string]
identifier[v] =[]
identifier[n] =[]
... | def asString(self, strict=False):
"""
Return the location as a string.
::
>>> l = Location(pop=1, snap=(-100.0, -200))
>>> l.asString()
'pop:1, snap:(-100.000,-200.000)'
"""
if len(self.keys()) == 0:
return 'origin' # depends on [cont... |
def pct_change(self, periods=1, fill_method='pad', limit=None, freq=None):
"""Calcuate pct_change of each value to previous entry in group"""
# TODO: Remove this conditional when #23918 is fixed
if freq:
return self.apply(lambda x: x.pct_change(periods=periods,
... | def function[pct_change, parameter[self, periods, fill_method, limit, freq]]:
constant[Calcuate pct_change of each value to previous entry in group]
if name[freq] begin[:]
return[call[name[self].apply, parameter[<ast.Lambda object at 0x7da18fe93c70>]]]
variable[filled] assign[=] call[cal... | keyword[def] identifier[pct_change] ( identifier[self] , identifier[periods] = literal[int] , identifier[fill_method] = literal[string] , identifier[limit] = keyword[None] , identifier[freq] = keyword[None] ):
literal[string]
keyword[if] identifier[freq] :
keyword[return] id... | def pct_change(self, periods=1, fill_method='pad', limit=None, freq=None):
"""Calcuate pct_change of each value to previous entry in group"""
# TODO: Remove this conditional when #23918 is fixed
if freq:
return self.apply(lambda x: x.pct_change(periods=periods, fill_method=fill_method, limit=limit, ... |
def list_datastores_full(service_instance):
'''
Returns a list of datastores associated with a given service instance.
The list contains basic information about the datastore:
name, type, url, capacity, free, used, usage, hosts
service_instance
The Service Instance Object from which to ... | def function[list_datastores_full, parameter[service_instance]]:
constant[
Returns a list of datastores associated with a given service instance.
The list contains basic information about the datastore:
name, type, url, capacity, free, used, usage, hosts
service_instance
The Service... | keyword[def] identifier[list_datastores_full] ( identifier[service_instance] ):
literal[string]
identifier[datastores_list] = identifier[list_objects] ( identifier[service_instance] , identifier[vim] . identifier[Datastore] )
identifier[datastores] ={}
keyword[for] identifier[datastore] keywor... | def list_datastores_full(service_instance):
"""
Returns a list of datastores associated with a given service instance.
The list contains basic information about the datastore:
name, type, url, capacity, free, used, usage, hosts
service_instance
The Service Instance Object from which to ... |
def set_mac_address(self, mac_address=None, default=False, disable=False):
""" Sets the virtual-router mac address
This method will set the switch virtual-router mac address. If a
virtual-router mac address already exists it will be overwritten.
Args:
mac_address (string): ... | def function[set_mac_address, parameter[self, mac_address, default, disable]]:
constant[ Sets the virtual-router mac address
This method will set the switch virtual-router mac address. If a
virtual-router mac address already exists it will be overwritten.
Args:
mac_address ... | keyword[def] identifier[set_mac_address] ( identifier[self] , identifier[mac_address] = keyword[None] , identifier[default] = keyword[False] , identifier[disable] = keyword[False] ):
literal[string]
identifier[base_command] = literal[string]
keyword[if] keyword[not] identifier[default] ... | def set_mac_address(self, mac_address=None, default=False, disable=False):
""" Sets the virtual-router mac address
This method will set the switch virtual-router mac address. If a
virtual-router mac address already exists it will be overwritten.
Args:
mac_address (string): The ... |
def unregister(self, observers):
u"""
Concrete method of Subject.unregister().
Unregister observers as an argument to self.observers.
"""
if isinstance(observers, list) or isinstance(observers, tuple):
for observer in observers:
try:
... | def function[unregister, parameter[self, observers]]:
constant[
Concrete method of Subject.unregister().
Unregister observers as an argument to self.observers.
]
if <ast.BoolOp object at 0x7da1b0a65de0> begin[:]
for taget[name[observer]] in starred[name[observers]... | keyword[def] identifier[unregister] ( identifier[self] , identifier[observers] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[observers] , identifier[list] ) keyword[or] identifier[isinstance] ( identifier[observers] , identifier[tuple] ):
keyword[for] identifie... | def unregister(self, observers):
u"""
Concrete method of Subject.unregister().
Unregister observers as an argument to self.observers.
"""
if isinstance(observers, list) or isinstance(observers, tuple):
for observer in observers:
try:
index = self._obse... |
def download(outformat, path, identifier, namespace='cid', domain='compound', operation=None, searchtype=None,
overwrite=False, **kwargs):
"""Format can be XML, ASNT/B, JSON, SDF, CSV, PNG, TXT."""
response = get(identifier, namespace, domain, operation, outformat, searchtype, **kwargs)
if not... | def function[download, parameter[outformat, path, identifier, namespace, domain, operation, searchtype, overwrite]]:
constant[Format can be XML, ASNT/B, JSON, SDF, CSV, PNG, TXT.]
variable[response] assign[=] call[name[get], parameter[name[identifier], name[namespace], name[domain], name[operation], na... | keyword[def] identifier[download] ( identifier[outformat] , identifier[path] , identifier[identifier] , identifier[namespace] = literal[string] , identifier[domain] = literal[string] , identifier[operation] = keyword[None] , identifier[searchtype] = keyword[None] ,
identifier[overwrite] = keyword[False] ,** identifi... | def download(outformat, path, identifier, namespace='cid', domain='compound', operation=None, searchtype=None, overwrite=False, **kwargs):
"""Format can be XML, ASNT/B, JSON, SDF, CSV, PNG, TXT."""
response = get(identifier, namespace, domain, operation, outformat, searchtype, **kwargs)
if not overwrite an... |
def load_token(self, token, force=False):
"""Load data in a token.
:param token: Token to load.
:param force: Load token data even if signature expired.
Default: False.
"""
try:
data = self.loads(token)
except SignatureExpired as e:
... | def function[load_token, parameter[self, token, force]]:
constant[Load data in a token.
:param token: Token to load.
:param force: Load token data even if signature expired.
Default: False.
]
<ast.Try object at 0x7da18ede4e20>
<ast.Delete object at 0x7da18e... | keyword[def] identifier[load_token] ( identifier[self] , identifier[token] , identifier[force] = keyword[False] ):
literal[string]
keyword[try] :
identifier[data] = identifier[self] . identifier[loads] ( identifier[token] )
keyword[except] identifier[SignatureExpired] keywor... | def load_token(self, token, force=False):
"""Load data in a token.
:param token: Token to load.
:param force: Load token data even if signature expired.
Default: False.
"""
try:
data = self.loads(token) # depends on [control=['try'], data=[]]
except Si... |
def draw_on_image(self, image, color=(0, 255, 0), alpha=1.0, size=3,
copy=True, raise_if_out_of_image=False):
"""
Draw the keypoint onto a given image.
The keypoint is drawn as a square.
Parameters
----------
image : (H,W,3) ndarray
The... | def function[draw_on_image, parameter[self, image, color, alpha, size, copy, raise_if_out_of_image]]:
constant[
Draw the keypoint onto a given image.
The keypoint is drawn as a square.
Parameters
----------
image : (H,W,3) ndarray
The image onto which to dra... | keyword[def] identifier[draw_on_image] ( identifier[self] , identifier[image] , identifier[color] =( literal[int] , literal[int] , literal[int] ), identifier[alpha] = literal[int] , identifier[size] = literal[int] ,
identifier[copy] = keyword[True] , identifier[raise_if_out_of_image] = keyword[False] ):
lit... | def draw_on_image(self, image, color=(0, 255, 0), alpha=1.0, size=3, copy=True, raise_if_out_of_image=False):
"""
Draw the keypoint onto a given image.
The keypoint is drawn as a square.
Parameters
----------
image : (H,W,3) ndarray
The image onto which to draw ... |
def dre_dsigmai(self, pars):
r"""
:math:Add formula
"""
self._set_parameters(pars)
terms = self.m * self.num / self.denom
specs = np.sum(terms, axis=1)
result = 1 - specs
return result | def function[dre_dsigmai, parameter[self, pars]]:
constant[
:math:Add formula
]
call[name[self]._set_parameters, parameter[name[pars]]]
variable[terms] assign[=] binary_operation[binary_operation[name[self].m * name[self].num] / name[self].denom]
variable[specs] assign[=]... | keyword[def] identifier[dre_dsigmai] ( identifier[self] , identifier[pars] ):
literal[string]
identifier[self] . identifier[_set_parameters] ( identifier[pars] )
identifier[terms] = identifier[self] . identifier[m] * identifier[self] . identifier[num] / identifier[self] . identifier[denom]... | def dre_dsigmai(self, pars):
"""
:math:Add formula
"""
self._set_parameters(pars)
terms = self.m * self.num / self.denom
specs = np.sum(terms, axis=1)
result = 1 - specs
return result |
def run_script(script_path, session, handle_command=None, handle_line=None):
""" Run a script file using a valid sqlalchemy session.
Based on https://bit.ly/2CToAhY.
See also sqlalchemy transaction control: https://bit.ly/2yKso0A
:param script_path: The path where the script is located
:param sess... | def function[run_script, parameter[script_path, session, handle_command, handle_line]]:
constant[ Run a script file using a valid sqlalchemy session.
Based on https://bit.ly/2CToAhY.
See also sqlalchemy transaction control: https://bit.ly/2yKso0A
:param script_path: The path where the script is lo... | keyword[def] identifier[run_script] ( identifier[script_path] , identifier[session] , identifier[handle_command] = keyword[None] , identifier[handle_line] = keyword[None] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] % identifier[script_path] )
keyword[with] identifier[o... | def run_script(script_path, session, handle_command=None, handle_line=None):
""" Run a script file using a valid sqlalchemy session.
Based on https://bit.ly/2CToAhY.
See also sqlalchemy transaction control: https://bit.ly/2yKso0A
:param script_path: The path where the script is located
:param sess... |
def currentScopes(self, *args, **kwargs):
"""
Get Current Scopes
Return the expanded scopes available in the request, taking into account all sources
of scopes and scope restrictions (temporary credentials, assumeScopes, client scopes,
and roles).
This method gives outp... | def function[currentScopes, parameter[self]]:
constant[
Get Current Scopes
Return the expanded scopes available in the request, taking into account all sources
of scopes and scope restrictions (temporary credentials, assumeScopes, client scopes,
and roles).
This method ... | keyword[def] identifier[currentScopes] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[_makeApiCall] ( identifier[self] . identifier[funcinfo] [ literal[string] ],* identifier[args] ,** identifier[kwargs] ) | def currentScopes(self, *args, **kwargs):
"""
Get Current Scopes
Return the expanded scopes available in the request, taking into account all sources
of scopes and scope restrictions (temporary credentials, assumeScopes, client scopes,
and roles).
This method gives output: ... |
def scan(self, folder, sub=None, next_=None):
""" Request immediate rescan of a folder, or a specific path within a
folder.
Args:
folder (str): Folder ID.
sub (str): Path relative to the folder root. If sub is omitted
the entire folder is ... | def function[scan, parameter[self, folder, sub, next_]]:
constant[ Request immediate rescan of a folder, or a specific path within a
folder.
Args:
folder (str): Folder ID.
sub (str): Path relative to the folder root. If sub is omitted
the ... | keyword[def] identifier[scan] ( identifier[self] , identifier[folder] , identifier[sub] = keyword[None] , identifier[next_] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[sub] :
identifier[sub] = literal[string]
keyword[assert] identifier[isinstance... | def scan(self, folder, sub=None, next_=None):
""" Request immediate rescan of a folder, or a specific path within a
folder.
Args:
folder (str): Folder ID.
sub (str): Path relative to the folder root. If sub is omitted
the entire folder is scan... |
def _pdf_at_peak(self):
"""Pdf evaluated at the peak."""
return (self.peak - self.low) / (self.high - self.low) | def function[_pdf_at_peak, parameter[self]]:
constant[Pdf evaluated at the peak.]
return[binary_operation[binary_operation[name[self].peak - name[self].low] / binary_operation[name[self].high - name[self].low]]] | keyword[def] identifier[_pdf_at_peak] ( identifier[self] ):
literal[string]
keyword[return] ( identifier[self] . identifier[peak] - identifier[self] . identifier[low] )/( identifier[self] . identifier[high] - identifier[self] . identifier[low] ) | def _pdf_at_peak(self):
"""Pdf evaluated at the peak."""
return (self.peak - self.low) / (self.high - self.low) |
def _get_login_manager(self,
app: FlaskUnchained,
anonymous_user: AnonymousUser,
) -> LoginManager:
"""
Get an initialized instance of Flask Login's
:class:`~flask_login.LoginManager`.
"""
login_mana... | def function[_get_login_manager, parameter[self, app, anonymous_user]]:
constant[
Get an initialized instance of Flask Login's
:class:`~flask_login.LoginManager`.
]
variable[login_manager] assign[=] call[name[LoginManager], parameter[]]
name[login_manager].anonymous_user ... | keyword[def] identifier[_get_login_manager] ( identifier[self] ,
identifier[app] : identifier[FlaskUnchained] ,
identifier[anonymous_user] : identifier[AnonymousUser] ,
)-> identifier[LoginManager] :
literal[string]
identifier[login_manager] = identifier[LoginManager] ()
identifier[login... | def _get_login_manager(self, app: FlaskUnchained, anonymous_user: AnonymousUser) -> LoginManager:
"""
Get an initialized instance of Flask Login's
:class:`~flask_login.LoginManager`.
"""
login_manager = LoginManager()
login_manager.anonymous_user = anonymous_user or AnonymousUser
... |
def get_all_responses(self, receive_timeout_in_seconds=None):
"""
Receive all available responses from the transport as a generator.
:param receive_timeout_in_seconds: How long to block without receiving a message before raising
`MessageReceiveTimeout`... | def function[get_all_responses, parameter[self, receive_timeout_in_seconds]]:
constant[
Receive all available responses from the transport as a generator.
:param receive_timeout_in_seconds: How long to block without receiving a message before raising
`... | keyword[def] identifier[get_all_responses] ( identifier[self] , identifier[receive_timeout_in_seconds] = keyword[None] ):
literal[string]
identifier[wrapper] = identifier[self] . identifier[_make_middleware_stack] (
[ identifier[m] . identifier[response] keyword[for] identifier[m] keywo... | def get_all_responses(self, receive_timeout_in_seconds=None):
"""
Receive all available responses from the transport as a generator.
:param receive_timeout_in_seconds: How long to block without receiving a message before raising
`MessageReceiveTimeout` (de... |
def _onSize(self, evt):
"""
Called when wxEventSize is generated.
In this application we attempt to resize to fit the window, so it
is better to take the performance hit and redraw the whole window.
"""
DEBUG_MSG("_onSize()", 2, self)
# Create a new, correctly s... | def function[_onSize, parameter[self, evt]]:
constant[
Called when wxEventSize is generated.
In this application we attempt to resize to fit the window, so it
is better to take the performance hit and redraw the whole window.
]
call[name[DEBUG_MSG], parameter[constant[_o... | keyword[def] identifier[_onSize] ( identifier[self] , identifier[evt] ):
literal[string]
identifier[DEBUG_MSG] ( literal[string] , literal[int] , identifier[self] )
identifier[self] . identifier[_width] , identifier[self] . identifier[_height] = identifier[self] . identifier[GetC... | def _onSize(self, evt):
"""
Called when wxEventSize is generated.
In this application we attempt to resize to fit the window, so it
is better to take the performance hit and redraw the whole window.
"""
DEBUG_MSG('_onSize()', 2, self)
# Create a new, correctly sized bitmap
... |
def AddPassword(self, fileset):
"""Add the passwd entries to the shadow store."""
passwd = fileset.get("/etc/passwd")
if passwd:
self._ParseFile(passwd, self.ParsePasswdEntry)
else:
logging.debug("No /etc/passwd file.") | def function[AddPassword, parameter[self, fileset]]:
constant[Add the passwd entries to the shadow store.]
variable[passwd] assign[=] call[name[fileset].get, parameter[constant[/etc/passwd]]]
if name[passwd] begin[:]
call[name[self]._ParseFile, parameter[name[passwd], name[self].... | keyword[def] identifier[AddPassword] ( identifier[self] , identifier[fileset] ):
literal[string]
identifier[passwd] = identifier[fileset] . identifier[get] ( literal[string] )
keyword[if] identifier[passwd] :
identifier[self] . identifier[_ParseFile] ( identifier[passwd] , identifier[self] . i... | def AddPassword(self, fileset):
"""Add the passwd entries to the shadow store."""
passwd = fileset.get('/etc/passwd')
if passwd:
self._ParseFile(passwd, self.ParsePasswdEntry) # depends on [control=['if'], data=[]]
else:
logging.debug('No /etc/passwd file.') |
def get_ticket(self, ticket_id):
"""Fetches the ticket for the given ticket ID"""
url = 'tickets/%d' % ticket_id
ticket = self._api._get(url)
return Ticket(**ticket) | def function[get_ticket, parameter[self, ticket_id]]:
constant[Fetches the ticket for the given ticket ID]
variable[url] assign[=] binary_operation[constant[tickets/%d] <ast.Mod object at 0x7da2590d6920> name[ticket_id]]
variable[ticket] assign[=] call[name[self]._api._get, parameter[name[url]]]... | keyword[def] identifier[get_ticket] ( identifier[self] , identifier[ticket_id] ):
literal[string]
identifier[url] = literal[string] % identifier[ticket_id]
identifier[ticket] = identifier[self] . identifier[_api] . identifier[_get] ( identifier[url] )
keyword[return] identifier[... | def get_ticket(self, ticket_id):
"""Fetches the ticket for the given ticket ID"""
url = 'tickets/%d' % ticket_id
ticket = self._api._get(url)
return Ticket(**ticket) |
def parse_cigar(cigar):
"""
parse cigar string into list of operations
e.g.: 28M1I29M2I6M1I46M ->
[['28', 'M'], ['1', 'I'], ['29', 'M'], ['2', 'I'], ['6', 'M'], ['1', 'I'], ['46', 'M']]
"""
cigar = cigar.replace('M', 'M ').replace('I', 'I ').replace('D', 'D ').split()
cigar = [c.replac... | def function[parse_cigar, parameter[cigar]]:
constant[
parse cigar string into list of operations
e.g.: 28M1I29M2I6M1I46M ->
[['28', 'M'], ['1', 'I'], ['29', 'M'], ['2', 'I'], ['6', 'M'], ['1', 'I'], ['46', 'M']]
]
variable[cigar] assign[=] call[call[call[call[name[cigar].replace, ... | keyword[def] identifier[parse_cigar] ( identifier[cigar] ):
literal[string]
identifier[cigar] = identifier[cigar] . identifier[replace] ( literal[string] , literal[string] ). identifier[replace] ( literal[string] , literal[string] ). identifier[replace] ( literal[string] , literal[string] ). identifier[spl... | def parse_cigar(cigar):
"""
parse cigar string into list of operations
e.g.: 28M1I29M2I6M1I46M ->
[['28', 'M'], ['1', 'I'], ['29', 'M'], ['2', 'I'], ['6', 'M'], ['1', 'I'], ['46', 'M']]
"""
cigar = cigar.replace('M', 'M ').replace('I', 'I ').replace('D', 'D ').split()
cigar = [c.replac... |
def setDataset(self, dataset):
"""
Sets the dataset instance associated with this item.
:param dataset | <XChartDataset>
"""
self._dataset = dataset
# setup the tooltip
tip = []
tip.append('<b>%s</b>' % dataset.name())
... | def function[setDataset, parameter[self, dataset]]:
constant[
Sets the dataset instance associated with this item.
:param dataset | <XChartDataset>
]
name[self]._dataset assign[=] name[dataset]
variable[tip] assign[=] list[[]]
call[name[tip].append, ... | keyword[def] identifier[setDataset] ( identifier[self] , identifier[dataset] ):
literal[string]
identifier[self] . identifier[_dataset] = identifier[dataset]
identifier[tip] =[]
identifier[tip] . identifier[append] ( literal[string] % identifier[dataset] . identif... | def setDataset(self, dataset):
"""
Sets the dataset instance associated with this item.
:param dataset | <XChartDataset>
"""
self._dataset = dataset # setup the tooltip
tip = []
tip.append('<b>%s</b>' % dataset.name())
for value in dataset.values():
val... |
def msg_curse(self, args=None, max_width=None):
"""Return the dict to display in the curse interface."""
# Init the return message
ret = []
# Only process if stats exist and display plugin enable...
if not self.stats or self.is_disable():
return ret
# Max si... | def function[msg_curse, parameter[self, args, max_width]]:
constant[Return the dict to display in the curse interface.]
variable[ret] assign[=] list[[]]
if <ast.BoolOp object at 0x7da18eb55cc0> begin[:]
return[name[ret]]
variable[name_max_width] assign[=] binary_operation[name[ma... | keyword[def] identifier[msg_curse] ( identifier[self] , identifier[args] = keyword[None] , identifier[max_width] = keyword[None] ):
literal[string]
identifier[ret] =[]
keyword[if] keyword[not] identifier[self] . identifier[stats] keyword[or] identifier[self] . identi... | def msg_curse(self, args=None, max_width=None):
"""Return the dict to display in the curse interface."""
# Init the return message
ret = []
# Only process if stats exist and display plugin enable...
if not self.stats or self.is_disable():
return ret # depends on [control=['if'], data=[]]
... |
def preprocess_user_variables(userinput):
"""
<Purpose>
Command parser for user variables. Takes the raw userinput and replaces
each user variable with its set value.
<Arguments>
userinput: A raw user string
<Side Effects>
Each user variable will be replaced by the value that it was previously
... | def function[preprocess_user_variables, parameter[userinput]]:
constant[
<Purpose>
Command parser for user variables. Takes the raw userinput and replaces
each user variable with its set value.
<Arguments>
userinput: A raw user string
<Side Effects>
Each user variable will be replaced by ... | keyword[def] identifier[preprocess_user_variables] ( identifier[userinput] ):
literal[string]
identifier[retstr] = literal[string]
keyword[while] literal[string] keyword[in] identifier[userinput] :
identifier[text_before_variable] , identifier[variable_delimiter] , identifier[userinput] = identifie... | def preprocess_user_variables(userinput):
"""
<Purpose>
Command parser for user variables. Takes the raw userinput and replaces
each user variable with its set value.
<Arguments>
userinput: A raw user string
<Side Effects>
Each user variable will be replaced by the value that it was previousl... |
def get_as_string(self, key):
"""
Converts map element into a string or returns "" if conversion is not possible.
:param key: an index of element to get.
:return: string value ot the element or "" if conversion is not supported.
"""
value = self.get(key)
return ... | def function[get_as_string, parameter[self, key]]:
constant[
Converts map element into a string or returns "" if conversion is not possible.
:param key: an index of element to get.
:return: string value ot the element or "" if conversion is not supported.
]
variable[val... | keyword[def] identifier[get_as_string] ( identifier[self] , identifier[key] ):
literal[string]
identifier[value] = identifier[self] . identifier[get] ( identifier[key] )
keyword[return] identifier[StringConverter] . identifier[to_string] ( identifier[value] ) | def get_as_string(self, key):
"""
Converts map element into a string or returns "" if conversion is not possible.
:param key: an index of element to get.
:return: string value ot the element or "" if conversion is not supported.
"""
value = self.get(key)
return StringConver... |
def add_property(self, c_property_tuple, sync=True):
"""
add property to this container. if this container has no id then it's like sync=False.
:param c_property_tuple: property tuple defined like this :
=> property name = c_property_tuple[0]
=> property value = c_p... | def function[add_property, parameter[self, c_property_tuple, sync]]:
constant[
add property to this container. if this container has no id then it's like sync=False.
:param c_property_tuple: property tuple defined like this :
=> property name = c_property_tuple[0]
=... | keyword[def] identifier[add_property] ( identifier[self] , identifier[c_property_tuple] , identifier[sync] = keyword[True] ):
literal[string]
identifier[LOGGER] . identifier[debug] ( literal[string] )
keyword[if] identifier[c_property_tuple] [ literal[int] ] keyword[is] keyword[None] :
... | def add_property(self, c_property_tuple, sync=True):
"""
add property to this container. if this container has no id then it's like sync=False.
:param c_property_tuple: property tuple defined like this :
=> property name = c_property_tuple[0]
=> property value = c_prope... |
def rfc2426(self):
"""RFC2426-encode the field content.
:return: the field in the RFC 2426 format.
:returntype: `str`"""
if self.uri:
return rfc2425encode(self.name,self.uri,{"value":"uri"})
elif self.image:
if self.type:
p={"type":self.ty... | def function[rfc2426, parameter[self]]:
constant[RFC2426-encode the field content.
:return: the field in the RFC 2426 format.
:returntype: `str`]
if name[self].uri begin[:]
return[call[name[rfc2425encode], parameter[name[self].name, name[self].uri, dictionary[[<ast.Constant obje... | keyword[def] identifier[rfc2426] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[uri] :
keyword[return] identifier[rfc2425encode] ( identifier[self] . identifier[name] , identifier[self] . identifier[uri] ,{ literal[string] : literal[string] })
... | def rfc2426(self):
"""RFC2426-encode the field content.
:return: the field in the RFC 2426 format.
:returntype: `str`"""
if self.uri:
return rfc2425encode(self.name, self.uri, {'value': 'uri'}) # depends on [control=['if'], data=[]]
elif self.image:
if self.type:
... |
def from_validated_yaml(cls, yaml_str, selectable, **kwargs):
"""Create a shelf using a yaml shelf definition.
:param yaml_str: A string containing yaml ingredient definitions.
:param selectable: A SQLAlchemy Table, a Recipe, or a SQLAlchemy
join to select from.
:return: A shelf... | def function[from_validated_yaml, parameter[cls, yaml_str, selectable]]:
constant[Create a shelf using a yaml shelf definition.
:param yaml_str: A string containing yaml ingredient definitions.
:param selectable: A SQLAlchemy Table, a Recipe, or a SQLAlchemy
join to select from.
... | keyword[def] identifier[from_validated_yaml] ( identifier[cls] , identifier[yaml_str] , identifier[selectable] ,** identifier[kwargs] ):
literal[string]
identifier[obj] = identifier[safe_load] ( identifier[yaml_str] )
keyword[return] identifier[cls] . identifier[from_config] ( identifier[... | def from_validated_yaml(cls, yaml_str, selectable, **kwargs):
"""Create a shelf using a yaml shelf definition.
:param yaml_str: A string containing yaml ingredient definitions.
:param selectable: A SQLAlchemy Table, a Recipe, or a SQLAlchemy
join to select from.
:return: A shelf tha... |
def get_yeast_sequence(chromosome, start, end, reverse_complement=False):
'''Acquire a sequence from SGD http://www.yeastgenome.org
:param chromosome: Yeast chromosome.
:type chromosome: int
:param start: A biostart.
:type start: int
:param end: A bioend.
:type end: int
:param reverse_co... | def function[get_yeast_sequence, parameter[chromosome, start, end, reverse_complement]]:
constant[Acquire a sequence from SGD http://www.yeastgenome.org
:param chromosome: Yeast chromosome.
:type chromosome: int
:param start: A biostart.
:type start: int
:param end: A bioend.
:type end: ... | keyword[def] identifier[get_yeast_sequence] ( identifier[chromosome] , identifier[start] , identifier[end] , identifier[reverse_complement] = keyword[False] ):
literal[string]
keyword[import] identifier[requests]
keyword[if] identifier[start] != identifier[end] :
keyword[if] identifier[r... | def get_yeast_sequence(chromosome, start, end, reverse_complement=False):
"""Acquire a sequence from SGD http://www.yeastgenome.org
:param chromosome: Yeast chromosome.
:type chromosome: int
:param start: A biostart.
:type start: int
:param end: A bioend.
:type end: int
:param reverse_co... |
def create(cls, name, members=None, comment=None):
"""
Create the TCP Service group
:param str name: name of tcp service group
:param list element: tcp services by element or href
:type element: list(str,Element)
:raises CreateElementFailed: element creation failed with ... | def function[create, parameter[cls, name, members, comment]]:
constant[
Create the TCP Service group
:param str name: name of tcp service group
:param list element: tcp services by element or href
:type element: list(str,Element)
:raises CreateElementFailed: element crea... | keyword[def] identifier[create] ( identifier[cls] , identifier[name] , identifier[members] = keyword[None] , identifier[comment] = keyword[None] ):
literal[string]
identifier[element] =[] keyword[if] identifier[members] keyword[is] keyword[None] keyword[else] identifier[element_resolver] ( ide... | def create(cls, name, members=None, comment=None):
"""
Create the TCP Service group
:param str name: name of tcp service group
:param list element: tcp services by element or href
:type element: list(str,Element)
:raises CreateElementFailed: element creation failed with reas... |
def input_digit(self, next_char, remember_position=False):
"""Formats a phone number on-the-fly as each digit is entered.
If remember_position is set, remembers the position where next_char is
inserted, so that it can be retrieved later by using
get_remembered_position. The remembered p... | def function[input_digit, parameter[self, next_char, remember_position]]:
constant[Formats a phone number on-the-fly as each digit is entered.
If remember_position is set, remembers the position where next_char is
inserted, so that it can be retrieved later by using
get_remembered_posit... | keyword[def] identifier[input_digit] ( identifier[self] , identifier[next_char] , identifier[remember_position] = keyword[False] ):
literal[string]
identifier[self] . identifier[_accrued_input] += identifier[next_char]
keyword[if] identifier[remember_position] :
identifier[s... | def input_digit(self, next_char, remember_position=False):
"""Formats a phone number on-the-fly as each digit is entered.
If remember_position is set, remembers the position where next_char is
inserted, so that it can be retrieved later by using
get_remembered_position. The remembered posit... |
def _ScanVolumeSystemRoot(self, scan_context, scan_node, base_path_specs):
"""Scans a volume system root scan node for volume and file systems.
Args:
scan_context (SourceScannerContext): source scanner context.
scan_node (SourceScanNode): volume system root scan node.
base_path_specs (list[Pa... | def function[_ScanVolumeSystemRoot, parameter[self, scan_context, scan_node, base_path_specs]]:
constant[Scans a volume system root scan node for volume and file systems.
Args:
scan_context (SourceScannerContext): source scanner context.
scan_node (SourceScanNode): volume system root scan node.... | keyword[def] identifier[_ScanVolumeSystemRoot] ( identifier[self] , identifier[scan_context] , identifier[scan_node] , identifier[base_path_specs] ):
literal[string]
keyword[if] keyword[not] identifier[scan_node] keyword[or] keyword[not] identifier[scan_node] . identifier[path_spec] :
keyword[r... | def _ScanVolumeSystemRoot(self, scan_context, scan_node, base_path_specs):
"""Scans a volume system root scan node for volume and file systems.
Args:
scan_context (SourceScannerContext): source scanner context.
scan_node (SourceScanNode): volume system root scan node.
base_path_specs (list[Pa... |
def selection_redo(self, name="default", executor=None):
"""Redo selection, for the name."""
logger.debug("redo")
executor = executor or self.executor
assert self.selection_can_redo(name=name)
selection_history = self.selection_histories[name]
index = self.selection_histo... | def function[selection_redo, parameter[self, name, executor]]:
constant[Redo selection, for the name.]
call[name[logger].debug, parameter[constant[redo]]]
variable[executor] assign[=] <ast.BoolOp object at 0x7da20c795c60>
assert[call[name[self].selection_can_redo, parameter[]]]
varia... | keyword[def] identifier[selection_redo] ( identifier[self] , identifier[name] = literal[string] , identifier[executor] = keyword[None] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] )
identifier[executor] = identifier[executor] keyword[or] identifier[self] . ... | def selection_redo(self, name='default', executor=None):
"""Redo selection, for the name."""
logger.debug('redo')
executor = executor or self.executor
assert self.selection_can_redo(name=name)
selection_history = self.selection_histories[name]
index = self.selection_history_indices[name]
nex... |
def login(self, email, password):
"""
login using email and password
:param email: email address
:param password: password
"""
rsp = self._request()
self.default_headers['Authorization'] = rsp.data['token']
return rsp | def function[login, parameter[self, email, password]]:
constant[
login using email and password
:param email: email address
:param password: password
]
variable[rsp] assign[=] call[name[self]._request, parameter[]]
call[name[self].default_headers][constant[Authori... | keyword[def] identifier[login] ( identifier[self] , identifier[email] , identifier[password] ):
literal[string]
identifier[rsp] = identifier[self] . identifier[_request] ()
identifier[self] . identifier[default_headers] [ literal[string] ]= identifier[rsp] . identifier[data] [ literal[stri... | def login(self, email, password):
"""
login using email and password
:param email: email address
:param password: password
"""
rsp = self._request()
self.default_headers['Authorization'] = rsp.data['token']
return rsp |
def translate_book(translators=(HyperlinkStyleCorrector().translate, translate_line_footnotes),
book_dir=BOOK_PATH, dest=None, include_tags=None,
ext='.nlpiabak', skip_untitled=True):
""" Fix any style corrections listed in `translate` list of translation functions
>>> len... | def function[translate_book, parameter[translators, book_dir, dest, include_tags, ext, skip_untitled]]:
constant[ Fix any style corrections listed in `translate` list of translation functions
>>> len(translate_book(book_dir=BOOK_PATH, dest='cleaned_hyperlinks'))
3
>>> rm_rf(os.path.join(BOOK_PATH, ... | keyword[def] identifier[translate_book] ( identifier[translators] =( identifier[HyperlinkStyleCorrector] (). identifier[translate] , identifier[translate_line_footnotes] ),
identifier[book_dir] = identifier[BOOK_PATH] , identifier[dest] = keyword[None] , identifier[include_tags] = keyword[None] ,
identifier[ext] = ... | def translate_book(translators=(HyperlinkStyleCorrector().translate, translate_line_footnotes), book_dir=BOOK_PATH, dest=None, include_tags=None, ext='.nlpiabak', skip_untitled=True):
""" Fix any style corrections listed in `translate` list of translation functions
>>> len(translate_book(book_dir=BOOK_PATH, de... |
def init_widget(self):
""" Initialize the underlying widget.
"""
# Create and init the client
c = self.client = BridgedWebViewClient()
c.setWebView(self.widget, c.getId())
c.onLoadResource.connect(self.on_load_resource)
c.onPageFinished.connect(self.on_page_finis... | def function[init_widget, parameter[self]]:
constant[ Initialize the underlying widget.
]
variable[c] assign[=] call[name[BridgedWebViewClient], parameter[]]
call[name[c].setWebView, parameter[name[self].widget, call[name[c].getId, parameter[]]]]
call[name[c].onLoadResource.conn... | keyword[def] identifier[init_widget] ( identifier[self] ):
literal[string]
identifier[c] = identifier[self] . identifier[client] = identifier[BridgedWebViewClient] ()
identifier[c] . identifier[setWebView] ( identifier[self] . identifier[widget] , identifier[c] . identifier[getId]... | def init_widget(self):
""" Initialize the underlying widget.
"""
# Create and init the client
c = self.client = BridgedWebViewClient()
c.setWebView(self.widget, c.getId())
c.onLoadResource.connect(self.on_load_resource)
c.onPageFinished.connect(self.on_page_finished)
c.onPageStarted... |
def update_template(self, template_id, template_dict):
"""
Updates a template
:param template_id: the template id
:param template_dict: dict
:return: dict
"""
return self._create_put_request(
resource=TEMPLATES,
billomat_id=template_id,
... | def function[update_template, parameter[self, template_id, template_dict]]:
constant[
Updates a template
:param template_id: the template id
:param template_dict: dict
:return: dict
]
return[call[name[self]._create_put_request, parameter[]]] | keyword[def] identifier[update_template] ( identifier[self] , identifier[template_id] , identifier[template_dict] ):
literal[string]
keyword[return] identifier[self] . identifier[_create_put_request] (
identifier[resource] = identifier[TEMPLATES] ,
identifier[billomat_id] = ident... | def update_template(self, template_id, template_dict):
"""
Updates a template
:param template_id: the template id
:param template_dict: dict
:return: dict
"""
return self._create_put_request(resource=TEMPLATES, billomat_id=template_id, send_data=template_dict) |
def sort(self, key, reverse=False, none_greater=False):
'''Sort the list in the order of the dictionary key.
Example of use:
>>> test = [
... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 },
... {"name": "Larry", "age": 18, "wigs": [3, 2,... | def function[sort, parameter[self, key, reverse, none_greater]]:
constant[Sort the list in the order of the dictionary key.
Example of use:
>>> test = [
... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 },
... {"name": "Larry", "age": 18, ... | keyword[def] identifier[sort] ( identifier[self] , identifier[key] , identifier[reverse] = keyword[False] , identifier[none_greater] = keyword[False] ):
literal[string]
keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] , identifier[len] ( identifier[self] . identifier[table... | def sort(self, key, reverse=False, none_greater=False):
"""Sort the list in the order of the dictionary key.
Example of use:
>>> test = [
... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 },
... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}... |
def _apply_dvportgroup_config(pg_name, pg_spec, pg_conf):
'''
Applies the values in conf to a distributed portgroup spec
pg_name
The name of the portgroup
pg_spec
The vim.DVPortgroupConfigSpec to apply the config to
pg_conf
The portgroup config
'''
log.trace('Build... | def function[_apply_dvportgroup_config, parameter[pg_name, pg_spec, pg_conf]]:
constant[
Applies the values in conf to a distributed portgroup spec
pg_name
The name of the portgroup
pg_spec
The vim.DVPortgroupConfigSpec to apply the config to
pg_conf
The portgroup conf... | keyword[def] identifier[_apply_dvportgroup_config] ( identifier[pg_name] , identifier[pg_spec] , identifier[pg_conf] ):
literal[string]
identifier[log] . identifier[trace] ( literal[string] , identifier[pg_name] )
keyword[if] literal[string] keyword[in] identifier[pg_conf] :
identifier[pg_... | def _apply_dvportgroup_config(pg_name, pg_spec, pg_conf):
"""
Applies the values in conf to a distributed portgroup spec
pg_name
The name of the portgroup
pg_spec
The vim.DVPortgroupConfigSpec to apply the config to
pg_conf
The portgroup config
"""
log.trace("Build... |
def select_form(self, selector="form", nr=0):
"""Select a form in the current page.
:param selector: CSS selector or a bs4.element.Tag object to identify
the form to select.
If not specified, ``selector`` defaults to "form", which is
useful if, e.g., there is only on... | def function[select_form, parameter[self, selector, nr]]:
constant[Select a form in the current page.
:param selector: CSS selector or a bs4.element.Tag object to identify
the form to select.
If not specified, ``selector`` defaults to "form", which is
useful if, e.g.... | keyword[def] identifier[select_form] ( identifier[self] , identifier[selector] = literal[string] , identifier[nr] = literal[int] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[selector] , identifier[bs4] . identifier[element] . identifier[Tag] ):
keyword[if] ident... | def select_form(self, selector='form', nr=0):
"""Select a form in the current page.
:param selector: CSS selector or a bs4.element.Tag object to identify
the form to select.
If not specified, ``selector`` defaults to "form", which is
useful if, e.g., there is only one fo... |
def parse_args(self, args=None):
"""
Parse the arguments from the command line (or directly) to the parser
of this organizer
Parameters
----------
args: list
A list of arguments to parse. If None, the :attr:`sys.argv`
argument is used
Ret... | def function[parse_args, parameter[self, args]]:
constant[
Parse the arguments from the command line (or directly) to the parser
of this organizer
Parameters
----------
args: list
A list of arguments to parse. If None, the :attr:`sys.argv`
argumen... | keyword[def] identifier[parse_args] ( identifier[self] , identifier[args] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[parser] keyword[is] keyword[None] :
identifier[self] . identifier[setup_parser] ()
keyword[if] keyword[not] identifier[se... | def parse_args(self, args=None):
"""
Parse the arguments from the command line (or directly) to the parser
of this organizer
Parameters
----------
args: list
A list of arguments to parse. If None, the :attr:`sys.argv`
argument is used
Returns... |
def _reset_kind_map(cls):
"""Clear the kind map. Useful for testing."""
# Preserve "system" kinds, like __namespace__
keep = {}
for name, value in cls._kind_map.iteritems():
if name.startswith('__') and name.endswith('__'):
keep[name] = value
cls._kind_map.clear()
cls._kind_map.up... | def function[_reset_kind_map, parameter[cls]]:
constant[Clear the kind map. Useful for testing.]
variable[keep] assign[=] dictionary[[], []]
for taget[tuple[[<ast.Name object at 0x7da1b0fdd6c0>, <ast.Name object at 0x7da1b0fdd510>]]] in starred[call[name[cls]._kind_map.iteritems, parameter[]]] ... | keyword[def] identifier[_reset_kind_map] ( identifier[cls] ):
literal[string]
identifier[keep] ={}
keyword[for] identifier[name] , identifier[value] keyword[in] identifier[cls] . identifier[_kind_map] . identifier[iteritems] ():
keyword[if] identifier[name] . identifier[startswith] ( l... | def _reset_kind_map(cls):
"""Clear the kind map. Useful for testing."""
# Preserve "system" kinds, like __namespace__
keep = {}
for (name, value) in cls._kind_map.iteritems():
if name.startswith('__') and name.endswith('__'):
keep[name] = value # depends on [control=['if'], data=[]... |
def _insert_travel_impedance_data_to_db(self, travel_impedance_measure_name, data):
"""
Parameters
----------
travel_impedance_measure_name: str
data: list[dict]
Each list element must contain keys:
"from_stop_I", "to_stop_I", "min", "max", "median" and "m... | def function[_insert_travel_impedance_data_to_db, parameter[self, travel_impedance_measure_name, data]]:
constant[
Parameters
----------
travel_impedance_measure_name: str
data: list[dict]
Each list element must contain keys:
"from_stop_I", "to_stop_I", "m... | keyword[def] identifier[_insert_travel_impedance_data_to_db] ( identifier[self] , identifier[travel_impedance_measure_name] , identifier[data] ):
literal[string]
identifier[f] = identifier[float]
identifier[data_tuple] =[( identifier[x] [ literal[string] ], identifier[x] [ literal[string]... | def _insert_travel_impedance_data_to_db(self, travel_impedance_measure_name, data):
"""
Parameters
----------
travel_impedance_measure_name: str
data: list[dict]
Each list element must contain keys:
"from_stop_I", "to_stop_I", "min", "max", "median" and "mean"... |
def create_stack(StackName=None, TemplateBody=None, TemplateURL=None, Parameters=None, DisableRollback=None, TimeoutInMinutes=None, NotificationARNs=None, Capabilities=None, ResourceTypes=None, RoleARN=None, OnFailure=None, StackPolicyBody=None, StackPolicyURL=None, Tags=None, ClientRequestToken=None):
"""
Crea... | def function[create_stack, parameter[StackName, TemplateBody, TemplateURL, Parameters, DisableRollback, TimeoutInMinutes, NotificationARNs, Capabilities, ResourceTypes, RoleARN, OnFailure, StackPolicyBody, StackPolicyURL, Tags, ClientRequestToken]]:
constant[
Creates a stack as specified in the template. Af... | keyword[def] identifier[create_stack] ( identifier[StackName] = keyword[None] , identifier[TemplateBody] = keyword[None] , identifier[TemplateURL] = keyword[None] , identifier[Parameters] = keyword[None] , identifier[DisableRollback] = keyword[None] , identifier[TimeoutInMinutes] = keyword[None] , identifier[Notifica... | def create_stack(StackName=None, TemplateBody=None, TemplateURL=None, Parameters=None, DisableRollback=None, TimeoutInMinutes=None, NotificationARNs=None, Capabilities=None, ResourceTypes=None, RoleARN=None, OnFailure=None, StackPolicyBody=None, StackPolicyURL=None, Tags=None, ClientRequestToken=None):
"""
Crea... |
def _handle_somatic_ensemble(vrn_file, data):
"""For somatic ensemble, discard normal samples and filtered variants from vcfs.
Only needed for bcbio.variation based ensemble calling.
"""
if tz.get_in(["metadata", "phenotype"], data, "").lower().startswith("tumor"):
vrn_file_temp = vrn_file.repl... | def function[_handle_somatic_ensemble, parameter[vrn_file, data]]:
constant[For somatic ensemble, discard normal samples and filtered variants from vcfs.
Only needed for bcbio.variation based ensemble calling.
]
if call[call[call[name[tz].get_in, parameter[list[[<ast.Constant object at 0x7da20c... | keyword[def] identifier[_handle_somatic_ensemble] ( identifier[vrn_file] , identifier[data] ):
literal[string]
keyword[if] identifier[tz] . identifier[get_in] ([ literal[string] , literal[string] ], identifier[data] , literal[string] ). identifier[lower] (). identifier[startswith] ( literal[string] ):
... | def _handle_somatic_ensemble(vrn_file, data):
"""For somatic ensemble, discard normal samples and filtered variants from vcfs.
Only needed for bcbio.variation based ensemble calling.
"""
if tz.get_in(['metadata', 'phenotype'], data, '').lower().startswith('tumor'):
vrn_file_temp = vrn_file.repl... |
def remove(self, abspath_or_winfile, enable_verbose=True):
"""Remove absolute path or WinFile from FileCollection.
"""
if isinstance(abspath_or_winfile, str): # abspath
try:
del self.files[abspath_or_winfile]
except KeyError:
if enable_verb... | def function[remove, parameter[self, abspath_or_winfile, enable_verbose]]:
constant[Remove absolute path or WinFile from FileCollection.
]
if call[name[isinstance], parameter[name[abspath_or_winfile], name[str]]] begin[:]
<ast.Try object at 0x7da20c6a9630> | keyword[def] identifier[remove] ( identifier[self] , identifier[abspath_or_winfile] , identifier[enable_verbose] = keyword[True] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[abspath_or_winfile] , identifier[str] ):
keyword[try] :
keyword[del] id... | def remove(self, abspath_or_winfile, enable_verbose=True):
"""Remove absolute path or WinFile from FileCollection.
"""
if isinstance(abspath_or_winfile, str): # abspath
try:
del self.files[abspath_or_winfile] # depends on [control=['try'], data=[]]
except KeyError:
... |
def set_info(self, key, value, append=True):
"""
Set any special info you wish to the given key. Each info is stored in
a list and will be appended to rather then overriden unless append is
False.
"""
if append:
if key not in self.info:
self.in... | def function[set_info, parameter[self, key, value, append]]:
constant[
Set any special info you wish to the given key. Each info is stored in
a list and will be appended to rather then overriden unless append is
False.
]
if name[append] begin[:]
if compare... | keyword[def] identifier[set_info] ( identifier[self] , identifier[key] , identifier[value] , identifier[append] = keyword[True] ):
literal[string]
keyword[if] identifier[append] :
keyword[if] identifier[key] keyword[not] keyword[in] identifier[self] . identifier[info] :
... | def set_info(self, key, value, append=True):
"""
Set any special info you wish to the given key. Each info is stored in
a list and will be appended to rather then overriden unless append is
False.
"""
if append:
if key not in self.info:
self.info[key] = [] # ... |
def work():
"""Implement a worker for write-math.com."""
global n
cmd = utils.get_project_configuration()
if 'worker_api_key' not in cmd:
return ("You need to define a 'worker_api_key' in your ~/")
chunk_size = 1000
logging.info("Start working with n=%i", n)
for _ in range(chunk_s... | def function[work, parameter[]]:
constant[Implement a worker for write-math.com.]
<ast.Global object at 0x7da1b28af6d0>
variable[cmd] assign[=] call[name[utils].get_project_configuration, parameter[]]
if compare[constant[worker_api_key] <ast.NotIn object at 0x7da2590d7190> name[cmd]] begin[:... | keyword[def] identifier[work] ():
literal[string]
keyword[global] identifier[n]
identifier[cmd] = identifier[utils] . identifier[get_project_configuration] ()
keyword[if] literal[string] keyword[not] keyword[in] identifier[cmd] :
keyword[return] ( literal[string] )
identifie... | def work():
"""Implement a worker for write-math.com."""
global n
cmd = utils.get_project_configuration()
if 'worker_api_key' not in cmd:
return "You need to define a 'worker_api_key' in your ~/" # depends on [control=['if'], data=[]]
chunk_size = 1000
logging.info('Start working with n... |
def addpattern(base_func):
"""Decorator to add a new case to a pattern-matching function, where the new case is checked last."""
def pattern_adder(func):
@_coconut.functools.wraps(func)
@_coconut_tco
def add_pattern_func(*args, **kwargs):
try:
return base_func... | def function[addpattern, parameter[base_func]]:
constant[Decorator to add a new case to a pattern-matching function, where the new case is checked last.]
def function[pattern_adder, parameter[func]]:
def function[add_pattern_func, parameter[]]:
<ast.Try object at 0x7da1b0a058... | keyword[def] identifier[addpattern] ( identifier[base_func] ):
literal[string]
keyword[def] identifier[pattern_adder] ( identifier[func] ):
@ identifier[_coconut] . identifier[functools] . identifier[wraps] ( identifier[func] )
@ identifier[_coconut_tco]
keyword[def] identifier[... | def addpattern(base_func):
"""Decorator to add a new case to a pattern-matching function, where the new case is checked last."""
def pattern_adder(func):
@_coconut.functools.wraps(func)
@_coconut_tco
def add_pattern_func(*args, **kwargs):
try:
return base_fu... |
async def EnableHA(self, specs):
'''
specs : typing.Sequence[~ControllersSpec]
Returns -> typing.Sequence[~ControllersChangeResult]
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='HighAvailability',
request='EnableHA',
... | <ast.AsyncFunctionDef object at 0x7da1b0dbc610> | keyword[async] keyword[def] identifier[EnableHA] ( identifier[self] , identifier[specs] ):
literal[string]
identifier[_params] = identifier[dict] ()
identifier[msg] = identifier[dict] ( identifier[type] = literal[string] ,
identifier[request] = literal[string] ,
... | async def EnableHA(self, specs):
"""
specs : typing.Sequence[~ControllersSpec]
Returns -> typing.Sequence[~ControllersChangeResult]
"""
# map input types to rpc msg
_params = dict()
msg = dict(type='HighAvailability', request='EnableHA', version=2, params=_params)
_params['sp... |
def to_dict(self):
"""Return dictionary of object."""
dictionary = {}
for key, value in iteritems(self.__dict__):
property_name = key[1:]
if hasattr(self, property_name):
dictionary.update({property_name: getattr(self, property_name, None)})
return... | def function[to_dict, parameter[self]]:
constant[Return dictionary of object.]
variable[dictionary] assign[=] dictionary[[], []]
for taget[tuple[[<ast.Name object at 0x7da18eb55ea0>, <ast.Name object at 0x7da18eb57d30>]]] in starred[call[name[iteritems], parameter[name[self].__dict__]]] begin[:]... | keyword[def] identifier[to_dict] ( identifier[self] ):
literal[string]
identifier[dictionary] ={}
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[iteritems] ( identifier[self] . identifier[__dict__] ):
identifier[property_name] = identifier[key] [ li... | def to_dict(self):
"""Return dictionary of object."""
dictionary = {}
for (key, value) in iteritems(self.__dict__):
property_name = key[1:]
if hasattr(self, property_name):
dictionary.update({property_name: getattr(self, property_name, None)}) # depends on [control=['if'], data=... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.