code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def ll(self, folder="", begin_from_file="", num=-1, all_grant_data=False):
"""
Get the list of files and permissions from S3.
This is similar to LL (ls -lah) in Linux: List of files with permissions.
Parameters
----------
folder : string
Path to file on S3
... | def function[ll, parameter[self, folder, begin_from_file, num, all_grant_data]]:
constant[
Get the list of files and permissions from S3.
This is similar to LL (ls -lah) in Linux: List of files with permissions.
Parameters
----------
folder : string
Path to... | keyword[def] identifier[ll] ( identifier[self] , identifier[folder] = literal[string] , identifier[begin_from_file] = literal[string] , identifier[num] =- literal[int] , identifier[all_grant_data] = keyword[False] ):
literal[string]
keyword[return] identifier[self] . identifier[ls] ( identifier[fo... | def ll(self, folder='', begin_from_file='', num=-1, all_grant_data=False):
"""
Get the list of files and permissions from S3.
This is similar to LL (ls -lah) in Linux: List of files with permissions.
Parameters
----------
folder : string
Path to file on S3
... |
def _task_directory(self, job_id, task_id, task_attempt):
"""The local dir for staging files for that particular task."""
dir_name = 'task' if task_id is None else str(task_id)
if task_attempt:
dir_name = '%s.%s' % (dir_name, task_attempt)
return self._provider_root() + '/' + job_id + '/' + dir_na... | def function[_task_directory, parameter[self, job_id, task_id, task_attempt]]:
constant[The local dir for staging files for that particular task.]
variable[dir_name] assign[=] <ast.IfExp object at 0x7da1b012f040>
if name[task_attempt] begin[:]
variable[dir_name] assign[=] binary_... | keyword[def] identifier[_task_directory] ( identifier[self] , identifier[job_id] , identifier[task_id] , identifier[task_attempt] ):
literal[string]
identifier[dir_name] = literal[string] keyword[if] identifier[task_id] keyword[is] keyword[None] keyword[else] identifier[str] ( identifier[task_id] )
... | def _task_directory(self, job_id, task_id, task_attempt):
"""The local dir for staging files for that particular task."""
dir_name = 'task' if task_id is None else str(task_id)
if task_attempt:
dir_name = '%s.%s' % (dir_name, task_attempt) # depends on [control=['if'], data=[]]
return self._pro... |
def _limit_and_df(self, query, limit, as_df=False):
"""adds a limit (limit==None := no limit) to any query and allow a return as pandas.DataFrame
:param bool as_df: if is set to True results return as pandas.DataFrame
:param `sqlalchemy.orm.query.Query` query: SQL Alchemy query
:param i... | def function[_limit_and_df, parameter[self, query, limit, as_df]]:
constant[adds a limit (limit==None := no limit) to any query and allow a return as pandas.DataFrame
:param bool as_df: if is set to True results return as pandas.DataFrame
:param `sqlalchemy.orm.query.Query` query: SQL Alchemy q... | keyword[def] identifier[_limit_and_df] ( identifier[self] , identifier[query] , identifier[limit] , identifier[as_df] = keyword[False] ):
literal[string]
keyword[if] identifier[limit] :
keyword[if] identifier[isinstance] ( identifier[limit] , identifier[int] ):
iden... | def _limit_and_df(self, query, limit, as_df=False):
"""adds a limit (limit==None := no limit) to any query and allow a return as pandas.DataFrame
:param bool as_df: if is set to True results return as pandas.DataFrame
:param `sqlalchemy.orm.query.Query` query: SQL Alchemy query
:param int,t... |
def get_named_tensor(self, name):
"""
Returns a named tensor if available.
Returns:
valid: True if named tensor found, False otherwise
tensor: If valid, will be a tensor, otherwise None
"""
if name in self.named_tensors:
return True, self.name... | def function[get_named_tensor, parameter[self, name]]:
constant[
Returns a named tensor if available.
Returns:
valid: True if named tensor found, False otherwise
tensor: If valid, will be a tensor, otherwise None
]
if compare[name[name] in name[self].name... | keyword[def] identifier[get_named_tensor] ( identifier[self] , identifier[name] ):
literal[string]
keyword[if] identifier[name] keyword[in] identifier[self] . identifier[named_tensors] :
keyword[return] keyword[True] , identifier[self] . identifier[named_tensors] [ identifier[name]... | def get_named_tensor(self, name):
"""
Returns a named tensor if available.
Returns:
valid: True if named tensor found, False otherwise
tensor: If valid, will be a tensor, otherwise None
"""
if name in self.named_tensors:
return (True, self.named_tensors[n... |
def parse_iptables_rule(line):
'''
Parse one iptables rule. Returns a dict where each iptables code argument
is mapped to a name using IPTABLES_ARGS.
'''
bits = line.split()
definition = {}
key = None
args = []
not_arg = False
def add_args():
arg_string = ' '.join(arg... | def function[parse_iptables_rule, parameter[line]]:
constant[
Parse one iptables rule. Returns a dict where each iptables code argument
is mapped to a name using IPTABLES_ARGS.
]
variable[bits] assign[=] call[name[line].split, parameter[]]
variable[definition] assign[=] dictionary[[]... | keyword[def] identifier[parse_iptables_rule] ( identifier[line] ):
literal[string]
identifier[bits] = identifier[line] . identifier[split] ()
identifier[definition] ={}
identifier[key] = keyword[None]
identifier[args] =[]
identifier[not_arg] = keyword[False]
keyword[def] ide... | def parse_iptables_rule(line):
"""
Parse one iptables rule. Returns a dict where each iptables code argument
is mapped to a name using IPTABLES_ARGS.
"""
bits = line.split()
definition = {}
key = None
args = []
not_arg = False
def add_args():
arg_string = ' '.join(args)
... |
def edit_team(self, name, memberships=None, filter=None, description=None, show=None, theme=None,
perm_capture=None, perm_custom_events=None, perm_aws_data=None):
'''
**Description**
Edits an existing team. All arguments are optional. Team settings for any arguments unspecif... | def function[edit_team, parameter[self, name, memberships, filter, description, show, theme, perm_capture, perm_custom_events, perm_aws_data]]:
constant[
**Description**
Edits an existing team. All arguments are optional. Team settings for any arguments unspecified will remain at their curren... | keyword[def] identifier[edit_team] ( identifier[self] , identifier[name] , identifier[memberships] = keyword[None] , identifier[filter] = keyword[None] , identifier[description] = keyword[None] , identifier[show] = keyword[None] , identifier[theme] = keyword[None] ,
identifier[perm_capture] = keyword[None] , identif... | def edit_team(self, name, memberships=None, filter=None, description=None, show=None, theme=None, perm_capture=None, perm_custom_events=None, perm_aws_data=None):
"""
**Description**
Edits an existing team. All arguments are optional. Team settings for any arguments unspecified will remain at the... |
def update_annotations(self):
"""Update annotations made by the user, including bookmarks and events.
Depending on the settings, it might add the bookmarks to overview and
traces.
"""
start_time = self.parent.overview.start_time
if self.parent.notes.annot is None:
... | def function[update_annotations, parameter[self]]:
constant[Update annotations made by the user, including bookmarks and events.
Depending on the settings, it might add the bookmarks to overview and
traces.
]
variable[start_time] assign[=] name[self].parent.overview.start_time
... | keyword[def] identifier[update_annotations] ( identifier[self] ):
literal[string]
identifier[start_time] = identifier[self] . identifier[parent] . identifier[overview] . identifier[start_time]
keyword[if] identifier[self] . identifier[parent] . identifier[notes] . identifier[annot] key... | def update_annotations(self):
"""Update annotations made by the user, including bookmarks and events.
Depending on the settings, it might add the bookmarks to overview and
traces.
"""
start_time = self.parent.overview.start_time
if self.parent.notes.annot is None:
all_annot =... |
def update_virtual_meta(self):
"""Will read back the virtual column etc, written by :func:`DataFrame.write_virtual_meta`. This will be done when opening a DataFrame."""
import astropy.units
try:
path = os.path.join(self.get_private_dir(create=False), "virtual_meta.yaml")
... | def function[update_virtual_meta, parameter[self]]:
constant[Will read back the virtual column etc, written by :func:`DataFrame.write_virtual_meta`. This will be done when opening a DataFrame.]
import module[astropy.units]
<ast.Try object at 0x7da18dc04400> | keyword[def] identifier[update_virtual_meta] ( identifier[self] ):
literal[string]
keyword[import] identifier[astropy] . identifier[units]
keyword[try] :
identifier[path] = identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[get_private_dir] ... | def update_virtual_meta(self):
"""Will read back the virtual column etc, written by :func:`DataFrame.write_virtual_meta`. This will be done when opening a DataFrame."""
import astropy.units
try:
path = os.path.join(self.get_private_dir(create=False), 'virtual_meta.yaml')
if os.path.exists(pa... |
def forge_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To', rel_date=None,
rel_confidence='high', rel_reason=''):
"""
Forges a relationship between two TLOs.
Args:
left_id: The CRITs ID of the fi... | def function[forge_relationship, parameter[self, left_id, left_type, right_id, right_type, rel_type, rel_date, rel_confidence, rel_reason]]:
constant[
Forges a relationship between two TLOs.
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type... | keyword[def] identifier[forge_relationship] ( identifier[self] , identifier[left_id] , identifier[left_type] , identifier[right_id] , identifier[right_type] ,
identifier[rel_type] = literal[string] , identifier[rel_date] = keyword[None] ,
identifier[rel_confidence] = literal[string] , identifier[rel_reason] = liter... | def forge_relationship(self, left_id, left_type, right_id, right_type, rel_type='Related To', rel_date=None, rel_confidence='high', rel_reason=''):
"""
Forges a relationship between two TLOs.
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of... |
def round_sig_error(num, uncert, pm=False):
"""
Return a string of the number and its uncertainty to the right sig figs via uncertainty's print methods.
The uncertainty determines the sig fig rounding of the number.
https://pythonhosted.org/uncertainties/user_guide.html
"""
u = ufloat(num, uncer... | def function[round_sig_error, parameter[num, uncert, pm]]:
constant[
Return a string of the number and its uncertainty to the right sig figs via uncertainty's print methods.
The uncertainty determines the sig fig rounding of the number.
https://pythonhosted.org/uncertainties/user_guide.html
]
... | keyword[def] identifier[round_sig_error] ( identifier[num] , identifier[uncert] , identifier[pm] = keyword[False] ):
literal[string]
identifier[u] = identifier[ufloat] ( identifier[num] , identifier[uncert] )
keyword[if] identifier[pm] :
keyword[return] literal[string] . identifier[format] ... | def round_sig_error(num, uncert, pm=False):
"""
Return a string of the number and its uncertainty to the right sig figs via uncertainty's print methods.
The uncertainty determines the sig fig rounding of the number.
https://pythonhosted.org/uncertainties/user_guide.html
"""
u = ufloat(num, uncer... |
def object_get(self, multihash, **kwargs):
"""Get and serialize the DAG node named by multihash.
.. code-block:: python
>>> c.object_get('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
{'Data': '\x08\x01',
'Links': [
{'Hash': 'Qmd2xkBfEwEs9oMTk77A... | def function[object_get, parameter[self, multihash]]:
constant[Get and serialize the DAG node named by multihash.
.. code-block:: python
>>> c.object_get('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
{'Data': '',
'Links': [
{'Hash': 'Qmd2xkBfE... | keyword[def] identifier[object_get] ( identifier[self] , identifier[multihash] ,** identifier[kwargs] ):
literal[string]
identifier[args] =( identifier[multihash] ,)
keyword[return] identifier[self] . identifier[_client] . identifier[request] ( literal[string] , identifier[args] ,
... | def object_get(self, multihash, **kwargs):
"""Get and serialize the DAG node named by multihash.
.. code-block:: python
>>> c.object_get('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
{'Data': '\x08\x01',
'Links': [
{'Hash': 'Qmd2xkBfEwEs9oMTk77A6jrs... |
def run(self, request_cb, notification_cb):
"""Run the event loop to receive requests and notifications from Nvim.
While the event loop is running, `request_cb` and `_notification_cb`
will be called whenever requests or notifications are respectively
available.
"""
self.... | def function[run, parameter[self, request_cb, notification_cb]]:
constant[Run the event loop to receive requests and notifications from Nvim.
While the event loop is running, `request_cb` and `_notification_cb`
will be called whenever requests or notifications are respectively
available... | keyword[def] identifier[run] ( identifier[self] , identifier[request_cb] , identifier[notification_cb] ):
literal[string]
identifier[self] . identifier[_request_cb] = identifier[request_cb]
identifier[self] . identifier[_notification_cb] = identifier[notification_cb]
identifier[... | def run(self, request_cb, notification_cb):
"""Run the event loop to receive requests and notifications from Nvim.
While the event loop is running, `request_cb` and `_notification_cb`
will be called whenever requests or notifications are respectively
available.
"""
self._request... |
def getLorenzShares(data,weights=None,percentiles=[0.5],presorted=False):
'''
Calculates the Lorenz curve at the requested percentiles of (weighted) data.
Median by default.
Parameters
----------
data : numpy.array
A 1D array of float data.
weights : numpy.array
A weighting ... | def function[getLorenzShares, parameter[data, weights, percentiles, presorted]]:
constant[
Calculates the Lorenz curve at the requested percentiles of (weighted) data.
Median by default.
Parameters
----------
data : numpy.array
A 1D array of float data.
weights : numpy.array
... | keyword[def] identifier[getLorenzShares] ( identifier[data] , identifier[weights] = keyword[None] , identifier[percentiles] =[ literal[int] ], identifier[presorted] = keyword[False] ):
literal[string]
keyword[if] identifier[weights] keyword[is] keyword[None] :
identifier[weights] = identifier[n... | def getLorenzShares(data, weights=None, percentiles=[0.5], presorted=False):
"""
Calculates the Lorenz curve at the requested percentiles of (weighted) data.
Median by default.
Parameters
----------
data : numpy.array
A 1D array of float data.
weights : numpy.array
A weighti... |
def Nu_plate_Muley_Manglik(Re, Pr, chevron_angle, plate_enlargement_factor):
r'''Calculates Nusselt number for single-phase flow in a
Chevron-style plate heat exchanger according to [1]_, also shown in [2]_
and [3]_.
.. math::
Nu = [0.2668 - 0.006967(\beta) + 7.244\times 10^{-5}(\beta)^2]... | def function[Nu_plate_Muley_Manglik, parameter[Re, Pr, chevron_angle, plate_enlargement_factor]]:
constant[Calculates Nusselt number for single-phase flow in a
Chevron-style plate heat exchanger according to [1]_, also shown in [2]_
and [3]_.
.. math::
Nu = [0.2668 - 0.006967(\beta) +... | keyword[def] identifier[Nu_plate_Muley_Manglik] ( identifier[Re] , identifier[Pr] , identifier[chevron_angle] , identifier[plate_enlargement_factor] ):
literal[string]
identifier[beta] , identifier[phi] = identifier[chevron_angle] , identifier[plate_enlargement_factor]
identifier[t1] =( literal[int] ... | def Nu_plate_Muley_Manglik(Re, Pr, chevron_angle, plate_enlargement_factor):
"""Calculates Nusselt number for single-phase flow in a
Chevron-style plate heat exchanger according to [1]_, also shown in [2]_
and [3]_.
.. math::
Nu = [0.2668 - 0.006967(\\beta) + 7.244\\times 10^{-5}(\\beta)^... |
def cdf(self, x):
"""
Computes the cdf of a specific value, ie. computes F(x) where F denotes
the CDF of the distribution.
"""
t = 0
N = float(self.n)
if len(self) == 1: # only one centroid
return int(x >= self.C.min_key())
for i, key in enu... | def function[cdf, parameter[self, x]]:
constant[
Computes the cdf of a specific value, ie. computes F(x) where F denotes
the CDF of the distribution.
]
variable[t] assign[=] constant[0]
variable[N] assign[=] call[name[float], parameter[name[self].n]]
if compare[ca... | keyword[def] identifier[cdf] ( identifier[self] , identifier[x] ):
literal[string]
identifier[t] = literal[int]
identifier[N] = identifier[float] ( identifier[self] . identifier[n] )
keyword[if] identifier[len] ( identifier[self] )== literal[int] :
keyword[return] ... | def cdf(self, x):
"""
Computes the cdf of a specific value, ie. computes F(x) where F denotes
the CDF of the distribution.
"""
t = 0
N = float(self.n)
if len(self) == 1: # only one centroid
return int(x >= self.C.min_key()) # depends on [control=['if'], data=[]]
for... |
def get_json_feed_content(url, offset=0, limit=None):
"""
Get the entries in a JSON feed
"""
end = limit + offset if limit is not None else None
response = _get(url)
try:
content = json.loads(response.text)
except Exception as parse_error:
logger.warning(
'Fail... | def function[get_json_feed_content, parameter[url, offset, limit]]:
constant[
Get the entries in a JSON feed
]
variable[end] assign[=] <ast.IfExp object at 0x7da1b09be1d0>
variable[response] assign[=] call[name[_get], parameter[name[url]]]
<ast.Try object at 0x7da1b09bd270>
retur... | keyword[def] identifier[get_json_feed_content] ( identifier[url] , identifier[offset] = literal[int] , identifier[limit] = keyword[None] ):
literal[string]
identifier[end] = identifier[limit] + identifier[offset] keyword[if] identifier[limit] keyword[is] keyword[not] keyword[None] keyword[else] key... | def get_json_feed_content(url, offset=0, limit=None):
"""
Get the entries in a JSON feed
"""
end = limit + offset if limit is not None else None
response = _get(url)
try:
content = json.loads(response.text) # depends on [control=['try'], data=[]]
except Exception as parse_error:
... |
def gw_get(object_dict, name=None, plugin=None):
"""
Getter function to retrieve objects from a given object dictionary.
Used mainly to provide get() inside patterns.
:param object_dict: objects, which must have 'name' and 'plugin' as attribute
:type object_dict: dictionary
:param name: name o... | def function[gw_get, parameter[object_dict, name, plugin]]:
constant[
Getter function to retrieve objects from a given object dictionary.
Used mainly to provide get() inside patterns.
:param object_dict: objects, which must have 'name' and 'plugin' as attribute
:type object_dict: dictionary
... | keyword[def] identifier[gw_get] ( identifier[object_dict] , identifier[name] = keyword[None] , identifier[plugin] = keyword[None] ):
literal[string]
keyword[if] identifier[plugin] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[name] keyword[is] keyword[None] :
... | def gw_get(object_dict, name=None, plugin=None):
"""
Getter function to retrieve objects from a given object dictionary.
Used mainly to provide get() inside patterns.
:param object_dict: objects, which must have 'name' and 'plugin' as attribute
:type object_dict: dictionary
:param name: name o... |
def build(sub_parser, cmds):
"""todo: Docstring for build
:param sub_parser: arg description
:type sub_parser: type description
:return:
:rtype:
"""
res = {}
for cmd in cmds:
res[cmd.name] = cmd(sub_parser)
# end for cmd in cmds
return res | def function[build, parameter[sub_parser, cmds]]:
constant[todo: Docstring for build
:param sub_parser: arg description
:type sub_parser: type description
:return:
:rtype:
]
variable[res] assign[=] dictionary[[], []]
for taget[name[cmd]] in starred[name[cmds]] begin[:]
... | keyword[def] identifier[build] ( identifier[sub_parser] , identifier[cmds] ):
literal[string]
identifier[res] ={}
keyword[for] identifier[cmd] keyword[in] identifier[cmds] :
identifier[res] [ identifier[cmd] . identifier[name] ]= identifier[cmd] ( identifier[sub_parser] )
k... | def build(sub_parser, cmds):
"""todo: Docstring for build
:param sub_parser: arg description
:type sub_parser: type description
:return:
:rtype:
"""
res = {}
for cmd in cmds:
res[cmd.name] = cmd(sub_parser) # depends on [control=['for'], data=['cmd']]
# end for cmd in cmds
... |
def _rle(self, a):
'''
rle implementation credit to Thomas Browne from his SOF post Sept 2015
Parameters
----------
a : array, shape[n,]
input vector
Returns
-------
z : array, shape[nt,]
run lengths
p : array, shape[nt,]
... | def function[_rle, parameter[self, a]]:
constant[
rle implementation credit to Thomas Browne from his SOF post Sept 2015
Parameters
----------
a : array, shape[n,]
input vector
Returns
-------
z : array, shape[nt,]
run lengths
... | keyword[def] identifier[_rle] ( identifier[self] , identifier[a] ):
literal[string]
identifier[ia] = identifier[np] . identifier[asarray] ( identifier[a] )
identifier[n] = identifier[len] ( identifier[ia] )
identifier[y] = identifier[np] . identifier[array] ( identifier[ia] [ lite... | def _rle(self, a):
"""
rle implementation credit to Thomas Browne from his SOF post Sept 2015
Parameters
----------
a : array, shape[n,]
input vector
Returns
-------
z : array, shape[nt,]
run lengths
p : array, shape[nt,]
... |
def on_need_compare(self, pair):
"""Re-classify pair based on file attributes and options."""
# print("on_need_compare", pair)
# If no metadata is available, we could only classify file entries as
# 'existing'.
# Now we use peer information to improve this classification.
... | def function[on_need_compare, parameter[self, pair]]:
constant[Re-classify pair based on file attributes and options.]
variable[c_pair] assign[=] tuple[[<ast.Attribute object at 0x7da1b0418a60>, <ast.Attribute object at 0x7da1b0419e70>]]
variable[org_pair] assign[=] name[c_pair]
variable... | keyword[def] identifier[on_need_compare] ( identifier[self] , identifier[pair] ):
literal[string]
identifier[c_pair] =( identifier[pair] . identifier[local_classification] , identifier[pair] . identifier[remote_classification] )
identifier[org_pair] = i... | def on_need_compare(self, pair):
"""Re-classify pair based on file attributes and options."""
# print("on_need_compare", pair)
# If no metadata is available, we could only classify file entries as
# 'existing'.
# Now we use peer information to improve this classification.
c_pair = (pair.local_cl... |
def hil_gps_encode(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, vn, ve, vd, cog, satellites_visible):
'''
The global position, as returned by the Global Positioning System
(GPS). This is NOT the global
position estimate of the ... | def function[hil_gps_encode, parameter[self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, vn, ve, vd, cog, satellites_visible]]:
constant[
The global position, as returned by the Global Positioning System
(GPS). This is NOT the global
positi... | keyword[def] identifier[hil_gps_encode] ( identifier[self] , identifier[time_usec] , identifier[fix_type] , identifier[lat] , identifier[lon] , identifier[alt] , identifier[eph] , identifier[epv] , identifier[vel] , identifier[vn] , identifier[ve] , identifier[vd] , identifier[cog] , identifier[satellites_visible] ):... | def hil_gps_encode(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, vn, ve, vd, cog, satellites_visible):
"""
The global position, as returned by the Global Positioning System
(GPS). This is NOT the global
position estimate of the sytem, but r... |
def iter_subscriptions(self, login=None, number=-1, etag=None):
"""Iterate over repositories subscribed to by ``login`` or the
authenticated user.
:param str login: (optional), name of user whose subscriptions you want
to see
:param int number: (optional), number of reposito... | def function[iter_subscriptions, parameter[self, login, number, etag]]:
constant[Iterate over repositories subscribed to by ``login`` or the
authenticated user.
:param str login: (optional), name of user whose subscriptions you want
to see
:param int number: (optional), numb... | keyword[def] identifier[iter_subscriptions] ( identifier[self] , identifier[login] = keyword[None] , identifier[number] =- literal[int] , identifier[etag] = keyword[None] ):
literal[string]
keyword[if] identifier[login] :
keyword[return] identifier[self] . identifier[user] ( identifi... | def iter_subscriptions(self, login=None, number=-1, etag=None):
"""Iterate over repositories subscribed to by ``login`` or the
authenticated user.
:param str login: (optional), name of user whose subscriptions you want
to see
:param int number: (optional), number of repositories... |
def add_otp_style(self, zip_odp, style_file):
"""
takes the slide content and merges in the style_file
"""
style = zipwrap.Zippier(style_file)
for picture_file in style.ls("Pictures"):
zip_odp.write(picture_file, style.cat(picture_file, True))
xml_data = style... | def function[add_otp_style, parameter[self, zip_odp, style_file]]:
constant[
takes the slide content and merges in the style_file
]
variable[style] assign[=] call[name[zipwrap].Zippier, parameter[name[style_file]]]
for taget[name[picture_file]] in starred[call[name[style].ls, par... | keyword[def] identifier[add_otp_style] ( identifier[self] , identifier[zip_odp] , identifier[style_file] ):
literal[string]
identifier[style] = identifier[zipwrap] . identifier[Zippier] ( identifier[style_file] )
keyword[for] identifier[picture_file] keyword[in] identifier[style] . iden... | def add_otp_style(self, zip_odp, style_file):
"""
takes the slide content and merges in the style_file
"""
style = zipwrap.Zippier(style_file)
for picture_file in style.ls('Pictures'):
zip_odp.write(picture_file, style.cat(picture_file, True)) # depends on [control=['for'], data=['p... |
def get_delta(value):
"""
Return a timedelta object based on the value which can be a timedelta
or a number of seconds (int or float).
Raise an exception in all other cases.
"""
if isinstance(value, (int, float)):
return timedelta(seconds=value)
elif isinstance(value, timedelta):
... | def function[get_delta, parameter[value]]:
constant[
Return a timedelta object based on the value which can be a timedelta
or a number of seconds (int or float).
Raise an exception in all other cases.
]
if call[name[isinstance], parameter[name[value], tuple[[<ast.Name object at 0x7da18f8... | keyword[def] identifier[get_delta] ( identifier[value] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[value] ,( identifier[int] , identifier[float] )):
keyword[return] identifier[timedelta] ( identifier[seconds] = identifier[value] )
keyword[elif] identifier[isinstance]... | def get_delta(value):
"""
Return a timedelta object based on the value which can be a timedelta
or a number of seconds (int or float).
Raise an exception in all other cases.
"""
if isinstance(value, (int, float)):
return timedelta(seconds=value) # depends on [control=['if'], data=[]]
... |
def imagetransformer_b12l_4h_b256_uncond_dr03_rel_tpu():
"""works very well on 4x4."""
hparams = imagetransformer_b12l_4h_b256_uncond_dr03_tpu()
hparams.shared_rel = True
hparams.dec_attention_type = cia.AttentionType.RELATIVE_LOCAL_1D
return hparams | def function[imagetransformer_b12l_4h_b256_uncond_dr03_rel_tpu, parameter[]]:
constant[works very well on 4x4.]
variable[hparams] assign[=] call[name[imagetransformer_b12l_4h_b256_uncond_dr03_tpu], parameter[]]
name[hparams].shared_rel assign[=] constant[True]
name[hparams].dec_attention... | keyword[def] identifier[imagetransformer_b12l_4h_b256_uncond_dr03_rel_tpu] ():
literal[string]
identifier[hparams] = identifier[imagetransformer_b12l_4h_b256_uncond_dr03_tpu] ()
identifier[hparams] . identifier[shared_rel] = keyword[True]
identifier[hparams] . identifier[dec_attention_type] = identifier... | def imagetransformer_b12l_4h_b256_uncond_dr03_rel_tpu():
"""works very well on 4x4."""
hparams = imagetransformer_b12l_4h_b256_uncond_dr03_tpu()
hparams.shared_rel = True
hparams.dec_attention_type = cia.AttentionType.RELATIVE_LOCAL_1D
return hparams |
def subtract(dict_a, dict_b, strict=False):
"""a stricter form of subtract_by_key(), this version will only remove an
entry from dict_a if the key is in dict_b *and* the value at that key
matches"""
if not strict:
return subtract_by_key(dict_a, dict_b)
difference_dict = {}
for key in di... | def function[subtract, parameter[dict_a, dict_b, strict]]:
constant[a stricter form of subtract_by_key(), this version will only remove an
entry from dict_a if the key is in dict_b *and* the value at that key
matches]
if <ast.UnaryOp object at 0x7da1b28b9210> begin[:]
return[call[name[su... | keyword[def] identifier[subtract] ( identifier[dict_a] , identifier[dict_b] , identifier[strict] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[strict] :
keyword[return] identifier[subtract_by_key] ( identifier[dict_a] , identifier[dict_b] )
identifier[difference_... | def subtract(dict_a, dict_b, strict=False):
"""a stricter form of subtract_by_key(), this version will only remove an
entry from dict_a if the key is in dict_b *and* the value at that key
matches"""
if not strict:
return subtract_by_key(dict_a, dict_b) # depends on [control=['if'], data=[]]
... |
def register_alias_type(klass, *args):
"""
This function allows you to map subclasses of L{ClassAlias} to classes
listed in C{args}.
When an object is read/written from/to the AMF stream, a paired L{ClassAlias}
instance is created (or reused), based on the Python class of that object.
L{ClassAl... | def function[register_alias_type, parameter[klass]]:
constant[
This function allows you to map subclasses of L{ClassAlias} to classes
listed in C{args}.
When an object is read/written from/to the AMF stream, a paired L{ClassAlias}
instance is created (or reused), based on the Python class of th... | keyword[def] identifier[register_alias_type] ( identifier[klass] ,* identifier[args] ):
literal[string]
keyword[def] identifier[check_type_registered] ( identifier[arg] ):
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[ALIAS_TYPES] . identifier[iteritems] ():
ke... | def register_alias_type(klass, *args):
"""
This function allows you to map subclasses of L{ClassAlias} to classes
listed in C{args}.
When an object is read/written from/to the AMF stream, a paired L{ClassAlias}
instance is created (or reused), based on the Python class of that object.
L{ClassAl... |
def addOntology(self):
"""
Adds a new Ontology to this repo.
"""
self._openRepo()
name = self._args.name
filePath = self._getFilePath(self._args.filePath,
self._args.relativePath)
if name is None:
name = getNameFrom... | def function[addOntology, parameter[self]]:
constant[
Adds a new Ontology to this repo.
]
call[name[self]._openRepo, parameter[]]
variable[name] assign[=] name[self]._args.name
variable[filePath] assign[=] call[name[self]._getFilePath, parameter[name[self]._args.filePath,... | keyword[def] identifier[addOntology] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_openRepo] ()
identifier[name] = identifier[self] . identifier[_args] . identifier[name]
identifier[filePath] = identifier[self] . identifier[_getFilePath] ( identifier[self] ... | def addOntology(self):
"""
Adds a new Ontology to this repo.
"""
self._openRepo()
name = self._args.name
filePath = self._getFilePath(self._args.filePath, self._args.relativePath)
if name is None:
name = getNameFromPath(filePath) # depends on [control=['if'], data=['name']]
... |
def _get_definitions(source):
# type: (str) -> Tuple[Dict[str, str], int]
"""Extract a dictionary of arguments and definitions.
Args:
source: The source for a section of a usage string that contains
definitions.
Returns:
A two-tuple containing a dictionary of all arguments ... | def function[_get_definitions, parameter[source]]:
constant[Extract a dictionary of arguments and definitions.
Args:
source: The source for a section of a usage string that contains
definitions.
Returns:
A two-tuple containing a dictionary of all arguments and definitions a... | keyword[def] identifier[_get_definitions] ( identifier[source] ):
literal[string]
identifier[max_len] = literal[int]
identifier[descs] = identifier[collections] . identifier[OrderedDict] ()
identifier[lines] =( identifier[s] . identifier[strip] () keyword[for] identifier[s] keyword[in] ident... | def _get_definitions(source):
# type: (str) -> Tuple[Dict[str, str], int]
'Extract a dictionary of arguments and definitions.\n\n Args:\n source: The source for a section of a usage string that contains\n definitions.\n\n Returns:\n A two-tuple containing a dictionary of all argum... |
def fix_e722(self, result):
"""fix bare except"""
(line_index, _, target) = get_index_offset_contents(result,
self.source)
if BARE_EXCEPT_REGEX.search(target):
self.source[line_index] = '{0}{1}'.format(
targe... | def function[fix_e722, parameter[self, result]]:
constant[fix bare except]
<ast.Tuple object at 0x7da1b08a5c30> assign[=] call[name[get_index_offset_contents], parameter[name[result], name[self].source]]
if call[name[BARE_EXCEPT_REGEX].search, parameter[name[target]]] begin[:]
ca... | keyword[def] identifier[fix_e722] ( identifier[self] , identifier[result] ):
literal[string]
( identifier[line_index] , identifier[_] , identifier[target] )= identifier[get_index_offset_contents] ( identifier[result] ,
identifier[self] . identifier[source] )
keyword[if] identifier... | def fix_e722(self, result):
"""fix bare except"""
(line_index, _, target) = get_index_offset_contents(result, self.source)
if BARE_EXCEPT_REGEX.search(target):
self.source[line_index] = '{0}{1}'.format(target[:result['column'] - 1], 'except Exception:') # depends on [control=['if'], data=[]] |
def _streamSSE(url, on_data=print, accrue=False):
'''internal'''
messages = SSEClient(url)
if accrue:
ret = []
for msg in messages:
data = msg.data
on_data(json.loads(data))
if accrue:
ret.append(msg)
return ret | def function[_streamSSE, parameter[url, on_data, accrue]]:
constant[internal]
variable[messages] assign[=] call[name[SSEClient], parameter[name[url]]]
if name[accrue] begin[:]
variable[ret] assign[=] list[[]]
for taget[name[msg]] in starred[name[messages]] begin[:]
... | keyword[def] identifier[_streamSSE] ( identifier[url] , identifier[on_data] = identifier[print] , identifier[accrue] = keyword[False] ):
literal[string]
identifier[messages] = identifier[SSEClient] ( identifier[url] )
keyword[if] identifier[accrue] :
identifier[ret] =[]
keyword[for] i... | def _streamSSE(url, on_data=print, accrue=False):
"""internal"""
messages = SSEClient(url)
if accrue:
ret = [] # depends on [control=['if'], data=[]]
for msg in messages:
data = msg.data
on_data(json.loads(data))
if accrue:
ret.append(msg) # depends on [cont... |
def get_content(session, urls):
"""
Loads the content from URLs, ignoring connection errors.
:param session: requests Session instance
:param urls: list, str URLs
:return: str, content
"""
for url in urls:
resp = session.get(url)
if resp.ok:
return resp.json()
... | def function[get_content, parameter[session, urls]]:
constant[
Loads the content from URLs, ignoring connection errors.
:param session: requests Session instance
:param urls: list, str URLs
:return: str, content
]
for taget[name[url]] in starred[name[urls]] begin[:]
v... | keyword[def] identifier[get_content] ( identifier[session] , identifier[urls] ):
literal[string]
keyword[for] identifier[url] keyword[in] identifier[urls] :
identifier[resp] = identifier[session] . identifier[get] ( identifier[url] )
keyword[if] identifier[resp] . identifier[ok] :
... | def get_content(session, urls):
"""
Loads the content from URLs, ignoring connection errors.
:param session: requests Session instance
:param urls: list, str URLs
:return: str, content
"""
for url in urls:
resp = session.get(url)
if resp.ok:
return resp.json() # ... |
async def queue_declare(self):
""" Override this method to change how a queue is declared """
await self.channel.queue_declare(
self.queue,
durable=self.durable,
exclusive=self.exclusive,
no_wait=self.no_wait
) | <ast.AsyncFunctionDef object at 0x7da1b1bbad10> | keyword[async] keyword[def] identifier[queue_declare] ( identifier[self] ):
literal[string]
keyword[await] identifier[self] . identifier[channel] . identifier[queue_declare] (
identifier[self] . identifier[queue] ,
identifier[durable] = identifier[self] . identifier[durable] ,
... | async def queue_declare(self):
""" Override this method to change how a queue is declared """
await self.channel.queue_declare(self.queue, durable=self.durable, exclusive=self.exclusive, no_wait=self.no_wait) |
def dispatch(self):
'Perform dispatch, using request embedded within flask global state'
import flask
body = flask.request.get_json()
return self. dispatch_with_args(body, argMap=dict()) | def function[dispatch, parameter[self]]:
constant[Perform dispatch, using request embedded within flask global state]
import module[flask]
variable[body] assign[=] call[name[flask].request.get_json, parameter[]]
return[call[name[self].dispatch_with_args, parameter[name[body]]]] | keyword[def] identifier[dispatch] ( identifier[self] ):
literal[string]
keyword[import] identifier[flask]
identifier[body] = identifier[flask] . identifier[request] . identifier[get_json] ()
keyword[return] identifier[self] . identifier[dispatch_with_args] ( identifier[body] , ... | def dispatch(self):
"""Perform dispatch, using request embedded within flask global state"""
import flask
body = flask.request.get_json()
return self.dispatch_with_args(body, argMap=dict()) |
def _is_empty_cache_record(self, rec):
"""
Return True if the specified cache record has no data, False otherwise.
:param rec: cache record returned by :py:meth:`~._cache_get`
:type rec: dict
:return: True if record is empty, False otherwise
:rtype: bool
"""
... | def function[_is_empty_cache_record, parameter[self, rec]]:
constant[
Return True if the specified cache record has no data, False otherwise.
:param rec: cache record returned by :py:meth:`~._cache_get`
:type rec: dict
:return: True if record is empty, False otherwise
:r... | keyword[def] identifier[_is_empty_cache_record] ( identifier[self] , identifier[rec] ):
literal[string]
keyword[for] identifier[k] keyword[in] [
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
... | def _is_empty_cache_record(self, rec):
"""
Return True if the specified cache record has no data, False otherwise.
:param rec: cache record returned by :py:meth:`~._cache_get`
:type rec: dict
:return: True if record is empty, False otherwise
:rtype: bool
"""
# th... |
def url(self):
""" Full URL as requested by the client (computed).
This value is constructed out of different environment variables
and includes scheme, host, port, scriptname, path and query string.
"""
scheme = self.environ.get('wsgi.url_scheme', 'http')
host ... | def function[url, parameter[self]]:
constant[ Full URL as requested by the client (computed).
This value is constructed out of different environment variables
and includes scheme, host, port, scriptname, path and query string.
]
variable[scheme] assign[=] call[name[self... | keyword[def] identifier[url] ( identifier[self] ):
literal[string]
identifier[scheme] = identifier[self] . identifier[environ] . identifier[get] ( literal[string] , literal[string] )
identifier[host] = identifier[self] . identifier[environ] . identifier[get] ( literal[string] , identifier[... | def url(self):
""" Full URL as requested by the client (computed).
This value is constructed out of different environment variables
and includes scheme, host, port, scriptname, path and query string.
"""
scheme = self.environ.get('wsgi.url_scheme', 'http')
host = self.envir... |
def dump(self, output, close_after_write=True):
"""Write data to the output with tabular format.
Args:
output (file descriptor or str):
file descriptor or path to the output file.
close_after_write (bool, optional):
Close the output after write.
... | def function[dump, parameter[self, output, close_after_write]]:
constant[Write data to the output with tabular format.
Args:
output (file descriptor or str):
file descriptor or path to the output file.
close_after_write (bool, optional):
Close the... | keyword[def] identifier[dump] ( identifier[self] , identifier[output] , identifier[close_after_write] = keyword[True] ):
literal[string]
keyword[try] :
identifier[output] . identifier[write]
identifier[self] . identifier[stream] = identifier[output]
keyword[exc... | def dump(self, output, close_after_write=True):
"""Write data to the output with tabular format.
Args:
output (file descriptor or str):
file descriptor or path to the output file.
close_after_write (bool, optional):
Close the output after write.
... |
def register_user_type(self, keyspace, user_type, klass):
"""
Registers a class to use to represent a particular user-defined type.
Query parameters for this user-defined type will be assumed to be
instances of `klass`. Result sets for this user-defined type will
be instances of... | def function[register_user_type, parameter[self, keyspace, user_type, klass]]:
constant[
Registers a class to use to represent a particular user-defined type.
Query parameters for this user-defined type will be assumed to be
instances of `klass`. Result sets for this user-defined type w... | keyword[def] identifier[register_user_type] ( identifier[self] , identifier[keyspace] , identifier[user_type] , identifier[klass] ):
literal[string]
keyword[if] identifier[self] . identifier[protocol_version] < literal[int] :
identifier[log] . identifier[warning] ( literal[string]
... | def register_user_type(self, keyspace, user_type, klass):
"""
Registers a class to use to represent a particular user-defined type.
Query parameters for this user-defined type will be assumed to be
instances of `klass`. Result sets for this user-defined type will
be instances of `kl... |
def get_device_stats(self):
"""Get GPU stats."""
stats = []
for index, device_handle in enumerate(self.device_handles):
device_stats = {}
# Dictionnary key is the GPU_ID
device_stats['key'] = self.get_key()
# GPU id (for multiple GPU, start at 0)
... | def function[get_device_stats, parameter[self]]:
constant[Get GPU stats.]
variable[stats] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da18f810610>, <ast.Name object at 0x7da18f58d210>]]] in starred[call[name[enumerate], parameter[name[self].device_handles]]] begin[:]
... | keyword[def] identifier[get_device_stats] ( identifier[self] ):
literal[string]
identifier[stats] =[]
keyword[for] identifier[index] , identifier[device_handle] keyword[in] identifier[enumerate] ( identifier[self] . identifier[device_handles] ):
identifier[device_stats] ={... | def get_device_stats(self):
"""Get GPU stats."""
stats = []
for (index, device_handle) in enumerate(self.device_handles):
device_stats = {}
# Dictionnary key is the GPU_ID
device_stats['key'] = self.get_key()
# GPU id (for multiple GPU, start at 0)
device_stats['gpu_i... |
def tensor_dim_to_mesh_dim_size(layout, mesh_shape, tensor_dim):
"""How many ways does a tensor dimension get split.
This is used to "cheat" when building the mtf graph and peek at how a
tensor dimension will be split. Returns 1 if the tensor dimension is not
split.
Args:
layout: an input to convert_to... | def function[tensor_dim_to_mesh_dim_size, parameter[layout, mesh_shape, tensor_dim]]:
constant[How many ways does a tensor dimension get split.
This is used to "cheat" when building the mtf graph and peek at how a
tensor dimension will be split. Returns 1 if the tensor dimension is not
split.
Args:
... | keyword[def] identifier[tensor_dim_to_mesh_dim_size] ( identifier[layout] , identifier[mesh_shape] , identifier[tensor_dim] ):
literal[string]
identifier[layout_rules] = identifier[convert_to_layout_rules] ( identifier[layout] )
identifier[mesh_shape] = identifier[convert_to_shape] ( identifier[mesh_shape] ... | def tensor_dim_to_mesh_dim_size(layout, mesh_shape, tensor_dim):
"""How many ways does a tensor dimension get split.
This is used to "cheat" when building the mtf graph and peek at how a
tensor dimension will be split. Returns 1 if the tensor dimension is not
split.
Args:
layout: an input to convert_... |
def reexport_tf_summary():
"""Re-export all symbols from the original tf.summary.
This function finds the original tf.summary V2 API and re-exports all the
symbols from it within this module as well, so that when this module is
patched into the TF API namespace as the new tf.summary, the effect is an
overlay... | def function[reexport_tf_summary, parameter[]]:
constant[Re-export all symbols from the original tf.summary.
This function finds the original tf.summary V2 API and re-exports all the
symbols from it within this module as well, so that when this module is
patched into the TF API namespace as the new tf.su... | keyword[def] identifier[reexport_tf_summary] ():
literal[string]
keyword[import] identifier[sys]
identifier[packages] =[
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
]
keyword[if] keyword[not] identifier[getattr] ( identifi... | def reexport_tf_summary():
"""Re-export all symbols from the original tf.summary.
This function finds the original tf.summary V2 API and re-exports all the
symbols from it within this module as well, so that when this module is
patched into the TF API namespace as the new tf.summary, the effect is an
overl... |
def configure_error_handlers(app):
""" Configure application error handlers """
def render_error(error):
return (render_template('errors/%s.html' % error.code,
title=error_messages[error.code], code=error.code), error.code)
for (errcode, title) in error_messages.iteritems():
... | def function[configure_error_handlers, parameter[app]]:
constant[ Configure application error handlers ]
def function[render_error, parameter[error]]:
return[tuple[[<ast.Call object at 0x7da1b1616740>, <ast.Attribute object at 0x7da1b1616ec0>]]]
for taget[tuple[[<ast.Name object at 0x7da... | keyword[def] identifier[configure_error_handlers] ( identifier[app] ):
literal[string]
keyword[def] identifier[render_error] ( identifier[error] ):
keyword[return] ( identifier[render_template] ( literal[string] % identifier[error] . identifier[code] ,
identifier[title] = identifier[err... | def configure_error_handlers(app):
""" Configure application error handlers """
def render_error(error):
return (render_template('errors/%s.html' % error.code, title=error_messages[error.code], code=error.code), error.code)
for (errcode, title) in error_messages.iteritems():
app.errorhandle... |
def get_url(cls, url, uid, **kwargs):
"""
Construct the URL for talking to an individual resource.
http://myapi.com/api/resource/1
Args:
url: The url for this resource
uid: The unique identifier for an individual resource
kwargs: Additional keyword a... | def function[get_url, parameter[cls, url, uid]]:
constant[
Construct the URL for talking to an individual resource.
http://myapi.com/api/resource/1
Args:
url: The url for this resource
uid: The unique identifier for an individual resource
kwargs: Add... | keyword[def] identifier[get_url] ( identifier[cls] , identifier[url] , identifier[uid] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[uid] :
identifier[url] = literal[string] . identifier[format] ( identifier[url] , identifier[uid] )
keyword[else] :
... | def get_url(cls, url, uid, **kwargs):
"""
Construct the URL for talking to an individual resource.
http://myapi.com/api/resource/1
Args:
url: The url for this resource
uid: The unique identifier for an individual resource
kwargs: Additional keyword argue... |
def _posix_get_window_size():
"""Return (width, height) of console terminal on POSIX system.
(0, 0) on IOError, i.e. when no console is allocated.
"""
# see README.txt for reference information
# http://www.kernel.org/doc/man-pages/online/pages/man4/tty_ioctl.4.html
from fcntl import ioctl
... | def function[_posix_get_window_size, parameter[]]:
constant[Return (width, height) of console terminal on POSIX system.
(0, 0) on IOError, i.e. when no console is allocated.
]
from relative_module[fcntl] import module[ioctl]
from relative_module[termios] import module[TIOCGWINSZ]
from rel... | keyword[def] identifier[_posix_get_window_size] ():
literal[string]
keyword[from] identifier[fcntl] keyword[import] identifier[ioctl]
keyword[from] identifier[termios] keyword[import] identifier[TIOCGWINSZ]
keyword[from] identifier[array] keyword[import] identifier[array]
... | def _posix_get_window_size():
"""Return (width, height) of console terminal on POSIX system.
(0, 0) on IOError, i.e. when no console is allocated.
"""
# see README.txt for reference information
# http://www.kernel.org/doc/man-pages/online/pages/man4/tty_ioctl.4.html
from fcntl import ioctl
... |
def get_seconds(value, scale):
"""Convert time scale dict to seconds
Given a dictionary with keys for scale and value, convert
value into seconds based on scale.
"""
scales = {
'seconds': lambda x: x,
'minutes': lambda x: x * 60,
'hours': lambda x: x * 60 * 60,
'days': lambda x: x * 60 * 60 *... | def function[get_seconds, parameter[value, scale]]:
constant[Convert time scale dict to seconds
Given a dictionary with keys for scale and value, convert
value into seconds based on scale.
]
variable[scales] assign[=] dictionary[[<ast.Constant object at 0x7da20c76c850>, <ast.Constant object at 0x... | keyword[def] identifier[get_seconds] ( identifier[value] , identifier[scale] ):
literal[string]
identifier[scales] ={
literal[string] : keyword[lambda] identifier[x] : identifier[x] ,
literal[string] : keyword[lambda] identifier[x] : identifier[x] * literal[int] ,
literal[string] : keyword[lambda] ... | def get_seconds(value, scale):
"""Convert time scale dict to seconds
Given a dictionary with keys for scale and value, convert
value into seconds based on scale.
"""
scales = {'seconds': lambda x: x, 'minutes': lambda x: x * 60, 'hours': lambda x: x * 60 * 60, 'days': lambda x: x * 60 * 60 * 24, 'weeks':... |
def _check_samples_line(klass, arr):
"""Peform additional check on samples line"""
if len(arr) <= len(REQUIRE_NO_SAMPLE_HEADER):
if tuple(arr) != REQUIRE_NO_SAMPLE_HEADER:
raise exceptions.IncorrectVCFFormat(
"Sample header line indicates no sample but doe... | def function[_check_samples_line, parameter[klass, arr]]:
constant[Peform additional check on samples line]
if compare[call[name[len], parameter[name[arr]]] less_or_equal[<=] call[name[len], parameter[name[REQUIRE_NO_SAMPLE_HEADER]]]] begin[:]
if compare[call[name[tuple], parameter[name[... | keyword[def] identifier[_check_samples_line] ( identifier[klass] , identifier[arr] ):
literal[string]
keyword[if] identifier[len] ( identifier[arr] )<= identifier[len] ( identifier[REQUIRE_NO_SAMPLE_HEADER] ):
keyword[if] identifier[tuple] ( identifier[arr] )!= identifier[REQUIRE_NO_... | def _check_samples_line(klass, arr):
"""Peform additional check on samples line"""
if len(arr) <= len(REQUIRE_NO_SAMPLE_HEADER):
if tuple(arr) != REQUIRE_NO_SAMPLE_HEADER:
raise exceptions.IncorrectVCFFormat('Sample header line indicates no sample but does not equal required prefix {}'.forma... |
def main():
"""Main CLI application."""
parser = get_parser()
argcomplete.autocomplete(parser, always_complete_options=False)
args = parser.parse_args()
setup_logger(
level=args.log_level
)
try:
if args.config and \
args.command in \
('agg... | def function[main, parameter[]]:
constant[Main CLI application.]
variable[parser] assign[=] call[name[get_parser], parameter[]]
call[name[argcomplete].autocomplete, parameter[name[parser]]]
variable[args] assign[=] call[name[parser].parse_args, parameter[]]
call[name[setup_logger... | keyword[def] identifier[main] ():
literal[string]
identifier[parser] = identifier[get_parser] ()
identifier[argcomplete] . identifier[autocomplete] ( identifier[parser] , identifier[always_complete_options] = keyword[False] )
identifier[args] = identifier[parser] . identifier[parse_args] ()
... | def main():
"""Main CLI application."""
parser = get_parser()
argcomplete.autocomplete(parser, always_complete_options=False)
args = parser.parse_args()
setup_logger(level=args.log_level)
try:
if args.config and args.command in ('aggregate', 'show-closed-prs', 'show-all-prs'):
... |
def _get_hgroup(name, array):
'''Private function to check hostgroup'''
hostgroup = None
for temp in array.list_hgroups():
if temp['name'] == name:
hostgroup = temp
break
return hostgroup | def function[_get_hgroup, parameter[name, array]]:
constant[Private function to check hostgroup]
variable[hostgroup] assign[=] constant[None]
for taget[name[temp]] in starred[call[name[array].list_hgroups, parameter[]]] begin[:]
if compare[call[name[temp]][constant[name]] equal[=... | keyword[def] identifier[_get_hgroup] ( identifier[name] , identifier[array] ):
literal[string]
identifier[hostgroup] = keyword[None]
keyword[for] identifier[temp] keyword[in] identifier[array] . identifier[list_hgroups] ():
keyword[if] identifier[temp] [ literal[string] ]== identifier[na... | def _get_hgroup(name, array):
"""Private function to check hostgroup"""
hostgroup = None
for temp in array.list_hgroups():
if temp['name'] == name:
hostgroup = temp
break # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['temp']]
return hostgro... |
def get(self, entry):
"""
get the value from vault secret backend
"""
if self.apiVersion == 1:
path = self.secretsmount + '/' + entry
else:
path = self.secretsmount + '/data/' + entry
# note that the HTTP path contains v1 for both versions of the ... | def function[get, parameter[self, entry]]:
constant[
get the value from vault secret backend
]
if compare[name[self].apiVersion equal[==] constant[1]] begin[:]
variable[path] assign[=] binary_operation[binary_operation[name[self].secretsmount + constant[/]] + name[entry]]... | keyword[def] identifier[get] ( identifier[self] , identifier[entry] ):
literal[string]
keyword[if] identifier[self] . identifier[apiVersion] == literal[int] :
identifier[path] = identifier[self] . identifier[secretsmount] + literal[string] + identifier[entry]
keyword[else] :... | def get(self, entry):
"""
get the value from vault secret backend
"""
if self.apiVersion == 1:
path = self.secretsmount + '/' + entry # depends on [control=['if'], data=[]]
else:
path = self.secretsmount + '/data/' + entry
# note that the HTTP path contains v1 for both v... |
def allowed(self, url, agent):
'''Return true if the provided URL is allowed to agent.'''
return self.get(url).allowed(url, agent) | def function[allowed, parameter[self, url, agent]]:
constant[Return true if the provided URL is allowed to agent.]
return[call[call[name[self].get, parameter[name[url]]].allowed, parameter[name[url], name[agent]]]] | keyword[def] identifier[allowed] ( identifier[self] , identifier[url] , identifier[agent] ):
literal[string]
keyword[return] identifier[self] . identifier[get] ( identifier[url] ). identifier[allowed] ( identifier[url] , identifier[agent] ) | def allowed(self, url, agent):
"""Return true if the provided URL is allowed to agent."""
return self.get(url).allowed(url, agent) |
def to_string(mnemonic):
"""Return the string representation of the given mnemonic.
"""
strings = {
# Arithmetic Instructions
ReilMnemonic.ADD: "add",
ReilMnemonic.SUB: "sub",
ReilMnemonic.MUL: "mul",
ReilMnemonic.DIV: "div",
... | def function[to_string, parameter[mnemonic]]:
constant[Return the string representation of the given mnemonic.
]
variable[strings] assign[=] dictionary[[<ast.Attribute object at 0x7da18eb57400>, <ast.Attribute object at 0x7da18eb56a10>, <ast.Attribute object at 0x7da18eb54370>, <ast.Attribute ob... | keyword[def] identifier[to_string] ( identifier[mnemonic] ):
literal[string]
identifier[strings] ={
identifier[ReilMnemonic] . identifier[ADD] : literal[string] ,
identifier[ReilMnemonic] . identifier[SUB] : literal[string] ,
identifier[ReilMnemonic] . identifier... | def to_string(mnemonic):
"""Return the string representation of the given mnemonic.
"""
# Arithmetic Instructions
# Bitwise Instructions
# Data Transfer Instructions
# Conditional Instructions
# Other Instructions
# Extensions
strings = {ReilMnemonic.ADD: 'add', ReilMnemonic.SUB:... |
def reset_coords(self, names=None, drop=False, inplace=None):
"""Given names of coordinates, reset them to become variables
Parameters
----------
names : str or list of str, optional
Name(s) of non-index coordinates in this dataset to reset into
variables. By def... | def function[reset_coords, parameter[self, names, drop, inplace]]:
constant[Given names of coordinates, reset them to become variables
Parameters
----------
names : str or list of str, optional
Name(s) of non-index coordinates in this dataset to reset into
variab... | keyword[def] identifier[reset_coords] ( identifier[self] , identifier[names] = keyword[None] , identifier[drop] = keyword[False] , identifier[inplace] = keyword[None] ):
literal[string]
identifier[inplace] = identifier[_check_inplace] ( identifier[inplace] )
keyword[if] identifier[names] ... | def reset_coords(self, names=None, drop=False, inplace=None):
"""Given names of coordinates, reset them to become variables
Parameters
----------
names : str or list of str, optional
Name(s) of non-index coordinates in this dataset to reset into
variables. By default... |
def reconstruct_dict(dot_paths, values):
''' a method for reconstructing a dictionary from the values along dot paths '''
output_dict = {}
for i in range(len(dot_paths)):
if i + 1 <= len(values):
path_segments = segment_path(dot_paths[i])
current_nest = output_... | def function[reconstruct_dict, parameter[dot_paths, values]]:
constant[ a method for reconstructing a dictionary from the values along dot paths ]
variable[output_dict] assign[=] dictionary[[], []]
for taget[name[i]] in starred[call[name[range], parameter[call[name[len], parameter[name[dot_paths... | keyword[def] identifier[reconstruct_dict] ( identifier[dot_paths] , identifier[values] ):
literal[string]
identifier[output_dict] ={}
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[len] ( identifier[dot_paths] )):
keyword[if] identifier[i] + literal[int] <= ident... | def reconstruct_dict(dot_paths, values):
""" a method for reconstructing a dictionary from the values along dot paths """
output_dict = {}
for i in range(len(dot_paths)):
if i + 1 <= len(values):
path_segments = segment_path(dot_paths[i])
current_nest = output_dict
... |
def choose_form(self, number=None, xpath=None, name=None, **kwargs):
"""
Set the default form.
:param number: number of form (starting from zero)
:param id: value of "id" attribute
:param name: value of "name" attribute
:param xpath: XPath query
:raises: :class:`... | def function[choose_form, parameter[self, number, xpath, name]]:
constant[
Set the default form.
:param number: number of form (starting from zero)
:param id: value of "id" attribute
:param name: value of "name" attribute
:param xpath: XPath query
:raises: :class... | keyword[def] identifier[choose_form] ( identifier[self] , identifier[number] = keyword[None] , identifier[xpath] = keyword[None] , identifier[name] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[id_] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[None] )
... | def choose_form(self, number=None, xpath=None, name=None, **kwargs):
"""
Set the default form.
:param number: number of form (starting from zero)
:param id: value of "id" attribute
:param name: value of "name" attribute
:param xpath: XPath query
:raises: :class:`Data... |
def configure(self, name=None, rules=None, query=None, **options):
"""Configure the alert."""
self.name = name
if not name:
raise AssertionError("Alert's name should be defined and not empty.")
if not rules:
raise AssertionError("%s: Alert's rules is invalid" % n... | def function[configure, parameter[self, name, rules, query]]:
constant[Configure the alert.]
name[self].name assign[=] name[name]
if <ast.UnaryOp object at 0x7da1b0e67e80> begin[:]
<ast.Raise object at 0x7da1b0e64a60>
if <ast.UnaryOp object at 0x7da1b0e67b80> begin[:]
<as... | keyword[def] identifier[configure] ( identifier[self] , identifier[name] = keyword[None] , identifier[rules] = keyword[None] , identifier[query] = keyword[None] ,** identifier[options] ):
literal[string]
identifier[self] . identifier[name] = identifier[name]
keyword[if] keyword[not] ide... | def configure(self, name=None, rules=None, query=None, **options):
"""Configure the alert."""
self.name = name
if not name:
raise AssertionError("Alert's name should be defined and not empty.") # depends on [control=['if'], data=[]]
if not rules:
raise AssertionError("%s: Alert's rules ... |
def delete_attribute(self, name):
'''
Delete an attribute with a given *name* from the list of attributes.
'''
for idx, attr in enumerate(self.attributes):
attr_name, _ = attr
if attr_name == name:
del self.attributes[idx]
return | def function[delete_attribute, parameter[self, name]]:
constant[
Delete an attribute with a given *name* from the list of attributes.
]
for taget[tuple[[<ast.Name object at 0x7da1b0293bb0>, <ast.Name object at 0x7da1b0293790>]]] in starred[call[name[enumerate], parameter[name[self].attri... | keyword[def] identifier[delete_attribute] ( identifier[self] , identifier[name] ):
literal[string]
keyword[for] identifier[idx] , identifier[attr] keyword[in] identifier[enumerate] ( identifier[self] . identifier[attributes] ):
identifier[attr_name] , identifier[_] = identifier[attr... | def delete_attribute(self, name):
"""
Delete an attribute with a given *name* from the list of attributes.
"""
for (idx, attr) in enumerate(self.attributes):
(attr_name, _) = attr
if attr_name == name:
del self.attributes[idx]
return # depends on [control... |
def flag_to_list(flagval, flagtype):
"""Convert a string of comma-separated tf flags to a list of values."""
if flagtype == 'int':
return [int(_) for _ in flagval.split(',') if _]
elif flagtype == 'float':
return [float(_) for _ in flagval.split(',') if _]
elif flagtype == 'str':
... | def function[flag_to_list, parameter[flagval, flagtype]]:
constant[Convert a string of comma-separated tf flags to a list of values.]
if compare[name[flagtype] equal[==] constant[int]] begin[:]
return[<ast.ListComp object at 0x7da18f00c730>] | keyword[def] identifier[flag_to_list] ( identifier[flagval] , identifier[flagtype] ):
literal[string]
keyword[if] identifier[flagtype] == literal[string] :
keyword[return] [ identifier[int] ( identifier[_] ) keyword[for] identifier[_] keyword[in] identifier[flagval] . identifier[split] ( liter... | def flag_to_list(flagval, flagtype):
"""Convert a string of comma-separated tf flags to a list of values."""
if flagtype == 'int':
return [int(_) for _ in flagval.split(',') if _] # depends on [control=['if'], data=[]]
elif flagtype == 'float':
return [float(_) for _ in flagval.split(',') i... |
def _check_has_primary(sds):
"""Current topology type is ReplicaSetWithPrimary. Is primary still known?
Pass in a dict of ServerDescriptions.
Returns new topology type.
"""
for s in sds.values():
if s.server_type == SERVER_TYPE.RSPrimary:
return TOPOLOGY_TYPE.ReplicaSetWithPrim... | def function[_check_has_primary, parameter[sds]]:
constant[Current topology type is ReplicaSetWithPrimary. Is primary still known?
Pass in a dict of ServerDescriptions.
Returns new topology type.
]
for taget[name[s]] in starred[call[name[sds].values, parameter[]]] begin[:]
... | keyword[def] identifier[_check_has_primary] ( identifier[sds] ):
literal[string]
keyword[for] identifier[s] keyword[in] identifier[sds] . identifier[values] ():
keyword[if] identifier[s] . identifier[server_type] == identifier[SERVER_TYPE] . identifier[RSPrimary] :
keyword[return]... | def _check_has_primary(sds):
"""Current topology type is ReplicaSetWithPrimary. Is primary still known?
Pass in a dict of ServerDescriptions.
Returns new topology type.
"""
for s in sds.values():
if s.server_type == SERVER_TYPE.RSPrimary:
return TOPOLOGY_TYPE.ReplicaSetWithPrim... |
def remove_programmer(programmer_id):
"""remove programmer.
:param programmer_id: programmer id (e.g. 'avrisp')
:rtype: None
"""
log.debug('remove %s', programmer_id)
lines = programmers_txt().lines()
lines = filter(
lambda x: not x.strip().startswith(programmer_id + '.'), lines)
... | def function[remove_programmer, parameter[programmer_id]]:
constant[remove programmer.
:param programmer_id: programmer id (e.g. 'avrisp')
:rtype: None
]
call[name[log].debug, parameter[constant[remove %s], name[programmer_id]]]
variable[lines] assign[=] call[call[name[programmers_... | keyword[def] identifier[remove_programmer] ( identifier[programmer_id] ):
literal[string]
identifier[log] . identifier[debug] ( literal[string] , identifier[programmer_id] )
identifier[lines] = identifier[programmers_txt] (). identifier[lines] ()
identifier[lines] = identifier[filter] (
key... | def remove_programmer(programmer_id):
"""remove programmer.
:param programmer_id: programmer id (e.g. 'avrisp')
:rtype: None
"""
log.debug('remove %s', programmer_id)
lines = programmers_txt().lines()
lines = filter(lambda x: not x.strip().startswith(programmer_id + '.'), lines)
progra... |
def dump(ra, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the remote accounts as a list of dictionaries.
:param ra: Remote account to be dumped.
:type ra: `invenio_oauthclient.models.RemoteAccount [Invenio2.x]`
:returns: Remote accounts serialized to dictionary.
:rtype: dict
... | def function[dump, parameter[ra, from_date, with_json, latest_only]]:
constant[Dump the remote accounts as a list of dictionaries.
:param ra: Remote account to be dumped.
:type ra: `invenio_oauthclient.models.RemoteAccount [Invenio2.x]`
:returns: Remote accounts serialized to dictionary.
:rtype... | keyword[def] identifier[dump] ( identifier[ra] , identifier[from_date] , identifier[with_json] = keyword[True] , identifier[latest_only] = keyword[False] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[dict] ( identifier[id] = identifier[ra] . identifier[id] , identifier[user_id] = id... | def dump(ra, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the remote accounts as a list of dictionaries.
:param ra: Remote account to be dumped.
:type ra: `invenio_oauthclient.models.RemoteAccount [Invenio2.x]`
:returns: Remote accounts serialized to dictionary.
:rtype: dict
... |
def delete_snapshot(name, snap_name, runas=None, all=False):
'''
Delete a snapshot
.. note::
Deleting a snapshot from which other snapshots are dervied will not
delete the derived snapshots
:param str name:
Name/ID of VM whose snapshot will be deleted
:param str snap_name... | def function[delete_snapshot, parameter[name, snap_name, runas, all]]:
constant[
Delete a snapshot
.. note::
Deleting a snapshot from which other snapshots are dervied will not
delete the derived snapshots
:param str name:
Name/ID of VM whose snapshot will be deleted
... | keyword[def] identifier[delete_snapshot] ( identifier[name] , identifier[snap_name] , identifier[runas] = keyword[None] , identifier[all] = keyword[False] ):
literal[string]
identifier[strict] = keyword[not] identifier[all]
identifier[name] = identifier[salt] . identifier[utils] . identif... | def delete_snapshot(name, snap_name, runas=None, all=False):
"""
Delete a snapshot
.. note::
Deleting a snapshot from which other snapshots are dervied will not
delete the derived snapshots
:param str name:
Name/ID of VM whose snapshot will be deleted
:param str snap_name... |
def filter_from_options(key, options):
"""
:param key: Key str in options
:param options: Mapping object
:return:
New mapping object from 'options' in which the item with 'key' filtered
>>> filter_from_options('a', dict(a=1, b=2))
{'b': 2}
"""
return anyconfig.utils.filter_optio... | def function[filter_from_options, parameter[key, options]]:
constant[
:param key: Key str in options
:param options: Mapping object
:return:
New mapping object from 'options' in which the item with 'key' filtered
>>> filter_from_options('a', dict(a=1, b=2))
{'b': 2}
]
return... | keyword[def] identifier[filter_from_options] ( identifier[key] , identifier[options] ):
literal[string]
keyword[return] identifier[anyconfig] . identifier[utils] . identifier[filter_options] ([ identifier[k] keyword[for] identifier[k] keyword[in] identifier[options] . identifier[keys] ()
keyword[... | def filter_from_options(key, options):
"""
:param key: Key str in options
:param options: Mapping object
:return:
New mapping object from 'options' in which the item with 'key' filtered
>>> filter_from_options('a', dict(a=1, b=2))
{'b': 2}
"""
return anyconfig.utils.filter_optio... |
def _create_temp_requirements(self):
"""Create a temporary requirements.txt.
This allows testing again a git branch instead of pulling from pypi.
"""
self.use_temp_requirements_file = True
# Replace tcex version with develop branch of tcex
with open(self.requirements_fil... | def function[_create_temp_requirements, parameter[self]]:
constant[Create a temporary requirements.txt.
This allows testing again a git branch instead of pulling from pypi.
]
name[self].use_temp_requirements_file assign[=] constant[True]
with call[name[open], parameter[name[self... | keyword[def] identifier[_create_temp_requirements] ( identifier[self] ):
literal[string]
identifier[self] . identifier[use_temp_requirements_file] = keyword[True]
keyword[with] identifier[open] ( identifier[self] . identifier[requirements_file] , literal[string] ) keyword[as] i... | def _create_temp_requirements(self):
"""Create a temporary requirements.txt.
This allows testing again a git branch instead of pulling from pypi.
"""
self.use_temp_requirements_file = True
# Replace tcex version with develop branch of tcex
with open(self.requirements_file, 'r') as fh:
... |
def generate_data_type(self, data_type):
"""Output a data type definition (a struct or union)."""
if isinstance(data_type, Struct):
# Output a struct definition.
self.emit('')
self.emit('struct %s' % data_type.name)
with self.indent():
if d... | def function[generate_data_type, parameter[self, data_type]]:
constant[Output a data type definition (a struct or union).]
if call[name[isinstance], parameter[name[data_type], name[Struct]]] begin[:]
call[name[self].emit, parameter[constant[]]]
call[name[self].emit, param... | keyword[def] identifier[generate_data_type] ( identifier[self] , identifier[data_type] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[data_type] , identifier[Struct] ):
identifier[self] . identifier[emit] ( literal[string] )
identifier[self] .... | def generate_data_type(self, data_type):
"""Output a data type definition (a struct or union)."""
if isinstance(data_type, Struct):
# Output a struct definition.
self.emit('')
self.emit('struct %s' % data_type.name)
with self.indent():
if data_type.doc is not None:
... |
def _add_return_site(self, return_site):
"""
Registers a basic block as a site for control flow to return from this function.
:param CodeNode return_site: The block node that ends with a return.
"""
self._register_nodes(True, return_site)
self._ret_sites.add(return_... | def function[_add_return_site, parameter[self, return_site]]:
constant[
Registers a basic block as a site for control flow to return from this function.
:param CodeNode return_site: The block node that ends with a return.
]
call[name[self]._register_nodes, parameter[constant... | keyword[def] identifier[_add_return_site] ( identifier[self] , identifier[return_site] ):
literal[string]
identifier[self] . identifier[_register_nodes] ( keyword[True] , identifier[return_site] )
identifier[self] . identifier[_ret_sites] . identifier[add] ( identifier[return_site] )
... | def _add_return_site(self, return_site):
"""
Registers a basic block as a site for control flow to return from this function.
:param CodeNode return_site: The block node that ends with a return.
"""
self._register_nodes(True, return_site)
self._ret_sites.add(return_site)
# A... |
def viewport_changed(self, screen_id, x, y, width, height):
"""Signals that framebuffer window viewport has changed.
in screen_id of type int
Monitor to take the screenshot from.
in x of type int
Framebuffer x offset.
in y of type int
Framebuffer y ... | def function[viewport_changed, parameter[self, screen_id, x, y, width, height]]:
constant[Signals that framebuffer window viewport has changed.
in screen_id of type int
Monitor to take the screenshot from.
in x of type int
Framebuffer x offset.
in y of type int... | keyword[def] identifier[viewport_changed] ( identifier[self] , identifier[screen_id] , identifier[x] , identifier[y] , identifier[width] , identifier[height] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[screen_id] , identifier[baseinteger] ):
keywor... | def viewport_changed(self, screen_id, x, y, width, height):
"""Signals that framebuffer window viewport has changed.
in screen_id of type int
Monitor to take the screenshot from.
in x of type int
Framebuffer x offset.
in y of type int
Framebuffer y offs... |
def live_source_load(self, source):
"""
Send new source code to the bot
:param source:
:param good_cb: callback called if code was good
:param bad_cb: callback called if code was bad (will get contents of exception)
:return:
"""
source = source.rstrip('\n... | def function[live_source_load, parameter[self, source]]:
constant[
Send new source code to the bot
:param source:
:param good_cb: callback called if code was good
:param bad_cb: callback called if code was bad (will get contents of exception)
:return:
]
v... | keyword[def] identifier[live_source_load] ( identifier[self] , identifier[source] ):
literal[string]
identifier[source] = identifier[source] . identifier[rstrip] ( literal[string] )
keyword[if] identifier[source] != identifier[self] . identifier[source] :
identifier[self] . i... | def live_source_load(self, source):
"""
Send new source code to the bot
:param source:
:param good_cb: callback called if code was good
:param bad_cb: callback called if code was bad (will get contents of exception)
:return:
"""
source = source.rstrip('\n')
i... |
def standard_sc_expr_str(sc):
"""
Standard symbol/choice printing function. Uses plain Kconfig syntax, and
displays choices as <choice> (or <choice NAME>, for named choices).
See expr_str().
"""
if sc.__class__ is Symbol:
return '"{}"'.format(escape(sc.name)) if sc.is_constant else sc.n... | def function[standard_sc_expr_str, parameter[sc]]:
constant[
Standard symbol/choice printing function. Uses plain Kconfig syntax, and
displays choices as <choice> (or <choice NAME>, for named choices).
See expr_str().
]
if compare[name[sc].__class__ is name[Symbol]] begin[:]
ret... | keyword[def] identifier[standard_sc_expr_str] ( identifier[sc] ):
literal[string]
keyword[if] identifier[sc] . identifier[__class__] keyword[is] identifier[Symbol] :
keyword[return] literal[string] . identifier[format] ( identifier[escape] ( identifier[sc] . identifier[name] )) keyword[if] id... | def standard_sc_expr_str(sc):
"""
Standard symbol/choice printing function. Uses plain Kconfig syntax, and
displays choices as <choice> (or <choice NAME>, for named choices).
See expr_str().
"""
if sc.__class__ is Symbol:
return '"{}"'.format(escape(sc.name)) if sc.is_constant else sc.n... |
def get_name( self, name, lastblock=None, include_expired=False, include_history=True ):
"""
Given a name, return the latest version and history of
the metadata gleaned from the blockchain.
Name must be fully-qualified (i.e. name.ns_id)
Return None if no such name is currently re... | def function[get_name, parameter[self, name, lastblock, include_expired, include_history]]:
constant[
Given a name, return the latest version and history of
the metadata gleaned from the blockchain.
Name must be fully-qualified (i.e. name.ns_id)
Return None if no such name is cur... | keyword[def] identifier[get_name] ( identifier[self] , identifier[name] , identifier[lastblock] = keyword[None] , identifier[include_expired] = keyword[False] , identifier[include_history] = keyword[True] ):
literal[string]
keyword[if] identifier[lastblock] keyword[is] keyword[None] :
... | def get_name(self, name, lastblock=None, include_expired=False, include_history=True):
"""
Given a name, return the latest version and history of
the metadata gleaned from the blockchain.
Name must be fully-qualified (i.e. name.ns_id)
Return None if no such name is currently register... |
def is_correlated(self, threshold=0):
"""
Compare with a threshold to determine whether two timeseries correlate to each other.
:return: a CorrelationResult object if two time series correlate otherwise false.
"""
return self.correlation_result if self.correlation_result.coeffici... | def function[is_correlated, parameter[self, threshold]]:
constant[
Compare with a threshold to determine whether two timeseries correlate to each other.
:return: a CorrelationResult object if two time series correlate otherwise false.
]
return[<ast.IfExp object at 0x7da2054a6170>] | keyword[def] identifier[is_correlated] ( identifier[self] , identifier[threshold] = literal[int] ):
literal[string]
keyword[return] identifier[self] . identifier[correlation_result] keyword[if] identifier[self] . identifier[correlation_result] . identifier[coefficient] >= identifier[threshold] ... | def is_correlated(self, threshold=0):
"""
Compare with a threshold to determine whether two timeseries correlate to each other.
:return: a CorrelationResult object if two time series correlate otherwise false.
"""
return self.correlation_result if self.correlation_result.coefficient >= t... |
def sf(f, dirpath, jottapath):
"""Create and return a SyncFile tuple from filename.
localpath will be a byte string with utf8 code points
jottapath will be a unicode string"""
log.debug('Create SyncFile from %s', repr(f))
log.debug('Got encoded filename %r, joining with dirpath %r',... | def function[sf, parameter[f, dirpath, jottapath]]:
constant[Create and return a SyncFile tuple from filename.
localpath will be a byte string with utf8 code points
jottapath will be a unicode string]
call[name[log].debug, parameter[constant[Create SyncFile from %s], call[name[r... | keyword[def] identifier[sf] ( identifier[f] , identifier[dirpath] , identifier[jottapath] ):
literal[string]
identifier[log] . identifier[debug] ( literal[string] , identifier[repr] ( identifier[f] ))
identifier[log] . identifier[debug] ( literal[string] , identifier[_encode_filename_to_filesystem] ( ... | def sf(f, dirpath, jottapath):
"""Create and return a SyncFile tuple from filename.
localpath will be a byte string with utf8 code points
jottapath will be a unicode string"""
log.debug('Create SyncFile from %s', repr(f))
log.debug('Got encoded filename %r, joining with dirpath %r',... |
def K(self, X, X2, target):
"""Return covariance between X and X2."""
self._K_computations(X, X2)
target += self.variance*self._K_dvar | def function[K, parameter[self, X, X2, target]]:
constant[Return covariance between X and X2.]
call[name[self]._K_computations, parameter[name[X], name[X2]]]
<ast.AugAssign object at 0x7da1b1c2f460> | keyword[def] identifier[K] ( identifier[self] , identifier[X] , identifier[X2] , identifier[target] ):
literal[string]
identifier[self] . identifier[_K_computations] ( identifier[X] , identifier[X2] )
identifier[target] += identifier[self] . identifier[variance] * identifier[self] . identi... | def K(self, X, X2, target):
"""Return covariance between X and X2."""
self._K_computations(X, X2)
target += self.variance * self._K_dvar |
def update_or_create(self, model, **kwargs):
'''Update or create a new instance of ``model``.
This method can raise an exception if the ``kwargs`` dictionary
contains field data that does not validate.
:param model: a :class:`StdModel`
:param kwargs: dictionary of parame... | def function[update_or_create, parameter[self, model]]:
constant[Update or create a new instance of ``model``.
This method can raise an exception if the ``kwargs`` dictionary
contains field data that does not validate.
:param model: a :class:`StdModel`
:param kwargs: dictionary... | keyword[def] identifier[update_or_create] ( identifier[self] , identifier[model] ,** identifier[kwargs] ):
literal[string]
identifier[backend] = identifier[self] . identifier[model] ( identifier[model] ). identifier[backend]
keyword[return] identifier[backend] . identifier[execute] ( ... | def update_or_create(self, model, **kwargs):
"""Update or create a new instance of ``model``.
This method can raise an exception if the ``kwargs`` dictionary
contains field data that does not validate.
:param model: a :class:`StdModel`
:param kwargs: dictionary of parameters.
... |
def update_http_method_params(self):
"""
Update HTTP url parameters based on msm_id and query filters if
there are any.
"""
url_params = {}
if self.start:
url_params.update(
{"start": int(calendar.timegm(self.start.timetuple()))}
)... | def function[update_http_method_params, parameter[self]]:
constant[
Update HTTP url parameters based on msm_id and query filters if
there are any.
]
variable[url_params] assign[=] dictionary[[], []]
if name[self].start begin[:]
call[name[url_params].update... | keyword[def] identifier[update_http_method_params] ( identifier[self] ):
literal[string]
identifier[url_params] ={}
keyword[if] identifier[self] . identifier[start] :
identifier[url_params] . identifier[update] (
{ literal[string] : identifier[int] ( identifier[c... | def update_http_method_params(self):
"""
Update HTTP url parameters based on msm_id and query filters if
there are any.
"""
url_params = {}
if self.start:
url_params.update({'start': int(calendar.timegm(self.start.timetuple()))}) # depends on [control=['if'], data=[]]
if... |
def shell2json(s):
"""Convert shell syntax to json."""
replace = {
r'BinData\(.+?\)': '1',
r'(new )?Date\(.+?\)': '1',
r'Timestamp\(.+?\)': '1',
r'ObjectId\(.+?\)': '1',
r'DBRef\(.+?\)': '1',
r'undefined': '1',
r'MinKey': '1',
r'MaxKey': '1',
... | def function[shell2json, parameter[s]]:
constant[Convert shell syntax to json.]
variable[replace] assign[=] dictionary[[<ast.Constant object at 0x7da1b175efb0>, <ast.Constant object at 0x7da1b175f190>, <ast.Constant object at 0x7da1b175d720>, <ast.Constant object at 0x7da1b175e260>, <ast.Constant object... | keyword[def] identifier[shell2json] ( identifier[s] ):
literal[string]
identifier[replace] ={
literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[string] : literal[string] ,
lit... | def shell2json(s):
"""Convert shell syntax to json."""
replace = {'BinData\\(.+?\\)': '1', '(new )?Date\\(.+?\\)': '1', 'Timestamp\\(.+?\\)': '1', 'ObjectId\\(.+?\\)': '1', 'DBRef\\(.+?\\)': '1', 'undefined': '1', 'MinKey': '1', 'MaxKey': '1', 'NumberLong\\(.+?\\)': '1', '/.+?/\\w*': '1'}
for (key, value) i... |
def reverse_axis(self, axis_to_reverse):
"""Reverse an axis in all figure plots.
This will reverse the tick marks on an axis for each plot in the figure.
It can be overridden in SinglePlot class.
Args:
axis_to_reverse (str): Axis to reverse. Supports `x` and `y`.
R... | def function[reverse_axis, parameter[self, axis_to_reverse]]:
constant[Reverse an axis in all figure plots.
This will reverse the tick marks on an axis for each plot in the figure.
It can be overridden in SinglePlot class.
Args:
axis_to_reverse (str): Axis to reverse. Suppo... | keyword[def] identifier[reverse_axis] ( identifier[self] , identifier[axis_to_reverse] ):
literal[string]
keyword[if] identifier[axis_to_reverse] . identifier[lower] ()== literal[string] :
identifier[self] . identifier[general] . identifier[reverse_x_axis] = keyword[True]
ke... | def reverse_axis(self, axis_to_reverse):
"""Reverse an axis in all figure plots.
This will reverse the tick marks on an axis for each plot in the figure.
It can be overridden in SinglePlot class.
Args:
axis_to_reverse (str): Axis to reverse. Supports `x` and `y`.
Raise... |
def today_as_utc_datetime():
"""Datetime/Date comparisons aren't great, and someone might configure TODAY, to be a date."""
now = today()
if not isinstance(now, datetime) and isinstance(now, date):
now = datetime.combine(now, datetime.min.time())
now = now.replace(tzinfo=tz.gettz('UTC'))
... | def function[today_as_utc_datetime, parameter[]]:
constant[Datetime/Date comparisons aren't great, and someone might configure TODAY, to be a date.]
variable[now] assign[=] call[name[today], parameter[]]
if <ast.BoolOp object at 0x7da1b0bf35b0> begin[:]
variable[now] assign[=] ca... | keyword[def] identifier[today_as_utc_datetime] ():
literal[string]
identifier[now] = identifier[today] ()
keyword[if] keyword[not] identifier[isinstance] ( identifier[now] , identifier[datetime] ) keyword[and] identifier[isinstance] ( identifier[now] , identifier[date] ):
identifier[now] =... | def today_as_utc_datetime():
"""Datetime/Date comparisons aren't great, and someone might configure TODAY, to be a date."""
now = today()
if not isinstance(now, datetime) and isinstance(now, date):
now = datetime.combine(now, datetime.min.time())
now = now.replace(tzinfo=tz.gettz('UTC')) # ... |
def translate(self, package, into=None):
"""From a binary package, translate to a local binary distribution."""
if not package.local:
raise ValueError('BinaryTranslator cannot translate remote packages.')
if not isinstance(package, self._package_type):
return None
if not package.compatible(s... | def function[translate, parameter[self, package, into]]:
constant[From a binary package, translate to a local binary distribution.]
if <ast.UnaryOp object at 0x7da204620370> begin[:]
<ast.Raise object at 0x7da204620a30>
if <ast.UnaryOp object at 0x7da204622230> begin[:]
return[co... | keyword[def] identifier[translate] ( identifier[self] , identifier[package] , identifier[into] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[package] . identifier[local] :
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[if] keyword[not] identifier... | def translate(self, package, into=None):
"""From a binary package, translate to a local binary distribution."""
if not package.local:
raise ValueError('BinaryTranslator cannot translate remote packages.') # depends on [control=['if'], data=[]]
if not isinstance(package, self._package_type):
... |
def stop(self, timeout=None):
"""
Stops the task thread. Synchronous!
"""
with self._lock:
if self._thread:
self._queue.put_nowait(self._terminator)
self._thread.join(timeout=timeout)
self._thread = None
self._th... | def function[stop, parameter[self, timeout]]:
constant[
Stops the task thread. Synchronous!
]
with name[self]._lock begin[:]
if name[self]._thread begin[:]
call[name[self]._queue.put_nowait, parameter[name[self]._terminator]]
... | keyword[def] identifier[stop] ( identifier[self] , identifier[timeout] = keyword[None] ):
literal[string]
keyword[with] identifier[self] . identifier[_lock] :
keyword[if] identifier[self] . identifier[_thread] :
identifier[self] . identifier[_queue] . identifier[put_... | def stop(self, timeout=None):
"""
Stops the task thread. Synchronous!
"""
with self._lock:
if self._thread:
self._queue.put_nowait(self._terminator)
self._thread.join(timeout=timeout)
self._thread = None
self._thread_for_pid = None # depen... |
def snake_to_camel(value):
"""
Converts a snake_case_string to a camelCaseString.
>>> snake_to_camel("foo_bar_baz")
'fooBarBaz'
"""
camel = "".join(word.title() for word in value.split("_"))
return value[:1].lower() + camel[1:] | def function[snake_to_camel, parameter[value]]:
constant[
Converts a snake_case_string to a camelCaseString.
>>> snake_to_camel("foo_bar_baz")
'fooBarBaz'
]
variable[camel] assign[=] call[constant[].join, parameter[<ast.GeneratorExp object at 0x7da204622080>]]
return[binary_operatio... | keyword[def] identifier[snake_to_camel] ( identifier[value] ):
literal[string]
identifier[camel] = literal[string] . identifier[join] ( identifier[word] . identifier[title] () keyword[for] identifier[word] keyword[in] identifier[value] . identifier[split] ( literal[string] ))
keyword[return] ident... | def snake_to_camel(value):
"""
Converts a snake_case_string to a camelCaseString.
>>> snake_to_camel("foo_bar_baz")
'fooBarBaz'
"""
camel = ''.join((word.title() for word in value.split('_')))
return value[:1].lower() + camel[1:] |
def _sampleLocationOnSide(self):
"""
Helper method to sample from the lateral surface of a cylinder.
"""
z = random.uniform(-1, 1) * self.height / 2.
sampledAngle = 2 * random.random() * pi
x, y = self.radius * cos(sampledAngle), self.radius * sin(sampledAngle)
return [x, y, z] | def function[_sampleLocationOnSide, parameter[self]]:
constant[
Helper method to sample from the lateral surface of a cylinder.
]
variable[z] assign[=] binary_operation[binary_operation[call[name[random].uniform, parameter[<ast.UnaryOp object at 0x7da1b0831d20>, constant[1]]] * name[self].height... | keyword[def] identifier[_sampleLocationOnSide] ( identifier[self] ):
literal[string]
identifier[z] = identifier[random] . identifier[uniform] (- literal[int] , literal[int] )* identifier[self] . identifier[height] / literal[int]
identifier[sampledAngle] = literal[int] * identifier[random] . identifie... | def _sampleLocationOnSide(self):
"""
Helper method to sample from the lateral surface of a cylinder.
"""
z = random.uniform(-1, 1) * self.height / 2.0
sampledAngle = 2 * random.random() * pi
(x, y) = (self.radius * cos(sampledAngle), self.radius * sin(sampledAngle))
return [x, y, z] |
def build_register_credit_card_parameters(client_ref: str) -> PaymentParameters:
"""
Builds the parameters needed to present the user with a datatrans form to register a credit card.
Contrary to a payment form, datatrans will not show an amount.
:param client_ref: A unique reference for this alias capt... | def function[build_register_credit_card_parameters, parameter[client_ref]]:
constant[
Builds the parameters needed to present the user with a datatrans form to register a credit card.
Contrary to a payment form, datatrans will not show an amount.
:param client_ref: A unique reference for this alias... | keyword[def] identifier[build_register_credit_card_parameters] ( identifier[client_ref] : identifier[str] )-> identifier[PaymentParameters] :
literal[string]
identifier[amount] = literal[int]
identifier[currency] = literal[string]
identifier[merchant_id] = identifier[web_merchant_id]
ide... | def build_register_credit_card_parameters(client_ref: str) -> PaymentParameters:
"""
Builds the parameters needed to present the user with a datatrans form to register a credit card.
Contrary to a payment form, datatrans will not show an amount.
:param client_ref: A unique reference for this alias capt... |
def align_two_alignments(aln1, aln2, moltype, params=None):
"""Returns an Alignment object from two existing Alignments.
aln1, aln2: cogent.core.alignment.Alignment objects, or data that can be
used to build them.
- Mafft profile alignment only works with aligned sequences. Alignment
object... | def function[align_two_alignments, parameter[aln1, aln2, moltype, params]]:
constant[Returns an Alignment object from two existing Alignments.
aln1, aln2: cogent.core.alignment.Alignment objects, or data that can be
used to build them.
- Mafft profile alignment only works with aligned sequences... | keyword[def] identifier[align_two_alignments] ( identifier[aln1] , identifier[aln2] , identifier[moltype] , identifier[params] = keyword[None] ):
literal[string]
identifier[aln1] = identifier[Alignment] ( identifier[aln1] , identifier[MolType] = identifier[moltype] )
identifier[aln1_int_map]... | def align_two_alignments(aln1, aln2, moltype, params=None):
"""Returns an Alignment object from two existing Alignments.
aln1, aln2: cogent.core.alignment.Alignment objects, or data that can be
used to build them.
- Mafft profile alignment only works with aligned sequences. Alignment
object... |
def apply_statusbar_settings(self):
"""Update status bar widgets settings"""
show_status_bar = CONF.get('main', 'show_status_bar')
self.statusBar().setVisible(show_status_bar)
if show_status_bar:
for widget, name in ((self.mem_status, 'memory_usage'),
... | def function[apply_statusbar_settings, parameter[self]]:
constant[Update status bar widgets settings]
variable[show_status_bar] assign[=] call[name[CONF].get, parameter[constant[main], constant[show_status_bar]]]
call[call[name[self].statusBar, parameter[]].setVisible, parameter[name[show_status... | keyword[def] identifier[apply_statusbar_settings] ( identifier[self] ):
literal[string]
identifier[show_status_bar] = identifier[CONF] . identifier[get] ( literal[string] , literal[string] )
identifier[self] . identifier[statusBar] (). identifier[setVisible] ( identifier[show_status_bar... | def apply_statusbar_settings(self):
"""Update status bar widgets settings"""
show_status_bar = CONF.get('main', 'show_status_bar')
self.statusBar().setVisible(show_status_bar)
if show_status_bar:
for (widget, name) in ((self.mem_status, 'memory_usage'), (self.cpu_status, 'cpu_usage')):
... |
def group_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a replication group exists.
CLI example::
salt myminion boto_elasticache.group_exists myelasticache
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
conn... | def function[group_exists, parameter[name, region, key, keyid, profile]]:
constant[
Check to see if a replication group exists.
CLI example::
salt myminion boto_elasticache.group_exists myelasticache
]
variable[conn] assign[=] call[name[_get_conn], parameter[]]
<ast.Try object ... | keyword[def] identifier[group_exists] ( identifier[name] , identifier[region] = keyword[None] , identifier[key] = keyword[None] , identifier[keyid] = keyword[None] , identifier[profile] = keyword[None] ):
literal[string]
identifier[conn] = identifier[_get_conn] ( identifier[region] = identifier[region] , i... | def group_exists(name, region=None, key=None, keyid=None, profile=None):
"""
Check to see if a replication group exists.
CLI example::
salt myminion boto_elasticache.group_exists myelasticache
"""
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
conn.... |
def releasers(cls):
"""
Returns all of the supported releasers.
"""
return [
HookReleaser,
VersionFileReleaser,
PythonReleaser,
CocoaPodsReleaser,
NPMReleaser,
CReleaser,
ChangelogReleaser,
G... | def function[releasers, parameter[cls]]:
constant[
Returns all of the supported releasers.
]
return[list[[<ast.Name object at 0x7da20c6c6230>, <ast.Name object at 0x7da20c6c4dc0>, <ast.Name object at 0x7da20c6c7490>, <ast.Name object at 0x7da20c6c6cb0>, <ast.Name object at 0x7da20c6c7eb0>, <... | keyword[def] identifier[releasers] ( identifier[cls] ):
literal[string]
keyword[return] [
identifier[HookReleaser] ,
identifier[VersionFileReleaser] ,
identifier[PythonReleaser] ,
identifier[CocoaPodsReleaser] ,
identifier[NPMReleaser] ,
identi... | def releasers(cls):
"""
Returns all of the supported releasers.
"""
return [HookReleaser, VersionFileReleaser, PythonReleaser, CocoaPodsReleaser, NPMReleaser, CReleaser, ChangelogReleaser, GitHubReleaser, GitReleaser] |
def generate_orders(events, sell_delay=5, sep=','):
"""Generate CSV orders based on events indicated in a DataFrame
Arguments:
events (pandas.DataFrame): Table of NaNs or 1's, one column for each symbol.
1 indicates a BUY event. -1 a SELL event. nan or 0 is a nonevent.
sell_delay (float): N... | def function[generate_orders, parameter[events, sell_delay, sep]]:
constant[Generate CSV orders based on events indicated in a DataFrame
Arguments:
events (pandas.DataFrame): Table of NaNs or 1's, one column for each symbol.
1 indicates a BUY event. -1 a SELL event. nan or 0 is a nonevent.
... | keyword[def] identifier[generate_orders] ( identifier[events] , identifier[sell_delay] = literal[int] , identifier[sep] = literal[string] ):
literal[string]
identifier[sell_delay] = identifier[float] ( identifier[unicode] ( identifier[sell_delay] )) keyword[or] literal[int]
keyword[for] identifier[... | def generate_orders(events, sell_delay=5, sep=','):
"""Generate CSV orders based on events indicated in a DataFrame
Arguments:
events (pandas.DataFrame): Table of NaNs or 1's, one column for each symbol.
1 indicates a BUY event. -1 a SELL event. nan or 0 is a nonevent.
sell_delay (float): N... |
def gps_input_encode(self, time_usec, gps_id, ignore_flags, time_week_ms, time_week, fix_type, lat, lon, alt, hdop, vdop, vn, ve, vd, speed_accuracy, horiz_accuracy, vert_accuracy, satellites_visible):
'''
GPS sensor input message. This is a raw sensor value sent by the GPS.
... | def function[gps_input_encode, parameter[self, time_usec, gps_id, ignore_flags, time_week_ms, time_week, fix_type, lat, lon, alt, hdop, vdop, vn, ve, vd, speed_accuracy, horiz_accuracy, vert_accuracy, satellites_visible]]:
constant[
GPS sensor input message. This is a raw sensor value sent by t... | keyword[def] identifier[gps_input_encode] ( identifier[self] , identifier[time_usec] , identifier[gps_id] , identifier[ignore_flags] , identifier[time_week_ms] , identifier[time_week] , identifier[fix_type] , identifier[lat] , identifier[lon] , identifier[alt] , identifier[hdop] , identifier[vdop] , identifier[vn] , ... | def gps_input_encode(self, time_usec, gps_id, ignore_flags, time_week_ms, time_week, fix_type, lat, lon, alt, hdop, vdop, vn, ve, vd, speed_accuracy, horiz_accuracy, vert_accuracy, satellites_visible):
"""
GPS sensor input message. This is a raw sensor value sent by the GPS.
This is... |
def ilx_conv(graph, prefix, ilx_start):
""" convert a set of temporary identifiers to ilx and modify the graph in place """
to_sub = set()
for subject in graph.subjects(rdflib.RDF.type, rdflib.OWL.Class):
if PREFIXES[prefix] in subject:
to_sub.add(subject)
ilx_base = 'ilx_{:0>7}'
... | def function[ilx_conv, parameter[graph, prefix, ilx_start]]:
constant[ convert a set of temporary identifiers to ilx and modify the graph in place ]
variable[to_sub] assign[=] call[name[set], parameter[]]
for taget[name[subject]] in starred[call[name[graph].subjects, parameter[name[rdflib].RDF.t... | keyword[def] identifier[ilx_conv] ( identifier[graph] , identifier[prefix] , identifier[ilx_start] ):
literal[string]
identifier[to_sub] = identifier[set] ()
keyword[for] identifier[subject] keyword[in] identifier[graph] . identifier[subjects] ( identifier[rdflib] . identifier[RDF] . identifier[typ... | def ilx_conv(graph, prefix, ilx_start):
""" convert a set of temporary identifiers to ilx and modify the graph in place """
to_sub = set()
for subject in graph.subjects(rdflib.RDF.type, rdflib.OWL.Class):
if PREFIXES[prefix] in subject:
to_sub.add(subject) # depends on [control=['if'], ... |
def _get_input_data(self, var, start_date, end_date):
"""Get the data for a single variable over the desired date range."""
logging.info(self._print_verbose("Getting input data:", var))
if isinstance(var, (float, int)):
return var
else:
cond_pfull = ((not hasattr... | def function[_get_input_data, parameter[self, var, start_date, end_date]]:
constant[Get the data for a single variable over the desired date range.]
call[name[logging].info, parameter[call[name[self]._print_verbose, parameter[constant[Getting input data:], name[var]]]]]
if call[name[isinstance],... | keyword[def] identifier[_get_input_data] ( identifier[self] , identifier[var] , identifier[start_date] , identifier[end_date] ):
literal[string]
identifier[logging] . identifier[info] ( identifier[self] . identifier[_print_verbose] ( literal[string] , identifier[var] ))
keyword[if] ident... | def _get_input_data(self, var, start_date, end_date):
"""Get the data for a single variable over the desired date range."""
logging.info(self._print_verbose('Getting input data:', var))
if isinstance(var, (float, int)):
return var # depends on [control=['if'], data=[]]
else:
cond_pfull ... |
def _head(self, client_kwargs):
"""
Returns object HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header.
"""
with _handle_client_exception():
# Object
if 'obj' in client_kwargs:
... | def function[_head, parameter[self, client_kwargs]]:
constant[
Returns object HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header.
]
with call[name[_handle_client_exception], parameter[]] begin[:]
... | keyword[def] identifier[_head] ( identifier[self] , identifier[client_kwargs] ):
literal[string]
keyword[with] identifier[_handle_client_exception] ():
keyword[if] literal[string] keyword[in] identifier[client_kwargs] :
keyword[return] identifier[self] . ... | def _head(self, client_kwargs):
"""
Returns object HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header.
"""
with _handle_client_exception():
# Object
if 'obj' in client_kwargs:
return self.cli... |
def validateLogicalInterfaceConfiguration(self, logicalInterfaceId):
"""
Validate the logical interface configuration.
Parameters:
- logicalInterfaceId (string)
Throws APIException on failure.
"""
req = ApiClient.oneLogicalInterfaceUrl % (self.host, "/draft", ... | def function[validateLogicalInterfaceConfiguration, parameter[self, logicalInterfaceId]]:
constant[
Validate the logical interface configuration.
Parameters:
- logicalInterfaceId (string)
Throws APIException on failure.
]
variable[req] assign[=] binary_operati... | keyword[def] identifier[validateLogicalInterfaceConfiguration] ( identifier[self] , identifier[logicalInterfaceId] ):
literal[string]
identifier[req] = identifier[ApiClient] . identifier[oneLogicalInterfaceUrl] %( identifier[self] . identifier[host] , literal[string] , identifier[logicalInterfaceId... | def validateLogicalInterfaceConfiguration(self, logicalInterfaceId):
"""
Validate the logical interface configuration.
Parameters:
- logicalInterfaceId (string)
Throws APIException on failure.
"""
req = ApiClient.oneLogicalInterfaceUrl % (self.host, '/draft', logicalI... |
def are_in(items, collection):
"""Return True for each item in the collection
:param items: a sub-collection
:param collection: a collection
:returns: a list of booleans
>>> are_in(['Terry', 'James'], ['Terry', 'John', 'Eric'])
[True, False]
"""
if not isinstance(items, (list, tuple))... | def function[are_in, parameter[items, collection]]:
constant[Return True for each item in the collection
:param items: a sub-collection
:param collection: a collection
:returns: a list of booleans
>>> are_in(['Terry', 'James'], ['Terry', 'John', 'Eric'])
[True, False]
]
if <as... | keyword[def] identifier[are_in] ( identifier[items] , identifier[collection] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[items] ,( identifier[list] , identifier[tuple] )):
identifier[items] =( identifier[items] ,)
keyword[return] identifier[map] ( keywor... | def are_in(items, collection):
"""Return True for each item in the collection
:param items: a sub-collection
:param collection: a collection
:returns: a list of booleans
>>> are_in(['Terry', 'James'], ['Terry', 'John', 'Eric'])
[True, False]
"""
if not isinstance(items, (list, tuple))... |
def custom_add_user_view(request):
''' The page to add a new user. '''
page_name = "Admin - Add User"
add_user_form = AddUserForm(request.POST or None, initial={
'status': UserProfile.RESIDENT,
})
if add_user_form.is_valid():
add_user_form.save()
message = MESSAGES['USER_... | def function[custom_add_user_view, parameter[request]]:
constant[ The page to add a new user. ]
variable[page_name] assign[=] constant[Admin - Add User]
variable[add_user_form] assign[=] call[name[AddUserForm], parameter[<ast.BoolOp object at 0x7da18f721b40>]]
if call[name[add_user_form]... | keyword[def] identifier[custom_add_user_view] ( identifier[request] ):
literal[string]
identifier[page_name] = literal[string]
identifier[add_user_form] = identifier[AddUserForm] ( identifier[request] . identifier[POST] keyword[or] keyword[None] , identifier[initial] ={
literal[string] : ident... | def custom_add_user_view(request):
""" The page to add a new user. """
page_name = 'Admin - Add User'
add_user_form = AddUserForm(request.POST or None, initial={'status': UserProfile.RESIDENT})
if add_user_form.is_valid():
add_user_form.save()
message = MESSAGES['USER_ADDED'].format(user... |
def dims_knight(self, move):
'''Knight on the rim is dim'''
if self.board.piece_type_at(move.from_square) == chess.KNIGHT:
rim = SquareSet(
chess.BB_RANK_1 | \
chess.BB_RANK_8 | \
chess.BB_FILE_A | \
chess.BB_FILE_H)
return move.to_square in rim | def function[dims_knight, parameter[self, move]]:
constant[Knight on the rim is dim]
if compare[call[name[self].board.piece_type_at, parameter[name[move].from_square]] equal[==] name[chess].KNIGHT] begin[:]
variable[rim] assign[=] call[name[SquareSet], parameter[binary_operation[binary_o... | keyword[def] identifier[dims_knight] ( identifier[self] , identifier[move] ):
literal[string]
keyword[if] identifier[self] . identifier[board] . identifier[piece_type_at] ( identifier[move] . identifier[from_square] )== identifier[chess] . identifier[KNIGHT] :
identifier[rim] = identifier[SquareSet... | def dims_knight(self, move):
"""Knight on the rim is dim"""
if self.board.piece_type_at(move.from_square) == chess.KNIGHT:
rim = SquareSet(chess.BB_RANK_1 | chess.BB_RANK_8 | chess.BB_FILE_A | chess.BB_FILE_H)
return move.to_square in rim # depends on [control=['if'], data=[]] |
def extend_access_token(self, app_id, app_secret):
"""
Extends the expiration time of a valid OAuth access token. See
<https://developers.facebook.com/docs/facebook-login/access-tokens/
expiration-and-extension>
"""
args = {
"client_id": app_id,
"... | def function[extend_access_token, parameter[self, app_id, app_secret]]:
constant[
Extends the expiration time of a valid OAuth access token. See
<https://developers.facebook.com/docs/facebook-login/access-tokens/
expiration-and-extension>
]
variable[args] assign[=] dicti... | keyword[def] identifier[extend_access_token] ( identifier[self] , identifier[app_id] , identifier[app_secret] ):
literal[string]
identifier[args] ={
literal[string] : identifier[app_id] ,
literal[string] : identifier[app_secret] ,
literal[string] : literal[string] ,
... | def extend_access_token(self, app_id, app_secret):
"""
Extends the expiration time of a valid OAuth access token. See
<https://developers.facebook.com/docs/facebook-login/access-tokens/
expiration-and-extension>
"""
args = {'client_id': app_id, 'client_secret': app_secret, 'gran... |
def __convertLongToString(self, iValue):
"""convert a long hex integer to string
remove '0x' and 'L' return string
Args:
iValue: long integer in hex format
Returns:
string of this long integer without "0x" and "L"
"""
string = ''
strVa... | def function[__convertLongToString, parameter[self, iValue]]:
constant[convert a long hex integer to string
remove '0x' and 'L' return string
Args:
iValue: long integer in hex format
Returns:
string of this long integer without "0x" and "L"
]
... | keyword[def] identifier[__convertLongToString] ( identifier[self] , identifier[iValue] ):
literal[string]
identifier[string] = literal[string]
identifier[strValue] = identifier[str] ( identifier[hex] ( identifier[iValue] ))
identifier[string] = identifier[strValue] . identifier[... | def __convertLongToString(self, iValue):
"""convert a long hex integer to string
remove '0x' and 'L' return string
Args:
iValue: long integer in hex format
Returns:
string of this long integer without "0x" and "L"
"""
string = ''
strValue = str(he... |
def is_all_field_none(self):
"""
:rtype: bool
"""
if self._target_url is not None:
return False
if self._category is not None:
return False
if self._event_type is not None:
return False
if self._object_ is not None:
... | def function[is_all_field_none, parameter[self]]:
constant[
:rtype: bool
]
if compare[name[self]._target_url is_not constant[None]] begin[:]
return[constant[False]]
if compare[name[self]._category is_not constant[None]] begin[:]
return[constant[False]]
if ... | keyword[def] identifier[is_all_field_none] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_target_url] keyword[is] keyword[not] keyword[None] :
keyword[return] keyword[False]
keyword[if] identifier[self] . identifier[_category] keywor... | def is_all_field_none(self):
"""
:rtype: bool
"""
if self._target_url is not None:
return False # depends on [control=['if'], data=[]]
if self._category is not None:
return False # depends on [control=['if'], data=[]]
if self._event_type is not None:
return Fals... |
def continuous_binary_search(f, lo, hi, gap=1e-4):
"""Binary search for a function
:param f: boolean monotone function with f(hi) = True
:param int lo:
:param int hi: with hi >= lo
:param float gap:
:returns: first value x in [lo,hi] such that f(x),
x is computed up to some precisi... | def function[continuous_binary_search, parameter[f, lo, hi, gap]]:
constant[Binary search for a function
:param f: boolean monotone function with f(hi) = True
:param int lo:
:param int hi: with hi >= lo
:param float gap:
:returns: first value x in [lo,hi] such that f(x),
x is c... | keyword[def] identifier[continuous_binary_search] ( identifier[f] , identifier[lo] , identifier[hi] , identifier[gap] = literal[int] ):
literal[string]
keyword[while] identifier[hi] - identifier[lo] > identifier[gap] :
identifier[mid] =( identifier[lo] + identifier[hi] )/ literal[int]
... | def continuous_binary_search(f, lo, hi, gap=0.0001):
"""Binary search for a function
:param f: boolean monotone function with f(hi) = True
:param int lo:
:param int hi: with hi >= lo
:param float gap:
:returns: first value x in [lo,hi] such that f(x),
x is computed up to some preci... |
def save(self, cfg, filename, print_ir=False, format='dot', options=None):
"""Save basic block graph into a file.
"""
if options is None:
options = {}
try:
dot_graph = Dot(**self.graph_format)
# Add nodes.
nodes = {}
for bb in... | def function[save, parameter[self, cfg, filename, print_ir, format, options]]:
constant[Save basic block graph into a file.
]
if compare[name[options] is constant[None]] begin[:]
variable[options] assign[=] dictionary[[], []]
<ast.Try object at 0x7da1b0926e90> | keyword[def] identifier[save] ( identifier[self] , identifier[cfg] , identifier[filename] , identifier[print_ir] = keyword[False] , identifier[format] = literal[string] , identifier[options] = keyword[None] ):
literal[string]
keyword[if] identifier[options] keyword[is] keyword[None] :
... | def save(self, cfg, filename, print_ir=False, format='dot', options=None):
"""Save basic block graph into a file.
"""
if options is None:
options = {} # depends on [control=['if'], data=['options']]
try:
dot_graph = Dot(**self.graph_format)
# Add nodes.
nodes = {}
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.