code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def get_comment_lookup_session(self):
"""Gets the ``OsidSession`` associated with the comment lookup service.
return: (osid.commenting.CommentLookupSession) - a
``CommentLookupSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``suppor... | def function[get_comment_lookup_session, parameter[self]]:
constant[Gets the ``OsidSession`` associated with the comment lookup service.
return: (osid.commenting.CommentLookupSession) - a
``CommentLookupSession``
raise: OperationFailed - unable to complete request
raise... | keyword[def] identifier[get_comment_lookup_session] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[supports_comment_lookup] ():
keyword[raise] identifier[errors] . identifier[Unimplemented] ()
keyword[return] ident... | def get_comment_lookup_session(self):
"""Gets the ``OsidSession`` associated with the comment lookup service.
return: (osid.commenting.CommentLookupSession) - a
``CommentLookupSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_c... |
def execute(self):
"""
Remote Popen (actually execute the slack webhook call)
"""
proxies = {}
if self.proxy:
# we only need https proxy for Slack, as the endpoint is https
proxies = {'https': self.proxy}
slack_message = self._build_slack_message(... | def function[execute, parameter[self]]:
constant[
Remote Popen (actually execute the slack webhook call)
]
variable[proxies] assign[=] dictionary[[], []]
if name[self].proxy begin[:]
variable[proxies] assign[=] dictionary[[<ast.Constant object at 0x7da20c6c55a0>],... | keyword[def] identifier[execute] ( identifier[self] ):
literal[string]
identifier[proxies] ={}
keyword[if] identifier[self] . identifier[proxy] :
identifier[proxies] ={ literal[string] : identifier[self] . identifier[proxy] }
identifier[slack_message] = ide... | def execute(self):
"""
Remote Popen (actually execute the slack webhook call)
"""
proxies = {}
if self.proxy:
# we only need https proxy for Slack, as the endpoint is https
proxies = {'https': self.proxy} # depends on [control=['if'], data=[]]
slack_message = self._build... |
def base_url(self, url):
"""Return url without querystring or fragment"""
parts = list(self.parse_url(url))
parts[4:] = ['' for i in parts[4:]]
return urlunparse(parts) | def function[base_url, parameter[self, url]]:
constant[Return url without querystring or fragment]
variable[parts] assign[=] call[name[list], parameter[call[name[self].parse_url, parameter[name[url]]]]]
call[name[parts]][<ast.Slice object at 0x7da1b121a7a0>] assign[=] <ast.ListComp object at 0x7... | keyword[def] identifier[base_url] ( identifier[self] , identifier[url] ):
literal[string]
identifier[parts] = identifier[list] ( identifier[self] . identifier[parse_url] ( identifier[url] ))
identifier[parts] [ literal[int] :]=[ literal[string] keyword[for] identifier[i] keyword[in] id... | def base_url(self, url):
"""Return url without querystring or fragment"""
parts = list(self.parse_url(url))
parts[4:] = ['' for i in parts[4:]]
return urlunparse(parts) |
def reset(self):
"""Clear out the state of the BuildGraph, in particular Target mappings and dependencies.
:API: public
"""
self._target_by_address = OrderedDict()
self._target_dependencies_by_address = defaultdict(OrderedSet)
self._target_dependees_by_address = defaultdict(OrderedSet)
self... | def function[reset, parameter[self]]:
constant[Clear out the state of the BuildGraph, in particular Target mappings and dependencies.
:API: public
]
name[self]._target_by_address assign[=] call[name[OrderedDict], parameter[]]
name[self]._target_dependencies_by_address assign[=] call[nam... | keyword[def] identifier[reset] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_target_by_address] = identifier[OrderedDict] ()
identifier[self] . identifier[_target_dependencies_by_address] = identifier[defaultdict] ( identifier[OrderedSet] )
identifier[self] . identifier[_ta... | def reset(self):
"""Clear out the state of the BuildGraph, in particular Target mappings and dependencies.
:API: public
"""
self._target_by_address = OrderedDict()
self._target_dependencies_by_address = defaultdict(OrderedSet)
self._target_dependees_by_address = defaultdict(OrderedSet)
self... |
def patch(self):
"""Return a jsonpatch object representing the delta"""
original = self.__dict__['__original__']
return jsonpatch.make_patch(original, dict(self)).to_string() | def function[patch, parameter[self]]:
constant[Return a jsonpatch object representing the delta]
variable[original] assign[=] call[name[self].__dict__][constant[__original__]]
return[call[call[name[jsonpatch].make_patch, parameter[name[original], call[name[dict], parameter[name[self]]]]].to_string, ... | keyword[def] identifier[patch] ( identifier[self] ):
literal[string]
identifier[original] = identifier[self] . identifier[__dict__] [ literal[string] ]
keyword[return] identifier[jsonpatch] . identifier[make_patch] ( identifier[original] , identifier[dict] ( identifier[self] )). identifie... | def patch(self):
"""Return a jsonpatch object representing the delta"""
original = self.__dict__['__original__']
return jsonpatch.make_patch(original, dict(self)).to_string() |
def get_version(version=None):
"""Derives a PEP386-compliant version number from VERSION."""
if version is None:
version = VERSION
assert len(version) == 5
assert version[3] in ("alpha", "beta", "rc", "final")
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub =... | def function[get_version, parameter[version]]:
constant[Derives a PEP386-compliant version number from VERSION.]
if compare[name[version] is constant[None]] begin[:]
variable[version] assign[=] name[VERSION]
assert[compare[call[name[len], parameter[name[version]]] equal[==] constant[... | keyword[def] identifier[get_version] ( identifier[version] = keyword[None] ):
literal[string]
keyword[if] identifier[version] keyword[is] keyword[None] :
identifier[version] = identifier[VERSION]
keyword[assert] identifier[len] ( identifier[version] )== literal[int]
keyword[assert]... | def get_version(version=None):
"""Derives a PEP386-compliant version number from VERSION."""
if version is None:
version = VERSION # depends on [control=['if'], data=['version']]
assert len(version) == 5
assert version[3] in ('alpha', 'beta', 'rc', 'final')
# Now build the two parts of the ... |
def sign(self, signer: Signer):
""" Sign message using signer. """
message_data = self._data_to_sign()
self.signature = signer.sign(data=message_data) | def function[sign, parameter[self, signer]]:
constant[ Sign message using signer. ]
variable[message_data] assign[=] call[name[self]._data_to_sign, parameter[]]
name[self].signature assign[=] call[name[signer].sign, parameter[]] | keyword[def] identifier[sign] ( identifier[self] , identifier[signer] : identifier[Signer] ):
literal[string]
identifier[message_data] = identifier[self] . identifier[_data_to_sign] ()
identifier[self] . identifier[signature] = identifier[signer] . identifier[sign] ( identifier[data] = ide... | def sign(self, signer: Signer):
""" Sign message using signer. """
message_data = self._data_to_sign()
self.signature = signer.sign(data=message_data) |
def send_command(self, command: str, *args, **kwargs):
"""
For request bot to perform some action
"""
info = 'send command `%s` to bot. Args: %s | Kwargs: %s'
self._messaging_logger.command.info(info, command, args, kwargs)
command = command.encode('utf8')
# targ... | def function[send_command, parameter[self, command]]:
constant[
For request bot to perform some action
]
variable[info] assign[=] constant[send command `%s` to bot. Args: %s | Kwargs: %s]
call[name[self]._messaging_logger.command.info, parameter[name[info], name[command], name[ar... | keyword[def] identifier[send_command] ( identifier[self] , identifier[command] : identifier[str] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[info] = literal[string]
identifier[self] . identifier[_messaging_logger] . identifier[command] . identifier[info] ( ide... | def send_command(self, command: str, *args, **kwargs):
"""
For request bot to perform some action
"""
info = 'send command `%s` to bot. Args: %s | Kwargs: %s'
self._messaging_logger.command.info(info, command, args, kwargs)
command = command.encode('utf8')
# target = target.encode('a... |
def focus_prev(self):
"""move focus to previous position (DFO)"""
w, focuspos = self.get_focus()
prev = self._tree.prev_position(focuspos)
if prev is not None:
self.set_focus(prev) | def function[focus_prev, parameter[self]]:
constant[move focus to previous position (DFO)]
<ast.Tuple object at 0x7da20c990670> assign[=] call[name[self].get_focus, parameter[]]
variable[prev] assign[=] call[name[self]._tree.prev_position, parameter[name[focuspos]]]
if compare[name[prev]... | keyword[def] identifier[focus_prev] ( identifier[self] ):
literal[string]
identifier[w] , identifier[focuspos] = identifier[self] . identifier[get_focus] ()
identifier[prev] = identifier[self] . identifier[_tree] . identifier[prev_position] ( identifier[focuspos] )
keyword[if] id... | def focus_prev(self):
"""move focus to previous position (DFO)"""
(w, focuspos) = self.get_focus()
prev = self._tree.prev_position(focuspos)
if prev is not None:
self.set_focus(prev) # depends on [control=['if'], data=['prev']] |
def colorize(string, color='black', bold=False, underline=False, highlight=False):
"""
:param string: message to colorize.
:type string: unicode
:param color: one of :attr:`fatbotslim.irc.colors.ColorMessage._colors`.
:type color: str
:param bold: if the string has to be ... | def function[colorize, parameter[string, color, bold, underline, highlight]]:
constant[
:param string: message to colorize.
:type string: unicode
:param color: one of :attr:`fatbotslim.irc.colors.ColorMessage._colors`.
:type color: str
:param bold: if the string has to be... | keyword[def] identifier[colorize] ( identifier[string] , identifier[color] = literal[string] , identifier[bold] = keyword[False] , identifier[underline] = keyword[False] , identifier[highlight] = keyword[False] ):
literal[string]
identifier[result] = literal[string]
keyword[if] identifie... | def colorize(string, color='black', bold=False, underline=False, highlight=False):
"""
:param string: message to colorize.
:type string: unicode
:param color: one of :attr:`fatbotslim.irc.colors.ColorMessage._colors`.
:type color: str
:param bold: if the string has to be in b... |
def _map_arg(arg):
"""
Return `arg` appropriately parsed or mapped to a usable value.
"""
# Grab the easy to parse values
if isinstance(arg, _ast.Str):
return repr(arg.s)
elif isinstance(arg, _ast.Num):
return arg.n
elif isinstance(arg, _ast.Name):
name = arg.id
... | def function[_map_arg, parameter[arg]]:
constant[
Return `arg` appropriately parsed or mapped to a usable value.
]
if call[name[isinstance], parameter[name[arg], name[_ast].Str]] begin[:]
return[call[name[repr], parameter[name[arg].s]]] | keyword[def] identifier[_map_arg] ( identifier[arg] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[arg] , identifier[_ast] . identifier[Str] ):
keyword[return] identifier[repr] ( identifier[arg] . identifier[s] )
keyword[elif] identifier[isinstance] ( identifier[ar... | def _map_arg(arg):
"""
Return `arg` appropriately parsed or mapped to a usable value.
"""
# Grab the easy to parse values
if isinstance(arg, _ast.Str):
return repr(arg.s) # depends on [control=['if'], data=[]]
elif isinstance(arg, _ast.Num):
return arg.n # depends on [control=... |
def create_syslog(self,
service_id,
version_number,
name,
address,
port=514,
use_tls="0",
tls_ca_cert=None,
token=None,
_format=None,
response_condition=None):
"""Create a Syslog for a particular service and version."""
body = self._formdata({
"name": name,
"address": address,
"port": p... | def function[create_syslog, parameter[self, service_id, version_number, name, address, port, use_tls, tls_ca_cert, token, _format, response_condition]]:
constant[Create a Syslog for a particular service and version.]
variable[body] assign[=] call[name[self]._formdata, parameter[dictionary[[<ast.Constant... | keyword[def] identifier[create_syslog] ( identifier[self] ,
identifier[service_id] ,
identifier[version_number] ,
identifier[name] ,
identifier[address] ,
identifier[port] = literal[int] ,
identifier[use_tls] = literal[string] ,
identifier[tls_ca_cert] = keyword[None] ,
identifier[token] = keyword[None] ,
id... | def create_syslog(self, service_id, version_number, name, address, port=514, use_tls='0', tls_ca_cert=None, token=None, _format=None, response_condition=None):
"""Create a Syslog for a particular service and version."""
body = self._formdata({'name': name, 'address': address, 'port': port, 'use_tls': use_tls, '... |
def create_account(self, short_name, author_name=None, author_url=None,
replace_token=True):
""" Create a new Telegraph account
:param short_name: Account name, helps users with several
accounts remember which they are currently using.
... | def function[create_account, parameter[self, short_name, author_name, author_url, replace_token]]:
constant[ Create a new Telegraph account
:param short_name: Account name, helps users with several
accounts remember which they are currently using.
D... | keyword[def] identifier[create_account] ( identifier[self] , identifier[short_name] , identifier[author_name] = keyword[None] , identifier[author_url] = keyword[None] ,
identifier[replace_token] = keyword[True] ):
literal[string]
identifier[response] = identifier[self] . identifier[_telegraph] . ... | def create_account(self, short_name, author_name=None, author_url=None, replace_token=True):
""" Create a new Telegraph account
:param short_name: Account name, helps users with several
accounts remember which they are currently using.
Displayed to the ... |
def _set_igmps_querier(self, v, load=False):
"""
Setter method for igmps_querier, mapped from YANG variable /interface_vlan/vlan/ip/igmpVlan/snooping/igmps_querier (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_igmps_querier is considered as a private
me... | def function[_set_igmps_querier, parameter[self, v, load]]:
constant[
Setter method for igmps_querier, mapped from YANG variable /interface_vlan/vlan/ip/igmpVlan/snooping/igmps_querier (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_igmps_querier is consi... | keyword[def] identifier[_set_igmps_querier] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
... | def _set_igmps_querier(self, v, load=False):
"""
Setter method for igmps_querier, mapped from YANG variable /interface_vlan/vlan/ip/igmpVlan/snooping/igmps_querier (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_igmps_querier is considered as a private
me... |
def derive_key(mode, version, salt, key,
private_key, dh, auth_secret,
keyid, keylabel="P-256"):
"""Derive the encryption key
:param mode: operational mode (encrypt or decrypt)
:type mode: enumerate('encrypt', 'decrypt)
:param salt: encryption salt value
:type salt: st... | def function[derive_key, parameter[mode, version, salt, key, private_key, dh, auth_secret, keyid, keylabel]]:
constant[Derive the encryption key
:param mode: operational mode (encrypt or decrypt)
:type mode: enumerate('encrypt', 'decrypt)
:param salt: encryption salt value
:type salt: str
:... | keyword[def] identifier[derive_key] ( identifier[mode] , identifier[version] , identifier[salt] , identifier[key] ,
identifier[private_key] , identifier[dh] , identifier[auth_secret] ,
identifier[keyid] , identifier[keylabel] = literal[string] ):
literal[string]
identifier[context] = literal[string]
... | def derive_key(mode, version, salt, key, private_key, dh, auth_secret, keyid, keylabel='P-256'):
"""Derive the encryption key
:param mode: operational mode (encrypt or decrypt)
:type mode: enumerate('encrypt', 'decrypt)
:param salt: encryption salt value
:type salt: str
:param key: raw key
... |
def import_from_html(
filename_or_fobj,
encoding="utf-8",
index=0,
ignore_colspan=True,
preserve_html=False,
properties=False,
table_tag="table",
row_tag="tr",
column_tag="td|th",
*args,
**kwargs
):
"""Return rows.Table from HTML file."""
source = Source.from_file(
... | def function[import_from_html, parameter[filename_or_fobj, encoding, index, ignore_colspan, preserve_html, properties, table_tag, row_tag, column_tag]]:
constant[Return rows.Table from HTML file.]
variable[source] assign[=] call[name[Source].from_file, parameter[name[filename_or_fobj]]]
variable... | keyword[def] identifier[import_from_html] (
identifier[filename_or_fobj] ,
identifier[encoding] = literal[string] ,
identifier[index] = literal[int] ,
identifier[ignore_colspan] = keyword[True] ,
identifier[preserve_html] = keyword[False] ,
identifier[properties] = keyword[False] ,
identifier[table_tag] = lite... | def import_from_html(filename_or_fobj, encoding='utf-8', index=0, ignore_colspan=True, preserve_html=False, properties=False, table_tag='table', row_tag='tr', column_tag='td|th', *args, **kwargs):
"""Return rows.Table from HTML file."""
source = Source.from_file(filename_or_fobj, plugin_name='html', mode='rb', ... |
def post_molo_comment(request, next=None, using=None):
"""
Allows for posting of a Molo Comment, this allows comments to
be set with the "user_name" as "Anonymous"
"""
data = request.POST.copy()
if 'submit_anonymously' in data:
data['name'] = 'Anonymous'
# replace with our changed PO... | def function[post_molo_comment, parameter[request, next, using]]:
constant[
Allows for posting of a Molo Comment, this allows comments to
be set with the "user_name" as "Anonymous"
]
variable[data] assign[=] call[name[request].POST.copy, parameter[]]
if compare[constant[submit_anonym... | keyword[def] identifier[post_molo_comment] ( identifier[request] , identifier[next] = keyword[None] , identifier[using] = keyword[None] ):
literal[string]
identifier[data] = identifier[request] . identifier[POST] . identifier[copy] ()
keyword[if] literal[string] keyword[in] identifier[data] :
... | def post_molo_comment(request, next=None, using=None):
"""
Allows for posting of a Molo Comment, this allows comments to
be set with the "user_name" as "Anonymous"
"""
data = request.POST.copy()
if 'submit_anonymously' in data:
data['name'] = 'Anonymous' # depends on [control=['if'], da... |
def row_wise_rescale(matrix):
"""
Row-wise rescale of a given matrix.
For fMRI data (num_voxels x num_time_points), this would translate to voxel-wise normalization over time.
Parameters
----------
matrix : ndarray
Input rectangular matrix, typically a carpet of size num_voxels x num_... | def function[row_wise_rescale, parameter[matrix]]:
constant[
Row-wise rescale of a given matrix.
For fMRI data (num_voxels x num_time_points), this would translate to voxel-wise normalization over time.
Parameters
----------
matrix : ndarray
Input rectangular matrix, typically a c... | keyword[def] identifier[row_wise_rescale] ( identifier[matrix] ):
literal[string]
keyword[if] identifier[matrix] . identifier[shape] [ literal[int] ]<= identifier[matrix] . identifier[shape] [ literal[int] ]:
keyword[raise] identifier[ValueError] ( literal[string]
literal[string] )
... | def row_wise_rescale(matrix):
"""
Row-wise rescale of a given matrix.
For fMRI data (num_voxels x num_time_points), this would translate to voxel-wise normalization over time.
Parameters
----------
matrix : ndarray
Input rectangular matrix, typically a carpet of size num_voxels x num_... |
def recursive_requests(response, spider, ignore_regex='',
ignore_file_extensions='pdf'):
"""
Manages recursive requests.
Determines urls to recursivly crawl if they do not match certain file
extensions and do not match a certain regex set in the config file.
... | def function[recursive_requests, parameter[response, spider, ignore_regex, ignore_file_extensions]]:
constant[
Manages recursive requests.
Determines urls to recursivly crawl if they do not match certain file
extensions and do not match a certain regex set in the config file.
:p... | keyword[def] identifier[recursive_requests] ( identifier[response] , identifier[spider] , identifier[ignore_regex] = literal[string] ,
identifier[ignore_file_extensions] = literal[string] ):
literal[string]
keyword[return] [
identifier[scrapy] . identifier[Reque... | def recursive_requests(response, spider, ignore_regex='', ignore_file_extensions='pdf'):
"""
Manages recursive requests.
Determines urls to recursivly crawl if they do not match certain file
extensions and do not match a certain regex set in the config file.
:param obj response: the... |
def handle_delete_user(self, req):
"""Handles the DELETE v2/<account>/<user> call for deleting a user from an
account.
Can only be called by an account .admin.
:param req: The swob.Request to process.
:returns: swob.Response, 2xx on success.
"""
# Validate path ... | def function[handle_delete_user, parameter[self, req]]:
constant[Handles the DELETE v2/<account>/<user> call for deleting a user from an
account.
Can only be called by an account .admin.
:param req: The swob.Request to process.
:returns: swob.Response, 2xx on success.
]... | keyword[def] identifier[handle_delete_user] ( identifier[self] , identifier[req] ):
literal[string]
identifier[account] = identifier[req] . identifier[path_info_pop] ()
identifier[user] = identifier[req] . identifier[path_info_pop] ()
keyword[if] identifier[req] . identi... | def handle_delete_user(self, req):
"""Handles the DELETE v2/<account>/<user> call for deleting a user from an
account.
Can only be called by an account .admin.
:param req: The swob.Request to process.
:returns: swob.Response, 2xx on success.
"""
# Validate path info
... |
def dos_plot_data(self, yscale=1, xmin=-6., xmax=6., colours=None,
plot_total=True, legend_cutoff=3, subplot=False,
zero_to_efermi=True, cache=None):
"""Get the plotting data.
Args:
yscale (:obj:`float`, optional): Scaling factor for the y-axis.
... | def function[dos_plot_data, parameter[self, yscale, xmin, xmax, colours, plot_total, legend_cutoff, subplot, zero_to_efermi, cache]]:
constant[Get the plotting data.
Args:
yscale (:obj:`float`, optional): Scaling factor for the y-axis.
xmin (:obj:`float`, optional): The minimum ... | keyword[def] identifier[dos_plot_data] ( identifier[self] , identifier[yscale] = literal[int] , identifier[xmin] =- literal[int] , identifier[xmax] = literal[int] , identifier[colours] = keyword[None] ,
identifier[plot_total] = keyword[True] , identifier[legend_cutoff] = literal[int] , identifier[subplot] = keyword[... | def dos_plot_data(self, yscale=1, xmin=-6.0, xmax=6.0, colours=None, plot_total=True, legend_cutoff=3, subplot=False, zero_to_efermi=True, cache=None):
"""Get the plotting data.
Args:
yscale (:obj:`float`, optional): Scaling factor for the y-axis.
xmin (:obj:`float`, optional): The ... |
def find(self, obj, filter_to_class=Ingredient, constructor=None):
"""
Find an Ingredient, optionally using the shelf.
:param obj: A string or Ingredient
:param filter_to_class: The Ingredient subclass that obj must be an
instance of
:param constructor: An optional call... | def function[find, parameter[self, obj, filter_to_class, constructor]]:
constant[
Find an Ingredient, optionally using the shelf.
:param obj: A string or Ingredient
:param filter_to_class: The Ingredient subclass that obj must be an
instance of
:param constructor: An op... | keyword[def] identifier[find] ( identifier[self] , identifier[obj] , identifier[filter_to_class] = identifier[Ingredient] , identifier[constructor] = keyword[None] ):
literal[string]
keyword[if] identifier[callable] ( identifier[constructor] ):
identifier[obj] = identifier[constructor... | def find(self, obj, filter_to_class=Ingredient, constructor=None):
"""
Find an Ingredient, optionally using the shelf.
:param obj: A string or Ingredient
:param filter_to_class: The Ingredient subclass that obj must be an
instance of
:param constructor: An optional callable... |
def encode(obj):
r"""Encode all unicode/str objects in a dataframe in the encoding indicated (as a fun attribute)
similar to to_ascii, but doesn't return a None, even when it fails.
>>> encode(u'Is 2013 a year or a code point for "\u2013"?')
b'Is 2013 a year or a code point for "\xe2\x80\x93"?'
>>>... | def function[encode, parameter[obj]]:
constant[Encode all unicode/str objects in a dataframe in the encoding indicated (as a fun attribute)
similar to to_ascii, but doesn't return a None, even when it fails.
>>> encode(u'Is 2013 a year or a code point for "\u2013"?')
b'Is 2013 a year or a code poin... | keyword[def] identifier[encode] ( identifier[obj] ):
literal[string]
keyword[try] :
keyword[return] identifier[obj] . identifier[encode] ( identifier[encode] . identifier[encoding] )
keyword[except] identifier[AttributeError] :
keyword[pass]
keyword[except] identifier[Unicod... | def encode(obj):
"""Encode all unicode/str objects in a dataframe in the encoding indicated (as a fun attribute)
similar to to_ascii, but doesn't return a None, even when it fails.
>>> encode(u'Is 2013 a year or a code point for "\\u2013"?')
b'Is 2013 a year or a code point for "\\xe2\\x80\\x93"?'
... |
def Publish(self, request, context):
"""Dispatches the request to the plugins publish method"""
LOG.debug("Publish called")
try:
self.plugin.publish(
[Metric(pb=m) for m in request.Metrics],
ConfigMap(pb=request.Config)
)
return... | def function[Publish, parameter[self, request, context]]:
constant[Dispatches the request to the plugins publish method]
call[name[LOG].debug, parameter[constant[Publish called]]]
<ast.Try object at 0x7da1b2426980> | keyword[def] identifier[Publish] ( identifier[self] , identifier[request] , identifier[context] ):
literal[string]
identifier[LOG] . identifier[debug] ( literal[string] )
keyword[try] :
identifier[self] . identifier[plugin] . identifier[publish] (
[ identifier[Metr... | def Publish(self, request, context):
"""Dispatches the request to the plugins publish method"""
LOG.debug('Publish called')
try:
self.plugin.publish([Metric(pb=m) for m in request.Metrics], ConfigMap(pb=request.Config))
return ErrReply() # depends on [control=['try'], data=[]]
except Ex... |
def B012(t,i):
"""
Constructs ternary implication coding (0=not there, 2=U, 1=V)
t is B column position
i = |M|-1 to 0
"""
if not i:
return "1"
nA = Awidth(i)
nB = Bwidth(i)
nBB = nB + nA
if t < nB:
return "0"+B012(t,i-1)
elif t < nBB:
return "1"+A012(... | def function[B012, parameter[t, i]]:
constant[
Constructs ternary implication coding (0=not there, 2=U, 1=V)
t is B column position
i = |M|-1 to 0
]
if <ast.UnaryOp object at 0x7da18c4ce410> begin[:]
return[constant[1]]
variable[nA] assign[=] call[name[Awidth], parameter[... | keyword[def] identifier[B012] ( identifier[t] , identifier[i] ):
literal[string]
keyword[if] keyword[not] identifier[i] :
keyword[return] literal[string]
identifier[nA] = identifier[Awidth] ( identifier[i] )
identifier[nB] = identifier[Bwidth] ( identifier[i] )
identifier[nBB] =... | def B012(t, i):
"""
Constructs ternary implication coding (0=not there, 2=U, 1=V)
t is B column position
i = |M|-1 to 0
"""
if not i:
return '1' # depends on [control=['if'], data=[]]
nA = Awidth(i)
nB = Bwidth(i)
nBB = nB + nA
if t < nB:
return '0' + B012(t, i -... |
def call_on_each_endpoint(self, callback):
"""Find all server endpoints defined in the swagger spec and calls 'callback' for each,
with an instance of EndpointData as argument.
"""
if 'paths' not in self.swagger_dict:
return
for path, d in list(self.swagger_dict['pa... | def function[call_on_each_endpoint, parameter[self, callback]]:
constant[Find all server endpoints defined in the swagger spec and calls 'callback' for each,
with an instance of EndpointData as argument.
]
if compare[constant[paths] <ast.NotIn object at 0x7da2590d7190> name[self].swagger... | keyword[def] identifier[call_on_each_endpoint] ( identifier[self] , identifier[callback] ):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[self] . identifier[swagger_dict] :
keyword[return]
keyword[for] identifier[path] , identifier[d] ... | def call_on_each_endpoint(self, callback):
"""Find all server endpoints defined in the swagger spec and calls 'callback' for each,
with an instance of EndpointData as argument.
"""
if 'paths' not in self.swagger_dict:
return # depends on [control=['if'], data=[]]
for (path, d) in li... |
def print_tables(xmldoc, output, output_format, tableList = [], columnList = [],
round_floats = True, decimal_places = 2, format_links = True,
title = None, print_table_names = True, unique_rows = False,
row_span_columns = [], rspan_break_columns = []):
"""
Method to print tables in an xml file in o... | def function[print_tables, parameter[xmldoc, output, output_format, tableList, columnList, round_floats, decimal_places, format_links, title, print_table_names, unique_rows, row_span_columns, rspan_break_columns]]:
constant[
Method to print tables in an xml file in other formats.
Input is an xmldoc, out... | keyword[def] identifier[print_tables] ( identifier[xmldoc] , identifier[output] , identifier[output_format] , identifier[tableList] =[], identifier[columnList] =[],
identifier[round_floats] = keyword[True] , identifier[decimal_places] = literal[int] , identifier[format_links] = keyword[True] ,
identifier[title] = k... | def print_tables(xmldoc, output, output_format, tableList=[], columnList=[], round_floats=True, decimal_places=2, format_links=True, title=None, print_table_names=True, unique_rows=False, row_span_columns=[], rspan_break_columns=[]):
"""
Method to print tables in an xml file in other formats.
Input is an xm... |
def frompsl(args):
"""
%prog frompsl old.new.psl old.fasta new.fasta
Generate chain file from psl file. The pipeline is describe in:
<http://genomewiki.ucsc.edu/index.php/Minimal_Steps_For_LiftOver>
"""
from jcvi.formats.sizes import Sizes
p = OptionParser(frompsl.__doc__)
opts, args =... | def function[frompsl, parameter[args]]:
constant[
%prog frompsl old.new.psl old.fasta new.fasta
Generate chain file from psl file. The pipeline is describe in:
<http://genomewiki.ucsc.edu/index.php/Minimal_Steps_For_LiftOver>
]
from relative_module[jcvi.formats.sizes] import module[Sizes]
... | keyword[def] identifier[frompsl] ( identifier[args] ):
literal[string]
keyword[from] identifier[jcvi] . identifier[formats] . identifier[sizes] keyword[import] identifier[Sizes]
identifier[p] = identifier[OptionParser] ( identifier[frompsl] . identifier[__doc__] )
identifier[opts] , identifi... | def frompsl(args):
"""
%prog frompsl old.new.psl old.fasta new.fasta
Generate chain file from psl file. The pipeline is describe in:
<http://genomewiki.ucsc.edu/index.php/Minimal_Steps_For_LiftOver>
"""
from jcvi.formats.sizes import Sizes
p = OptionParser(frompsl.__doc__)
(opts, args) ... |
def _get_variants(name):
"""Return variants of chemical name."""
names = [name]
oldname = name
# Map greek words to unicode characters
if DOT_GREEK_RE.search(name):
wordname = name
while True:
m = DOT_GREEK_RE.search(wordname)
if m:
wordname = ... | def function[_get_variants, parameter[name]]:
constant[Return variants of chemical name.]
variable[names] assign[=] list[[<ast.Name object at 0x7da18fe90ca0>]]
variable[oldname] assign[=] name[name]
if call[name[DOT_GREEK_RE].search, parameter[name[name]]] begin[:]
variab... | keyword[def] identifier[_get_variants] ( identifier[name] ):
literal[string]
identifier[names] =[ identifier[name] ]
identifier[oldname] = identifier[name]
keyword[if] identifier[DOT_GREEK_RE] . identifier[search] ( identifier[name] ):
identifier[wordname] = identifier[name]
... | def _get_variants(name):
"""Return variants of chemical name."""
names = [name]
oldname = name
# Map greek words to unicode characters
if DOT_GREEK_RE.search(name):
wordname = name
while True:
m = DOT_GREEK_RE.search(wordname)
if m:
wordname = ... |
def endpoint_catalog(catalog=None): # noqa: E501
"""Retrieve the endpoint catalog
Retrieve the endpoint catalog # noqa: E501
:param catalog: The data needed to get a catalog
:type catalog: dict | bytes
:rtype: Response
"""
if connexion.request.is_json:
catalog = UserAuth.from_dic... | def function[endpoint_catalog, parameter[catalog]]:
constant[Retrieve the endpoint catalog
Retrieve the endpoint catalog # noqa: E501
:param catalog: The data needed to get a catalog
:type catalog: dict | bytes
:rtype: Response
]
if name[connexion].request.is_json begin[:]
... | keyword[def] identifier[endpoint_catalog] ( identifier[catalog] = keyword[None] ):
literal[string]
keyword[if] identifier[connexion] . identifier[request] . identifier[is_json] :
identifier[catalog] = identifier[UserAuth] . identifier[from_dict] ( identifier[connexion] . identifier[request] . ide... | def endpoint_catalog(catalog=None): # noqa: E501
'Retrieve the endpoint catalog\n\n Retrieve the endpoint catalog # noqa: E501\n\n :param catalog: The data needed to get a catalog\n :type catalog: dict | bytes\n\n :rtype: Response\n '
if connexion.request.is_json:
catalog = UserAuth.from... |
def get_glove_w2v(source_dir="./data/news20/", dim=100):
"""
Parse or download the pre-trained glove word2vec if source_dir is empty.
:param source_dir: The directory storing the pre-trained word2vec
:param dim: The dimension of a vector
:return: A dict mapping from word to vector
"""
w2v_d... | def function[get_glove_w2v, parameter[source_dir, dim]]:
constant[
Parse or download the pre-trained glove word2vec if source_dir is empty.
:param source_dir: The directory storing the pre-trained word2vec
:param dim: The dimension of a vector
:return: A dict mapping from word to vector
]
... | keyword[def] identifier[get_glove_w2v] ( identifier[source_dir] = literal[string] , identifier[dim] = literal[int] ):
literal[string]
identifier[w2v_dir] = identifier[download_glove_w2v] ( identifier[source_dir] )
identifier[w2v_path] = identifier[os] . identifier[path] . identifier[join] ( identifier... | def get_glove_w2v(source_dir='./data/news20/', dim=100):
"""
Parse or download the pre-trained glove word2vec if source_dir is empty.
:param source_dir: The directory storing the pre-trained word2vec
:param dim: The dimension of a vector
:return: A dict mapping from word to vector
"""
w2v_d... |
def on_recv_rsp(self, rsp_pb):
"""
在收到实时经纪数据推送后会回调到该函数,使用者需要在派生类中覆盖此方法
注意该回调是在独立子线程中
:param rsp_pb: 派生类中不需要直接处理该参数
:return: 成功时返回(RET_OK, stock_code, [bid_frame_table, ask_frame_table]), 相关frame table含义见 get_broker_queue_ 的返回值说明
失败时返回(RET_ERROR, ERR_MSG, None)... | def function[on_recv_rsp, parameter[self, rsp_pb]]:
constant[
在收到实时经纪数据推送后会回调到该函数,使用者需要在派生类中覆盖此方法
注意该回调是在独立子线程中
:param rsp_pb: 派生类中不需要直接处理该参数
:return: 成功时返回(RET_OK, stock_code, [bid_frame_table, ask_frame_table]), 相关frame table含义见 get_broker_queue_ 的返回值说明
失败时返... | keyword[def] identifier[on_recv_rsp] ( identifier[self] , identifier[rsp_pb] ):
literal[string]
identifier[ret_code] , identifier[content] = identifier[self] . identifier[parse_rsp_pb] ( identifier[rsp_pb] )
keyword[if] identifier[ret_code] != identifier[RET_OK] :
keyword[ret... | def on_recv_rsp(self, rsp_pb):
"""
在收到实时经纪数据推送后会回调到该函数,使用者需要在派生类中覆盖此方法
注意该回调是在独立子线程中
:param rsp_pb: 派生类中不需要直接处理该参数
:return: 成功时返回(RET_OK, stock_code, [bid_frame_table, ask_frame_table]), 相关frame table含义见 get_broker_queue_ 的返回值说明
失败时返回(RET_ERROR, ERR_MSG, None)
... |
def add_sign(xml, key, cert, debug=False, sign_algorithm=OneLogin_Saml2_Constants.RSA_SHA1, digest_algorithm=OneLogin_Saml2_Constants.SHA1):
"""
Adds signature key and senders certificate to an element (Message or
Assertion).
:param xml: The element we should sign
:type: string ... | def function[add_sign, parameter[xml, key, cert, debug, sign_algorithm, digest_algorithm]]:
constant[
Adds signature key and senders certificate to an element (Message or
Assertion).
:param xml: The element we should sign
:type: string | Document
:param key: The private... | keyword[def] identifier[add_sign] ( identifier[xml] , identifier[key] , identifier[cert] , identifier[debug] = keyword[False] , identifier[sign_algorithm] = identifier[OneLogin_Saml2_Constants] . identifier[RSA_SHA1] , identifier[digest_algorithm] = identifier[OneLogin_Saml2_Constants] . identifier[SHA1] ):
... | def add_sign(xml, key, cert, debug=False, sign_algorithm=OneLogin_Saml2_Constants.RSA_SHA1, digest_algorithm=OneLogin_Saml2_Constants.SHA1):
"""
Adds signature key and senders certificate to an element (Message or
Assertion).
:param xml: The element we should sign
:type: string | Do... |
def _get_line_offset(self):
"""Get line offset for the current segment
Read line offset from the file and adapt it to the current segment
or half disk scan so that
y(l) ~ l - loff
because this is what get_geostationary_area_extent() expects.
"""
# Get line ... | def function[_get_line_offset, parameter[self]]:
constant[Get line offset for the current segment
Read line offset from the file and adapt it to the current segment
or half disk scan so that
y(l) ~ l - loff
because this is what get_geostationary_area_extent() expects.
... | keyword[def] identifier[_get_line_offset] ( identifier[self] ):
literal[string]
identifier[nlines] = identifier[int] ( identifier[self] . identifier[mda] [ literal[string] ])
identifier[loff] = identifier[np] . identifier[float32] ( identifier[self] . identifier[mda] [ literal[str... | def _get_line_offset(self):
"""Get line offset for the current segment
Read line offset from the file and adapt it to the current segment
or half disk scan so that
y(l) ~ l - loff
because this is what get_geostationary_area_extent() expects.
"""
# Get line offset f... |
def add_phase(self):
"""Context manager for when adding all the tokens"""
# add stuff
yield self
# Make sure we output eveything
self.finish_hanging()
# Remove trailing indents and dedents
while len(self.result) > 1 and self.result[-2][0] in (INDENT, ERRORTOKEN,... | def function[add_phase, parameter[self]]:
constant[Context manager for when adding all the tokens]
<ast.Yield object at 0x7da1b0b71d50>
call[name[self].finish_hanging, parameter[]]
while <ast.BoolOp object at 0x7da1b0b73ca0> begin[:]
call[name[self].result.pop, parameter[... | keyword[def] identifier[add_phase] ( identifier[self] ):
literal[string]
keyword[yield] identifier[self]
identifier[self] . identifier[finish_hanging] ()
keyword[while] identifier[len] ( identifier[self] . identifier[result] )> literal[int] keyword... | def add_phase(self):
"""Context manager for when adding all the tokens"""
# add stuff
yield self
# Make sure we output eveything
self.finish_hanging()
# Remove trailing indents and dedents
while len(self.result) > 1 and self.result[-2][0] in (INDENT, ERRORTOKEN, NEWLINE):
self.result... |
def delete(self, stream, start_time, end_time, start_id=None, namespace=None):
"""
Delete events in the stream with name `stream` that occurred between
`start_time` and `end_time` (both inclusive). An optional `start_id` allows
the client to delete events starting from after an ID rather than starting
... | def function[delete, parameter[self, stream, start_time, end_time, start_id, namespace]]:
constant[
Delete events in the stream with name `stream` that occurred between
`start_time` and `end_time` (both inclusive). An optional `start_id` allows
the client to delete events starting from after an ID ... | keyword[def] identifier[delete] ( identifier[self] , identifier[stream] , identifier[start_time] , identifier[end_time] , identifier[start_id] = keyword[None] , identifier[namespace] = keyword[None] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[start_time] , identifier[types] . identi... | def delete(self, stream, start_time, end_time, start_id=None, namespace=None):
"""
Delete events in the stream with name `stream` that occurred between
`start_time` and `end_time` (both inclusive). An optional `start_id` allows
the client to delete events starting from after an ID rather than starting
... |
def common_update_sys(self):
"""
update system package
"""
try:
sudo('apt-get update -y --fix-missing')
except Exception as e:
print(e)
print(green('System package is up to date.'))
print() | def function[common_update_sys, parameter[self]]:
constant[
update system package
]
<ast.Try object at 0x7da204565750>
call[name[print], parameter[call[name[green], parameter[constant[System package is up to date.]]]]]
call[name[print], parameter[]] | keyword[def] identifier[common_update_sys] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[sudo] ( literal[string] )
keyword[except] identifier[Exception] keyword[as] identifier[e] :
identifier[print] ( identifier[e] )
identifier[print... | def common_update_sys(self):
"""
update system package
"""
try:
sudo('apt-get update -y --fix-missing') # depends on [control=['try'], data=[]]
except Exception as e:
print(e) # depends on [control=['except'], data=['e']]
print(green('System package is up to date.')... |
def classifications(ctx, classifications, results, readlevel, readlevel_path):
"""Retrieve performed metagenomic classifications"""
# basic operation -- just print
if not readlevel and not results:
cli_resource_fetcher(ctx, "classifications", classifications)
# fetch the results
elif not r... | def function[classifications, parameter[ctx, classifications, results, readlevel, readlevel_path]]:
constant[Retrieve performed metagenomic classifications]
if <ast.BoolOp object at 0x7da18ede5900> begin[:]
call[name[cli_resource_fetcher], parameter[name[ctx], constant[classifications], ... | keyword[def] identifier[classifications] ( identifier[ctx] , identifier[classifications] , identifier[results] , identifier[readlevel] , identifier[readlevel_path] ):
literal[string]
keyword[if] keyword[not] identifier[readlevel] keyword[and] keyword[not] identifier[results] :
identifie... | def classifications(ctx, classifications, results, readlevel, readlevel_path):
"""Retrieve performed metagenomic classifications"""
# basic operation -- just print
if not readlevel and (not results):
cli_resource_fetcher(ctx, 'classifications', classifications) # depends on [control=['if'], data=[]... |
def coerce(self, value, **kwargs):
"""Coerces the value to the proper type."""
if value is None:
return None
return self._coercion.coerce(value, **kwargs) | def function[coerce, parameter[self, value]]:
constant[Coerces the value to the proper type.]
if compare[name[value] is constant[None]] begin[:]
return[constant[None]]
return[call[name[self]._coercion.coerce, parameter[name[value]]]] | keyword[def] identifier[coerce] ( identifier[self] , identifier[value] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[None] :
keyword[return] keyword[None]
keyword[return] identifier[self] . identifier[_coercion] . identifier... | def coerce(self, value, **kwargs):
"""Coerces the value to the proper type."""
if value is None:
return None # depends on [control=['if'], data=[]]
return self._coercion.coerce(value, **kwargs) |
def u_projection(a):
r"""
Return the orthogonal projection function over :math:`a`.
The function returned computes the orthogonal projection over
:math:`a` in the Hilbert space of :math:`U`-centered distance
matrices.
The projection of a matrix :math:`B` over a matrix :math:`A`
is defined ... | def function[u_projection, parameter[a]]:
constant[
Return the orthogonal projection function over :math:`a`.
The function returned computes the orthogonal projection over
:math:`a` in the Hilbert space of :math:`U`-centered distance
matrices.
The projection of a matrix :math:`B` over a ma... | keyword[def] identifier[u_projection] ( identifier[a] ):
literal[string]
identifier[c] = identifier[a]
identifier[denominator] = identifier[u_product] ( identifier[c] , identifier[c] )
identifier[docstring] = literal[string]
keyword[if] identifier[denominator] == literal[int] :
... | def u_projection(a):
"""
Return the orthogonal projection function over :math:`a`.
The function returned computes the orthogonal projection over
:math:`a` in the Hilbert space of :math:`U`-centered distance
matrices.
The projection of a matrix :math:`B` over a matrix :math:`A`
is defined a... |
def display(self, image):
"""
Takes a :py:mod:`PIL.Image` and renders it to a pygame display surface.
"""
assert(image.size == self.size)
self._last_image = image
image = self.preprocess(image)
self._clock.tick(self._fps)
self._pygame.event.pump()
... | def function[display, parameter[self, image]]:
constant[
Takes a :py:mod:`PIL.Image` and renders it to a pygame display surface.
]
assert[compare[name[image].size equal[==] name[self].size]]
name[self]._last_image assign[=] name[image]
variable[image] assign[=] call[name[self... | keyword[def] identifier[display] ( identifier[self] , identifier[image] ):
literal[string]
keyword[assert] ( identifier[image] . identifier[size] == identifier[self] . identifier[size] )
identifier[self] . identifier[_last_image] = identifier[image]
identifier[image] = identifie... | def display(self, image):
"""
Takes a :py:mod:`PIL.Image` and renders it to a pygame display surface.
"""
assert image.size == self.size
self._last_image = image
image = self.preprocess(image)
self._clock.tick(self._fps)
self._pygame.event.pump()
if self._abort():
sel... |
def needs_repl_key(self):
"""
We need a repl key if you are auth + a cluster member +
version is None or >= 2.0.0
"""
cluster = self.get_cluster()
return (self.supports_repl_key() and
cluster is not None and cluster.get_repl_key() is not None) | def function[needs_repl_key, parameter[self]]:
constant[
We need a repl key if you are auth + a cluster member +
version is None or >= 2.0.0
]
variable[cluster] assign[=] call[name[self].get_cluster, parameter[]]
return[<ast.BoolOp object at 0x7da1b2844d90>] | keyword[def] identifier[needs_repl_key] ( identifier[self] ):
literal[string]
identifier[cluster] = identifier[self] . identifier[get_cluster] ()
keyword[return] ( identifier[self] . identifier[supports_repl_key] () keyword[and]
identifier[cluster] keyword[is] keyword[not] key... | def needs_repl_key(self):
"""
We need a repl key if you are auth + a cluster member +
version is None or >= 2.0.0
"""
cluster = self.get_cluster()
return self.supports_repl_key() and cluster is not None and (cluster.get_repl_key() is not None) |
def get_user_name(uid, return_none_on_error=True, **kwargs):
'''
Get user name
:param uid: user number [1:16]
:param return_none_on_error: return None on error
:param kwargs:
- api_host=127.0.0.1
- api_user=admin
- api_pass=example
- api_port=623
- api_kg=Non... | def function[get_user_name, parameter[uid, return_none_on_error]]:
constant[
Get user name
:param uid: user number [1:16]
:param return_none_on_error: return None on error
:param kwargs:
- api_host=127.0.0.1
- api_user=admin
- api_pass=example
- api_port=623
... | keyword[def] identifier[get_user_name] ( identifier[uid] , identifier[return_none_on_error] = keyword[True] ,** identifier[kwargs] ):
literal[string]
keyword[with] identifier[_IpmiCommand] (** identifier[kwargs] ) keyword[as] identifier[s] :
keyword[return] identifier[s] . identifier[get_user_n... | def get_user_name(uid, return_none_on_error=True, **kwargs):
"""
Get user name
:param uid: user number [1:16]
:param return_none_on_error: return None on error
:param kwargs:
- api_host=127.0.0.1
- api_user=admin
- api_pass=example
- api_port=623
- api_kg=Non... |
def get_next_del_state(self, state, ret):
"""Return the next delete state from previous state. """
if ret:
if state == fw_const.INIT_STATE:
return state
else:
return state - 1
else:
return state | def function[get_next_del_state, parameter[self, state, ret]]:
constant[Return the next delete state from previous state. ]
if name[ret] begin[:]
if compare[name[state] equal[==] name[fw_const].INIT_STATE] begin[:]
return[name[state]] | keyword[def] identifier[get_next_del_state] ( identifier[self] , identifier[state] , identifier[ret] ):
literal[string]
keyword[if] identifier[ret] :
keyword[if] identifier[state] == identifier[fw_const] . identifier[INIT_STATE] :
keyword[return] identifier[state]
... | def get_next_del_state(self, state, ret):
"""Return the next delete state from previous state. """
if ret:
if state == fw_const.INIT_STATE:
return state # depends on [control=['if'], data=['state']]
else:
return state - 1 # depends on [control=['if'], data=[]]
else:... |
def copy_signal(signal_glob, source_db, target_db):
# type: (str, cm.CanMatrix, cm.CanMatrix) -> None
"""
Copy Signals identified by name from source CAN matrix to target CAN matrix.
In target CanMatrix the signal is put without frame, just on top level.
:param signal_glob: Signal glob pattern
... | def function[copy_signal, parameter[signal_glob, source_db, target_db]]:
constant[
Copy Signals identified by name from source CAN matrix to target CAN matrix.
In target CanMatrix the signal is put without frame, just on top level.
:param signal_glob: Signal glob pattern
:param source_db: Sourc... | keyword[def] identifier[copy_signal] ( identifier[signal_glob] , identifier[source_db] , identifier[target_db] ):
literal[string]
keyword[for] identifier[frame] keyword[in] identifier[source_db] . identifier[frames] :
keyword[for] identifier[signal] keyword[in] identifier[frame] . identifie... | def copy_signal(signal_glob, source_db, target_db):
# type: (str, cm.CanMatrix, cm.CanMatrix) -> None
'\n Copy Signals identified by name from source CAN matrix to target CAN matrix.\n In target CanMatrix the signal is put without frame, just on top level.\n\n :param signal_glob: Signal glob pattern\n ... |
def set_log_level(self, log_level=None):
"""Set the current log level for the daemon
The `log_level` parameter must be in [DEBUG, INFO, WARNING, ERROR, CRITICAL]
In case of any error, this function returns an object containing some properties:
'_status': 'ERR' because of the error
... | def function[set_log_level, parameter[self, log_level]]:
constant[Set the current log level for the daemon
The `log_level` parameter must be in [DEBUG, INFO, WARNING, ERROR, CRITICAL]
In case of any error, this function returns an object containing some properties:
'_status': 'ERR' bec... | keyword[def] identifier[set_log_level] ( identifier[self] , identifier[log_level] = keyword[None] ):
literal[string]
keyword[if] identifier[log_level] keyword[is] keyword[None] :
identifier[log_level] = identifier[cherrypy] . identifier[request] . identifier[json] [ literal[string] ... | def set_log_level(self, log_level=None):
"""Set the current log level for the daemon
The `log_level` parameter must be in [DEBUG, INFO, WARNING, ERROR, CRITICAL]
In case of any error, this function returns an object containing some properties:
'_status': 'ERR' because of the error
... |
def showAnns(self, anns):
"""
Display the specified annotations.
:param anns (array of object): annotations to display
:return: None
"""
if len(anns) == 0:
return 0
if 'segmentation' in anns[0] or 'keypoints' in anns[0]:
datasetType = 'inst... | def function[showAnns, parameter[self, anns]]:
constant[
Display the specified annotations.
:param anns (array of object): annotations to display
:return: None
]
if compare[call[name[len], parameter[name[anns]]] equal[==] constant[0]] begin[:]
return[constant[0]]
... | keyword[def] identifier[showAnns] ( identifier[self] , identifier[anns] ):
literal[string]
keyword[if] identifier[len] ( identifier[anns] )== literal[int] :
keyword[return] literal[int]
keyword[if] literal[string] keyword[in] identifier[anns] [ literal[int] ] keyword[or]... | def showAnns(self, anns):
"""
Display the specified annotations.
:param anns (array of object): annotations to display
:return: None
"""
if len(anns) == 0:
return 0 # depends on [control=['if'], data=[]]
if 'segmentation' in anns[0] or 'keypoints' in anns[0]:
... |
def Parse(self, stat, unused_knowledge_base):
"""Parse the key currentcontrolset output."""
value = stat.registry_data.GetValue()
if not str(value).isdigit() or int(value) > 999 or int(value) < 0:
raise parser.ParseError(
"Invalid value for CurrentControlSet key %s" % value)
yield rdfva... | def function[Parse, parameter[self, stat, unused_knowledge_base]]:
constant[Parse the key currentcontrolset output.]
variable[value] assign[=] call[name[stat].registry_data.GetValue, parameter[]]
if <ast.BoolOp object at 0x7da1b1b6d780> begin[:]
<ast.Raise object at 0x7da1b1b46830>
... | keyword[def] identifier[Parse] ( identifier[self] , identifier[stat] , identifier[unused_knowledge_base] ):
literal[string]
identifier[value] = identifier[stat] . identifier[registry_data] . identifier[GetValue] ()
keyword[if] keyword[not] identifier[str] ( identifier[value] ). identifier[isdigit] ... | def Parse(self, stat, unused_knowledge_base):
"""Parse the key currentcontrolset output."""
value = stat.registry_data.GetValue()
if not str(value).isdigit() or int(value) > 999 or int(value) < 0:
raise parser.ParseError('Invalid value for CurrentControlSet key %s' % value) # depends on [control=['... |
def buildTransaction(self, transaction=None):
"""
Build the transaction dictionary without sending
"""
if transaction is None:
built_transaction = {}
else:
built_transaction = dict(**transaction)
self.check_forbidden_keys_in_transaction(built_... | def function[buildTransaction, parameter[self, transaction]]:
constant[
Build the transaction dictionary without sending
]
if compare[name[transaction] is constant[None]] begin[:]
variable[built_transaction] assign[=] dictionary[[], []]
if compare[name[self].web3.... | keyword[def] identifier[buildTransaction] ( identifier[self] , identifier[transaction] = keyword[None] ):
literal[string]
keyword[if] identifier[transaction] keyword[is] keyword[None] :
identifier[built_transaction] ={}
keyword[else] :
identifier[built_transac... | def buildTransaction(self, transaction=None):
"""
Build the transaction dictionary without sending
"""
if transaction is None:
built_transaction = {} # depends on [control=['if'], data=[]]
else:
built_transaction = dict(**transaction)
self.check_forbidden_keys_in_tra... |
def show_osm_downloader(self):
"""Show the OSM buildings downloader dialog."""
from safe.gui.tools.osm_downloader_dialog import OsmDownloaderDialog
dialog = OsmDownloaderDialog(self.iface.mainWindow(), self.iface)
# otherwise dialog is never deleted
dialog.setAttribute(Qt.WA_Del... | def function[show_osm_downloader, parameter[self]]:
constant[Show the OSM buildings downloader dialog.]
from relative_module[safe.gui.tools.osm_downloader_dialog] import module[OsmDownloaderDialog]
variable[dialog] assign[=] call[name[OsmDownloaderDialog], parameter[call[name[self].iface.mainWindow,... | keyword[def] identifier[show_osm_downloader] ( identifier[self] ):
literal[string]
keyword[from] identifier[safe] . identifier[gui] . identifier[tools] . identifier[osm_downloader_dialog] keyword[import] identifier[OsmDownloaderDialog]
identifier[dialog] = identifier[OsmDownloaderDial... | def show_osm_downloader(self):
"""Show the OSM buildings downloader dialog."""
from safe.gui.tools.osm_downloader_dialog import OsmDownloaderDialog
dialog = OsmDownloaderDialog(self.iface.mainWindow(), self.iface)
# otherwise dialog is never deleted
dialog.setAttribute(Qt.WA_DeleteOnClose, True)
... |
def endswith(string, suffix):
"""
Like str.endswith, but also checks that the string ends with the given prefixes sequence of graphemes.
str.endswith may return true for a suffix that is not visually represented as a suffix if a grapheme cluster
is initiated before the suffix starts.
>>> grapheme.... | def function[endswith, parameter[string, suffix]]:
constant[
Like str.endswith, but also checks that the string ends with the given prefixes sequence of graphemes.
str.endswith may return true for a suffix that is not visually represented as a suffix if a grapheme cluster
is initiated before the su... | keyword[def] identifier[endswith] ( identifier[string] , identifier[suffix] ):
literal[string]
identifier[expected_index] = identifier[len] ( identifier[string] )- identifier[len] ( identifier[suffix] )
keyword[return] identifier[string] . identifier[endswith] ( identifier[suffix] ) keyword[and] ide... | def endswith(string, suffix):
"""
Like str.endswith, but also checks that the string ends with the given prefixes sequence of graphemes.
str.endswith may return true for a suffix that is not visually represented as a suffix if a grapheme cluster
is initiated before the suffix starts.
>>> grapheme.... |
def _format_structured_address(address):
"""
Pretty-print address and return lat, lon tuple.
"""
latitude = address['metadata'].get('latitude')
longitude = address['metadata'].get('longitude')
return Location(
", ".join((address['delivery_line_1'], address['la... | def function[_format_structured_address, parameter[address]]:
constant[
Pretty-print address and return lat, lon tuple.
]
variable[latitude] assign[=] call[call[name[address]][constant[metadata]].get, parameter[constant[latitude]]]
variable[longitude] assign[=] call[call[name[add... | keyword[def] identifier[_format_structured_address] ( identifier[address] ):
literal[string]
identifier[latitude] = identifier[address] [ literal[string] ]. identifier[get] ( literal[string] )
identifier[longitude] = identifier[address] [ literal[string] ]. identifier[get] ( literal[string... | def _format_structured_address(address):
"""
Pretty-print address and return lat, lon tuple.
"""
latitude = address['metadata'].get('latitude')
longitude = address['metadata'].get('longitude')
return Location(', '.join((address['delivery_line_1'], address['last_line'])), (latitude, longi... |
def set_properties(self, properties, recursive=True):
"""
Adds new or modifies existing properties listed in properties
properties - is a dict which contains the property names and values to set.
Property values can be a list or tuple to set multiple values
... | def function[set_properties, parameter[self, properties, recursive]]:
constant[
Adds new or modifies existing properties listed in properties
properties - is a dict which contains the property names and values to set.
Property values can be a list or tuple to set multiple v... | keyword[def] identifier[set_properties] ( identifier[self] , identifier[properties] , identifier[recursive] = keyword[True] ):
literal[string]
keyword[if] keyword[not] identifier[properties] :
keyword[return]
identifier[MAX_SIZE] = literal[int]
keywo... | def set_properties(self, properties, recursive=True):
"""
Adds new or modifies existing properties listed in properties
properties - is a dict which contains the property names and values to set.
Property values can be a list or tuple to set multiple values
... |
def get_crypt_class(self):
"""
Get the Keyczar class to use.
The class can be customized with the ENCRYPTED_FIELD_MODE setting. By default,
this setting is DECRYPT_AND_ENCRYPT. Set this to ENCRYPT to disable decryption.
This is necessary if you are only providing public keys to ... | def function[get_crypt_class, parameter[self]]:
constant[
Get the Keyczar class to use.
The class can be customized with the ENCRYPTED_FIELD_MODE setting. By default,
this setting is DECRYPT_AND_ENCRYPT. Set this to ENCRYPT to disable decryption.
This is necessary if you are onl... | keyword[def] identifier[get_crypt_class] ( identifier[self] ):
literal[string]
identifier[crypt_type] = identifier[getattr] ( identifier[settings] , literal[string] , literal[string] )
keyword[if] identifier[crypt_type] == literal[string] :
identifier[crypt_class_name] = lite... | def get_crypt_class(self):
"""
Get the Keyczar class to use.
The class can be customized with the ENCRYPTED_FIELD_MODE setting. By default,
this setting is DECRYPT_AND_ENCRYPT. Set this to ENCRYPT to disable decryption.
This is necessary if you are only providing public keys to Keyc... |
def insertImage(page, rect, filename=None, pixmap=None, stream=None, rotate=0,
keep_proportion = True,
overlay=True):
"""Insert an image in a rectangle on the current page.
Notes:
Exactly one of filename, pixmap or stream must be provided.
Args:
rect: (rect-l... | def function[insertImage, parameter[page, rect, filename, pixmap, stream, rotate, keep_proportion, overlay]]:
constant[Insert an image in a rectangle on the current page.
Notes:
Exactly one of filename, pixmap or stream must be provided.
Args:
rect: (rect-like) where to place the source... | keyword[def] identifier[insertImage] ( identifier[page] , identifier[rect] , identifier[filename] = keyword[None] , identifier[pixmap] = keyword[None] , identifier[stream] = keyword[None] , identifier[rotate] = literal[int] ,
identifier[keep_proportion] = keyword[True] ,
identifier[overlay] = keyword[True] ):
... | def insertImage(page, rect, filename=None, pixmap=None, stream=None, rotate=0, keep_proportion=True, overlay=True):
"""Insert an image in a rectangle on the current page.
Notes:
Exactly one of filename, pixmap or stream must be provided.
Args:
rect: (rect-like) where to place the source ima... |
def validate(mcs, bases, attributes):
"""Check attributes."""
if bases[0] is object:
return None
mcs.check_model_cls(attributes)
mcs.check_include_exclude(attributes)
mcs.check_properties(attributes) | def function[validate, parameter[mcs, bases, attributes]]:
constant[Check attributes.]
if compare[call[name[bases]][constant[0]] is name[object]] begin[:]
return[constant[None]]
call[name[mcs].check_model_cls, parameter[name[attributes]]]
call[name[mcs].check_include_exclude, par... | keyword[def] identifier[validate] ( identifier[mcs] , identifier[bases] , identifier[attributes] ):
literal[string]
keyword[if] identifier[bases] [ literal[int] ] keyword[is] identifier[object] :
keyword[return] keyword[None]
identifier[mcs] . identifier[check_model_cls] (... | def validate(mcs, bases, attributes):
"""Check attributes."""
if bases[0] is object:
return None # depends on [control=['if'], data=[]]
mcs.check_model_cls(attributes)
mcs.check_include_exclude(attributes)
mcs.check_properties(attributes) |
def symbolic_Rz_matrix(symbolic_theta):
"""Matrice symbolique de rotation autour de l'axe Z"""
return sympy.Matrix([
[sympy.cos(symbolic_theta), -sympy.sin(symbolic_theta), 0],
[sympy.sin(symbolic_theta), sympy.cos(symbolic_theta), 0],
[0, 0, 1]
]) | def function[symbolic_Rz_matrix, parameter[symbolic_theta]]:
constant[Matrice symbolique de rotation autour de l'axe Z]
return[call[name[sympy].Matrix, parameter[list[[<ast.List object at 0x7da207f01330>, <ast.List object at 0x7da18fe912d0>, <ast.List object at 0x7da18fe90310>]]]]] | keyword[def] identifier[symbolic_Rz_matrix] ( identifier[symbolic_theta] ):
literal[string]
keyword[return] identifier[sympy] . identifier[Matrix] ([
[ identifier[sympy] . identifier[cos] ( identifier[symbolic_theta] ),- identifier[sympy] . identifier[sin] ( identifier[symbolic_theta] ), literal[int] ... | def symbolic_Rz_matrix(symbolic_theta):
"""Matrice symbolique de rotation autour de l'axe Z"""
return sympy.Matrix([[sympy.cos(symbolic_theta), -sympy.sin(symbolic_theta), 0], [sympy.sin(symbolic_theta), sympy.cos(symbolic_theta), 0], [0, 0, 1]]) |
def distance_to_edge(self, skydir):
"""Return the angular distance from the given direction and
the edge of the projection."""
xpix, ypix = skydir.to_pixel(self.wcs, origin=0)
deltax = np.array((xpix - self._pix_center[0]) * self._pix_size[0],
ndmin=1)
... | def function[distance_to_edge, parameter[self, skydir]]:
constant[Return the angular distance from the given direction and
the edge of the projection.]
<ast.Tuple object at 0x7da2044c21a0> assign[=] call[name[skydir].to_pixel, parameter[name[self].wcs]]
variable[deltax] assign[=] call[na... | keyword[def] identifier[distance_to_edge] ( identifier[self] , identifier[skydir] ):
literal[string]
identifier[xpix] , identifier[ypix] = identifier[skydir] . identifier[to_pixel] ( identifier[self] . identifier[wcs] , identifier[origin] = literal[int] )
identifier[deltax] = identifier[n... | def distance_to_edge(self, skydir):
"""Return the angular distance from the given direction and
the edge of the projection."""
(xpix, ypix) = skydir.to_pixel(self.wcs, origin=0)
deltax = np.array((xpix - self._pix_center[0]) * self._pix_size[0], ndmin=1)
deltay = np.array((ypix - self._pix_cente... |
def ds_extent(ds, t_srs=None):
"""Return min/max extent of dataset based on corner coordinates
xmin, ymin, xmax, ymax
If t_srs is specified, output will be converted to specified srs
"""
ul, ll, ur, lr = gt_corners(ds.GetGeoTransform(), ds.RasterXSize, ds.RasterYSize)
ds_srs = get_ds_srs(ds) ... | def function[ds_extent, parameter[ds, t_srs]]:
constant[Return min/max extent of dataset based on corner coordinates
xmin, ymin, xmax, ymax
If t_srs is specified, output will be converted to specified srs
]
<ast.Tuple object at 0x7da1b0606860> assign[=] call[name[gt_corners], parameter[cal... | keyword[def] identifier[ds_extent] ( identifier[ds] , identifier[t_srs] = keyword[None] ):
literal[string]
identifier[ul] , identifier[ll] , identifier[ur] , identifier[lr] = identifier[gt_corners] ( identifier[ds] . identifier[GetGeoTransform] (), identifier[ds] . identifier[RasterXSize] , identifier[ds] ... | def ds_extent(ds, t_srs=None):
"""Return min/max extent of dataset based on corner coordinates
xmin, ymin, xmax, ymax
If t_srs is specified, output will be converted to specified srs
"""
(ul, ll, ur, lr) = gt_corners(ds.GetGeoTransform(), ds.RasterXSize, ds.RasterYSize)
ds_srs = get_ds_srs(ds)... |
def _request(self, endpoint, data, auth=None):
"""
Make HTTP POST request to an API endpoint.
:param str endpoint: API endpoint's relative URL, eg. `/account`.
:param dict data: POST request data.
:param tuple auth: HTTP basic auth credentials.
:return: A dictionary or a ... | def function[_request, parameter[self, endpoint, data, auth]]:
constant[
Make HTTP POST request to an API endpoint.
:param str endpoint: API endpoint's relative URL, eg. `/account`.
:param dict data: POST request data.
:param tuple auth: HTTP basic auth credentials.
:retu... | keyword[def] identifier[_request] ( identifier[self] , identifier[endpoint] , identifier[data] , identifier[auth] = keyword[None] ):
literal[string]
identifier[url] = literal[string] . identifier[format] ( identifier[self] . identifier[base_url] , identifier[endpoint] )
identifier[response... | def _request(self, endpoint, data, auth=None):
"""
Make HTTP POST request to an API endpoint.
:param str endpoint: API endpoint's relative URL, eg. `/account`.
:param dict data: POST request data.
:param tuple auth: HTTP basic auth credentials.
:return: A dictionary or a stri... |
def get_type_data(name):
"""Return dictionary representation of type.
Can be used to initialize primordium.type.primitives.Type
"""
name = name.upper()
if name in ISO_LANGUAGE_CODES:
name = ISO_LANGUAGE_CODES[name]
if name in ISO_MAJOR_LANGUAGE_TYPES:
namespace = '639-2'
... | def function[get_type_data, parameter[name]]:
constant[Return dictionary representation of type.
Can be used to initialize primordium.type.primitives.Type
]
variable[name] assign[=] call[name[name].upper, parameter[]]
if compare[name[name] in name[ISO_LANGUAGE_CODES]] begin[:]
... | keyword[def] identifier[get_type_data] ( identifier[name] ):
literal[string]
identifier[name] = identifier[name] . identifier[upper] ()
keyword[if] identifier[name] keyword[in] identifier[ISO_LANGUAGE_CODES] :
identifier[name] = identifier[ISO_LANGUAGE_CODES] [ identifier[name] ]
keyw... | def get_type_data(name):
"""Return dictionary representation of type.
Can be used to initialize primordium.type.primitives.Type
"""
name = name.upper()
if name in ISO_LANGUAGE_CODES:
name = ISO_LANGUAGE_CODES[name] # depends on [control=['if'], data=['name', 'ISO_LANGUAGE_CODES']]
if ... |
def dacl(obj_name=None, obj_type='file'):
'''
Helper function for instantiating a Dacl class.
Args:
obj_name (str):
The full path to the object. If None, a blank DACL will be created.
Default is None.
obj_type (str):
The type of object. Default is 'File... | def function[dacl, parameter[obj_name, obj_type]]:
constant[
Helper function for instantiating a Dacl class.
Args:
obj_name (str):
The full path to the object. If None, a blank DACL will be created.
Default is None.
obj_type (str):
The type of objec... | keyword[def] identifier[dacl] ( identifier[obj_name] = keyword[None] , identifier[obj_type] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[HAS_WIN32] :
keyword[return]
keyword[class] identifier[Dacl] ( identifier[flags] ( keyword[False] )):
literal[str... | def dacl(obj_name=None, obj_type='file'):
"""
Helper function for instantiating a Dacl class.
Args:
obj_name (str):
The full path to the object. If None, a blank DACL will be created.
Default is None.
obj_type (str):
The type of object. Default is 'File... |
def propagate_type_and_convert_call(result, node):
'''
Propagate the types variables and convert tmp call to real call operation
'''
calls_value = {}
calls_gas = {}
call_data = []
idx = 0
# use of while len() as result can be modified during the iteration
while idx < len(result... | def function[propagate_type_and_convert_call, parameter[result, node]]:
constant[
Propagate the types variables and convert tmp call to real call operation
]
variable[calls_value] assign[=] dictionary[[], []]
variable[calls_gas] assign[=] dictionary[[], []]
variable[call_data... | keyword[def] identifier[propagate_type_and_convert_call] ( identifier[result] , identifier[node] ):
literal[string]
identifier[calls_value] ={}
identifier[calls_gas] ={}
identifier[call_data] =[]
identifier[idx] = literal[int]
keyword[while] identifier[idx] < identifier[len] ( ... | def propagate_type_and_convert_call(result, node):
"""
Propagate the types variables and convert tmp call to real call operation
"""
calls_value = {}
calls_gas = {}
call_data = []
idx = 0
# use of while len() as result can be modified during the iteration
while idx < len(result):... |
def simxAuxiliaryConsoleOpen(clientID, title, maxLines, mode, position, size, textColor, backgroundColor, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
consoleHandle = ct.c_int()
if (sys.version_info[0] == 3) and (type(title) is str):
... | def function[simxAuxiliaryConsoleOpen, parameter[clientID, title, maxLines, mode, position, size, textColor, backgroundColor, operationMode]]:
constant[
Please have a look at the function description/documentation in the V-REP user manual
]
variable[consoleHandle] assign[=] call[name[ct].c_int, ... | keyword[def] identifier[simxAuxiliaryConsoleOpen] ( identifier[clientID] , identifier[title] , identifier[maxLines] , identifier[mode] , identifier[position] , identifier[size] , identifier[textColor] , identifier[backgroundColor] , identifier[operationMode] ):
literal[string]
identifier[consoleHandle] = ... | def simxAuxiliaryConsoleOpen(clientID, title, maxLines, mode, position, size, textColor, backgroundColor, operationMode):
"""
Please have a look at the function description/documentation in the V-REP user manual
"""
consoleHandle = ct.c_int()
if sys.version_info[0] == 3 and type(title) is str:
... |
def create_stream(name, **header):
"""Create a stream for publishing messages.
All keyword arguments will be used to form the header.
"""
assert isinstance(name, basestring), name
return CreateStream(parent=None, name=name, group=False, header=header) | def function[create_stream, parameter[name]]:
constant[Create a stream for publishing messages.
All keyword arguments will be used to form the header.
]
assert[call[name[isinstance], parameter[name[name], name[basestring]]]]
return[call[name[CreateStream], parameter[]]] | keyword[def] identifier[create_stream] ( identifier[name] ,** identifier[header] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[name] , identifier[basestring] ), identifier[name]
keyword[return] identifier[CreateStream] ( identifier[parent] = keyword[None] , identifier[name]... | def create_stream(name, **header):
"""Create a stream for publishing messages.
All keyword arguments will be used to form the header.
"""
assert isinstance(name, basestring), name
return CreateStream(parent=None, name=name, group=False, header=header) |
def find(self, tag_name, params=None, fn=None, case_sensitive=False):
"""
Same as :meth:`findAll`, but without `endtags`.
You can always get them from :attr:`endtag` property.
"""
return [
x for x in self.findAll(tag_name, params, fn, case_sensitive)
if n... | def function[find, parameter[self, tag_name, params, fn, case_sensitive]]:
constant[
Same as :meth:`findAll`, but without `endtags`.
You can always get them from :attr:`endtag` property.
]
return[<ast.ListComp object at 0x7da1b16ab940>] | keyword[def] identifier[find] ( identifier[self] , identifier[tag_name] , identifier[params] = keyword[None] , identifier[fn] = keyword[None] , identifier[case_sensitive] = keyword[False] ):
literal[string]
keyword[return] [
identifier[x] keyword[for] identifier[x] keyword[in] identifi... | def find(self, tag_name, params=None, fn=None, case_sensitive=False):
"""
Same as :meth:`findAll`, but without `endtags`.
You can always get them from :attr:`endtag` property.
"""
return [x for x in self.findAll(tag_name, params, fn, case_sensitive) if not x.isEndTag()] |
def allow_request(self, request, view):
"""
Modify throttling for service users.
Updates throttling rate if the request is coming from the service user, and
defaults to UserRateThrottle's configured setting otherwise.
Updated throttling rate comes from `DEFAULT_THROTTLE_RATES` ... | def function[allow_request, parameter[self, request, view]]:
constant[
Modify throttling for service users.
Updates throttling rate if the request is coming from the service user, and
defaults to UserRateThrottle's configured setting otherwise.
Updated throttling rate comes fro... | keyword[def] identifier[allow_request] ( identifier[self] , identifier[request] , identifier[view] ):
literal[string]
identifier[service_users] = identifier[get_service_usernames] ()
keyword[if] identifier[request] . identifier[user] . identifier[username] keyword[in] identifi... | def allow_request(self, request, view):
"""
Modify throttling for service users.
Updates throttling rate if the request is coming from the service user, and
defaults to UserRateThrottle's configured setting otherwise.
Updated throttling rate comes from `DEFAULT_THROTTLE_RATES` key ... |
def get(self, key, metadata=False, sort_order=None,
sort_target=None, **kwargs):
"""Range gets the keys in the range from the key-value store.
:param key:
:param metadata:
:param sort_order: 'ascend' or 'descend' or None
:param sort_target: 'key' or 'version' or 'cre... | def function[get, parameter[self, key, metadata, sort_order, sort_target]]:
constant[Range gets the keys in the range from the key-value store.
:param key:
:param metadata:
:param sort_order: 'ascend' or 'descend' or None
:param sort_target: 'key' or 'version' or 'create' or 'mo... | keyword[def] identifier[get] ( identifier[self] , identifier[key] , identifier[metadata] = keyword[False] , identifier[sort_order] = keyword[None] ,
identifier[sort_target] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
identifier[order] = literal[int]
... | def get(self, key, metadata=False, sort_order=None, sort_target=None, **kwargs):
"""Range gets the keys in the range from the key-value store.
:param key:
:param metadata:
:param sort_order: 'ascend' or 'descend' or None
:param sort_target: 'key' or 'version' or 'create' or 'mod' or... |
def prepare_request(self, method, url, body=''):
"""Prepare the request body and headers
:returns: headers of the signed request
"""
headers = {
'Content-type': 'application/json',
}
# Note: we don't pass body to sign() since it's only for bodies that
... | def function[prepare_request, parameter[self, method, url, body]]:
constant[Prepare the request body and headers
:returns: headers of the signed request
]
variable[headers] assign[=] dictionary[[<ast.Constant object at 0x7da18f00d660>], [<ast.Constant object at 0x7da18f00d6f0>]]
... | keyword[def] identifier[prepare_request] ( identifier[self] , identifier[method] , identifier[url] , identifier[body] = literal[string] ):
literal[string]
identifier[headers] ={
literal[string] : literal[string] ,
}
identifier[uri] , identifier[s... | def prepare_request(self, method, url, body=''):
"""Prepare the request body and headers
:returns: headers of the signed request
"""
headers = {'Content-type': 'application/json'}
# Note: we don't pass body to sign() since it's only for bodies that
# are form-urlencoded. Similarly, we d... |
def get_random_email(ltd="com"):
"""Get a random email address with the given ltd.
Args:
ltd (str): The ltd to use (e.g. com).
Returns:
str: The random email.
"""
email = [
RandomInputHelper.get_random_value(6, [string.ascii_lowercase]),
... | def function[get_random_email, parameter[ltd]]:
constant[Get a random email address with the given ltd.
Args:
ltd (str): The ltd to use (e.g. com).
Returns:
str: The random email.
]
variable[email] assign[=] list[[<ast.Call object at 0x7da18bcc8a90>, <a... | keyword[def] identifier[get_random_email] ( identifier[ltd] = literal[string] ):
literal[string]
identifier[email] =[
identifier[RandomInputHelper] . identifier[get_random_value] ( literal[int] ,[ identifier[string] . identifier[ascii_lowercase] ]),
literal[string] ,
ide... | def get_random_email(ltd='com'):
"""Get a random email address with the given ltd.
Args:
ltd (str): The ltd to use (e.g. com).
Returns:
str: The random email.
"""
email = [RandomInputHelper.get_random_value(6, [string.ascii_lowercase]), '@', RandomInputHelper.g... |
def write_outro (self):
"""Write end of check message."""
self.writeln(u"<br/>")
self.write(_("That's it.")+" ")
if self.stats.number >= 0:
self.write(_n("%d link checked.", "%d links checked.",
self.stats.number) % self.stats.number)
self.w... | def function[write_outro, parameter[self]]:
constant[Write end of check message.]
call[name[self].writeln, parameter[constant[<br/>]]]
call[name[self].write, parameter[binary_operation[call[name[_], parameter[constant[That's it.]]] + constant[ ]]]]
if compare[name[self].stats.number grea... | keyword[def] identifier[write_outro] ( identifier[self] ):
literal[string]
identifier[self] . identifier[writeln] ( literal[string] )
identifier[self] . identifier[write] ( identifier[_] ( literal[string] )+ literal[string] )
keyword[if] identifier[self] . identifier[stats] . ide... | def write_outro(self):
"""Write end of check message."""
self.writeln(u'<br/>')
self.write(_("That's it.") + ' ')
if self.stats.number >= 0:
self.write(_n('%d link checked.', '%d links checked.', self.stats.number) % self.stats.number)
self.write(u' ') # depends on [control=['if'], data... |
def predict(self, data, num_iteration=None,
raw_score=False, pred_leaf=False, pred_contrib=False,
data_has_header=False, is_reshape=True, **kwargs):
"""Make a prediction.
Parameters
----------
data : string, numpy array, pandas DataFrame, H2O DataTable's ... | def function[predict, parameter[self, data, num_iteration, raw_score, pred_leaf, pred_contrib, data_has_header, is_reshape]]:
constant[Make a prediction.
Parameters
----------
data : string, numpy array, pandas DataFrame, H2O DataTable's Frame or scipy.sparse
Data source for... | keyword[def] identifier[predict] ( identifier[self] , identifier[data] , identifier[num_iteration] = keyword[None] ,
identifier[raw_score] = keyword[False] , identifier[pred_leaf] = keyword[False] , identifier[pred_contrib] = keyword[False] ,
identifier[data_has_header] = keyword[False] , identifier[is_reshape] = k... | def predict(self, data, num_iteration=None, raw_score=False, pred_leaf=False, pred_contrib=False, data_has_header=False, is_reshape=True, **kwargs):
"""Make a prediction.
Parameters
----------
data : string, numpy array, pandas DataFrame, H2O DataTable's Frame or scipy.sparse
Da... |
def remove_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles,... | def function[remove_member_roles, parameter[self, guild_id, member_id, roles]]:
constant[Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current ... | keyword[def] identifier[remove_member_roles] ( identifier[self] , identifier[guild_id] : identifier[int] , identifier[member_id] : identifier[int] , identifier[roles] : identifier[List] [ identifier[int] ]):
literal[string]
identifier[current_roles] =[ identifier[role] keyword[for] identifier[rol... | def remove_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles, and... |
def _editdistance(a, b):
""" Simple unweighted Levenshtein distance """
r0 = range(0, len(b) + 1)
r1 = [0] * (len(b) + 1)
for i in range(0, len(a)):
r1[0] = i + 1
for j in range(0, len(b)):
c = 0 if a[i] is b[j] else 1
r1[j + 1] =... | def function[_editdistance, parameter[a, b]]:
constant[ Simple unweighted Levenshtein distance ]
variable[r0] assign[=] call[name[range], parameter[constant[0], binary_operation[call[name[len], parameter[name[b]]] + constant[1]]]]
variable[r1] assign[=] binary_operation[list[[<ast.Constant objec... | keyword[def] identifier[_editdistance] ( identifier[a] , identifier[b] ):
literal[string]
identifier[r0] = identifier[range] ( literal[int] , identifier[len] ( identifier[b] )+ literal[int] )
identifier[r1] =[ literal[int] ]*( identifier[len] ( identifier[b] )+ literal[int] )
key... | def _editdistance(a, b):
""" Simple unweighted Levenshtein distance """
r0 = range(0, len(b) + 1)
r1 = [0] * (len(b) + 1)
for i in range(0, len(a)):
r1[0] = i + 1
for j in range(0, len(b)):
c = 0 if a[i] is b[j] else 1
r1[j + 1] = min(r1[j] + 1, r0[j + 1] + 1, r0[... |
def check_update ():
"""Return the following values:
(False, errmsg) - online version could not be determined
(True, None) - user has newest version
(True, (version, url string)) - update available
(True, (version, None)) - current version is newer than online version
"""
version... | def function[check_update, parameter[]]:
constant[Return the following values:
(False, errmsg) - online version could not be determined
(True, None) - user has newest version
(True, (version, url string)) - update available
(True, (version, None)) - current version is newer than onli... | keyword[def] identifier[check_update] ():
literal[string]
identifier[version] , identifier[value] = identifier[get_online_version] ()
keyword[if] identifier[version] keyword[is] keyword[None] :
keyword[return] keyword[False] , identifier[value]
keyword[if] identifier[version] ... | def check_update():
"""Return the following values:
(False, errmsg) - online version could not be determined
(True, None) - user has newest version
(True, (version, url string)) - update available
(True, (version, None)) - current version is newer than online version
"""
(version... |
def init(*args, **kwargs):
"""Returns an initialized instance of the Batch class"""
# set up cellpy logger
default_log_level = kwargs.pop("default_log_level", None)
import cellpy.log as log
log.setup_logging(custom_log_dir=prms.Paths["filelogdir"],
default_level=default_log_lev... | def function[init, parameter[]]:
constant[Returns an initialized instance of the Batch class]
variable[default_log_level] assign[=] call[name[kwargs].pop, parameter[constant[default_log_level], constant[None]]]
import module[cellpy.log] as alias[log]
call[name[log].setup_logging, parameter[]... | keyword[def] identifier[init] (* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[default_log_level] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[None] )
keyword[import] identifier[cellpy] . identifier[log] keyword[as] identifier[log]
identifier... | def init(*args, **kwargs):
"""Returns an initialized instance of the Batch class"""
# set up cellpy logger
default_log_level = kwargs.pop('default_log_level', None)
import cellpy.log as log
log.setup_logging(custom_log_dir=prms.Paths['filelogdir'], default_level=default_log_level)
b = Batch(*arg... |
def get_compatible_systems(self, id_or_uri):
"""
Retrieves a collection of all storage systems that is applicable to this storage volume template.
Args:
id_or_uri:
Can be either the power device id or the uri
Returns:
list: Storage systems.
... | def function[get_compatible_systems, parameter[self, id_or_uri]]:
constant[
Retrieves a collection of all storage systems that is applicable to this storage volume template.
Args:
id_or_uri:
Can be either the power device id or the uri
Returns:
l... | keyword[def] identifier[get_compatible_systems] ( identifier[self] , identifier[id_or_uri] ):
literal[string]
identifier[uri] = identifier[self] . identifier[_client] . identifier[build_uri] ( identifier[id_or_uri] )+ literal[string]
keyword[return] identifier[self] . identifier[_client]... | def get_compatible_systems(self, id_or_uri):
"""
Retrieves a collection of all storage systems that is applicable to this storage volume template.
Args:
id_or_uri:
Can be either the power device id or the uri
Returns:
list: Storage systems.
"... |
def make_random_client_id(self):
"""
Returns a random client identifier
"""
if PY2:
return ('py_%s' %
base64.b64encode(str(random.randint(1, 0x40000000))))
else:
return ('py_%s' %
base64.b64encode(bytes(str(random.ra... | def function[make_random_client_id, parameter[self]]:
constant[
Returns a random client identifier
]
if name[PY2] begin[:]
return[binary_operation[constant[py_%s] <ast.Mod object at 0x7da2590d6920> call[name[base64].b64encode, parameter[call[name[str], parameter[call[name[random]... | keyword[def] identifier[make_random_client_id] ( identifier[self] ):
literal[string]
keyword[if] identifier[PY2] :
keyword[return] ( literal[string] %
identifier[base64] . identifier[b64encode] ( identifier[str] ( identifier[random] . identifier[randint] ( literal[int] , ... | def make_random_client_id(self):
"""
Returns a random client identifier
"""
if PY2:
return 'py_%s' % base64.b64encode(str(random.randint(1, 1073741824))) # depends on [control=['if'], data=[]]
else:
return 'py_%s' % base64.b64encode(bytes(str(random.randint(1, 1073741824)), ... |
def build_tensor_serving_input_receiver_fn(shape, dtype=tf.float32,
batch_size=1):
"""Returns a input_receiver_fn that can be used during serving.
This expects examples to come through as float tensors, and simply
wraps them as TensorServingInputReceivers.
Arguably, ... | def function[build_tensor_serving_input_receiver_fn, parameter[shape, dtype, batch_size]]:
constant[Returns a input_receiver_fn that can be used during serving.
This expects examples to come through as float tensors, and simply
wraps them as TensorServingInputReceivers.
Arguably, this should live in tf.... | keyword[def] identifier[build_tensor_serving_input_receiver_fn] ( identifier[shape] , identifier[dtype] = identifier[tf] . identifier[float32] ,
identifier[batch_size] = literal[int] ):
literal[string]
keyword[def] identifier[serving_input_receiver_fn] ():
identifier[features] = identifier[tf] . iden... | def build_tensor_serving_input_receiver_fn(shape, dtype=tf.float32, batch_size=1):
"""Returns a input_receiver_fn that can be used during serving.
This expects examples to come through as float tensors, and simply
wraps them as TensorServingInputReceivers.
Arguably, this should live in tf.estimator.export. ... |
def default_is_local(hadoop_conf=None, hadoop_home=None):
"""\
Is Hadoop configured to use the local file system?
By default, it is. A DFS must be explicitly configured.
"""
params = pydoop.hadoop_params(hadoop_conf, hadoop_home)
for k in 'fs.defaultFS', 'fs.default.name':
if not params... | def function[default_is_local, parameter[hadoop_conf, hadoop_home]]:
constant[ Is Hadoop configured to use the local file system?
By default, it is. A DFS must be explicitly configured.
]
variable[params] assign[=] call[name[pydoop].hadoop_params, parameter[name[hadoop_conf], name[hadoop_hom... | keyword[def] identifier[default_is_local] ( identifier[hadoop_conf] = keyword[None] , identifier[hadoop_home] = keyword[None] ):
literal[string]
identifier[params] = identifier[pydoop] . identifier[hadoop_params] ( identifier[hadoop_conf] , identifier[hadoop_home] )
keyword[for] identifier[k] keywor... | def default_is_local(hadoop_conf=None, hadoop_home=None):
""" Is Hadoop configured to use the local file system?
By default, it is. A DFS must be explicitly configured.
"""
params = pydoop.hadoop_params(hadoop_conf, hadoop_home)
for k in ('fs.defaultFS', 'fs.default.name'):
if not params... |
def _set_default_value(dict_obj, keys, value):
"""Setea valor en diccionario anidado, siguiendo lista de keys.
Args:
dict_obj (dict): Un diccionario anidado.
keys (list): Una lista de keys para navegar el diccionario.
value (any): Un valor para reemplazar.
"""
variable = dict_ob... | def function[_set_default_value, parameter[dict_obj, keys, value]]:
constant[Setea valor en diccionario anidado, siguiendo lista de keys.
Args:
dict_obj (dict): Un diccionario anidado.
keys (list): Una lista de keys para navegar el diccionario.
value (any): Un valor para reemplazar.... | keyword[def] identifier[_set_default_value] ( identifier[dict_obj] , identifier[keys] , identifier[value] ):
literal[string]
identifier[variable] = identifier[dict_obj]
keyword[if] identifier[len] ( identifier[keys] )== literal[int] :
keyword[if] keyword[not] identifier[variable] . ident... | def _set_default_value(dict_obj, keys, value):
"""Setea valor en diccionario anidado, siguiendo lista de keys.
Args:
dict_obj (dict): Un diccionario anidado.
keys (list): Una lista de keys para navegar el diccionario.
value (any): Un valor para reemplazar.
"""
variable = dict_ob... |
def vm_diskstats(vm_=None, **kwargs):
'''
Return disk usage counters used by the vms on this hyper in a
list of dicts:
:param vm_: domain name
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding... | def function[vm_diskstats, parameter[vm_]]:
constant[
Return disk usage counters used by the vms on this hyper in a
list of dicts:
:param vm_: domain name
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect ... | keyword[def] identifier[vm_diskstats] ( identifier[vm_] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[def] identifier[get_disk_devs] ( identifier[dom] ):
literal[string]
identifier[doc] = identifier[ElementTree] . identifier[fromstring] ( identifier[get_xml] ( identi... | def vm_diskstats(vm_=None, **kwargs):
"""
Return disk usage counters used by the vms on this hyper in a
list of dicts:
:param vm_: domain name
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding... |
def import_path_from_file(filename, as_list=False):
'''Returns a tuple of the import path and root module directory for the
supplied file.
'''
module_path = []
basename = os.path.splitext(os.path.basename(filename))[0]
if basename != '__init__':
module_path.append(basename)
dirname ... | def function[import_path_from_file, parameter[filename, as_list]]:
constant[Returns a tuple of the import path and root module directory for the
supplied file.
]
variable[module_path] assign[=] list[[]]
variable[basename] assign[=] call[call[name[os].path.splitext, parameter[call[name[os... | keyword[def] identifier[import_path_from_file] ( identifier[filename] , identifier[as_list] = keyword[False] ):
literal[string]
identifier[module_path] =[]
identifier[basename] = identifier[os] . identifier[path] . identifier[splitext] ( identifier[os] . identifier[path] . identifier[basename] ( ident... | def import_path_from_file(filename, as_list=False):
"""Returns a tuple of the import path and root module directory for the
supplied file.
"""
module_path = []
basename = os.path.splitext(os.path.basename(filename))[0]
if basename != '__init__':
module_path.append(basename) # depends on... |
def set_approvers(self, approver_ids=[], approver_group_ids=[], **kwargs):
"""Change MR-level allowed approvers and approver groups.
Args:
approver_ids (list): User IDs that can approve MRs
approver_group_ids (list): Group IDs whose members can approve MRs
Raises:
... | def function[set_approvers, parameter[self, approver_ids, approver_group_ids]]:
constant[Change MR-level allowed approvers and approver groups.
Args:
approver_ids (list): User IDs that can approve MRs
approver_group_ids (list): Group IDs whose members can approve MRs
Ra... | keyword[def] identifier[set_approvers] ( identifier[self] , identifier[approver_ids] =[], identifier[approver_group_ids] =[],** identifier[kwargs] ):
literal[string]
identifier[path] = literal[string] %( identifier[self] . identifier[_parent] . identifier[manager] . identifier[path] ,
iden... | def set_approvers(self, approver_ids=[], approver_group_ids=[], **kwargs):
"""Change MR-level allowed approvers and approver groups.
Args:
approver_ids (list): User IDs that can approve MRs
approver_group_ids (list): Group IDs whose members can approve MRs
Raises:
... |
async def open(self) -> 'HolderProver':
"""
Explicit entry. Perform ancestor opening operations,
then parse cache from archive if so configured, and
synchronize revocation registry to tails tree content.
:return: current object
"""
LOGGER.debug('HolderProver.ope... | <ast.AsyncFunctionDef object at 0x7da18f58cd90> | keyword[async] keyword[def] identifier[open] ( identifier[self] )-> literal[string] :
literal[string]
identifier[LOGGER] . identifier[debug] ( literal[string] )
keyword[await] identifier[super] (). identifier[open] ()
keyword[if] identifier[self] . identifier[config] . identi... | async def open(self) -> 'HolderProver':
"""
Explicit entry. Perform ancestor opening operations,
then parse cache from archive if so configured, and
synchronize revocation registry to tails tree content.
:return: current object
"""
LOGGER.debug('HolderProver.open >>>')
... |
def is_full(self):
"""
:return:
"""
if self.cache.currsize == self.cache.maxsize:
return True
return False | def function[is_full, parameter[self]]:
constant[
:return:
]
if compare[name[self].cache.currsize equal[==] name[self].cache.maxsize] begin[:]
return[constant[True]]
return[constant[False]] | keyword[def] identifier[is_full] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[cache] . identifier[currsize] == identifier[self] . identifier[cache] . identifier[maxsize] :
keyword[return] keyword[True]
keyword[return] keyword[False] | def is_full(self):
"""
:return:
"""
if self.cache.currsize == self.cache.maxsize:
return True # depends on [control=['if'], data=[]]
return False |
def cases(store, case_query, limit=100):
"""Preprocess case objects.
Add the necessary information to display the 'cases' view
Args:
store(adapter.MongoAdapter)
case_query(pymongo.Cursor)
limit(int): Maximum number of cases to display
Returns:
data(dict): includes the ... | def function[cases, parameter[store, case_query, limit]]:
constant[Preprocess case objects.
Add the necessary information to display the 'cases' view
Args:
store(adapter.MongoAdapter)
case_query(pymongo.Cursor)
limit(int): Maximum number of cases to display
Returns:
... | keyword[def] identifier[cases] ( identifier[store] , identifier[case_query] , identifier[limit] = literal[int] ):
literal[string]
identifier[case_groups] ={ identifier[status] :[] keyword[for] identifier[status] keyword[in] identifier[CASE_STATUSES] }
keyword[for] identifier[case_obj] keyword[in... | def cases(store, case_query, limit=100):
"""Preprocess case objects.
Add the necessary information to display the 'cases' view
Args:
store(adapter.MongoAdapter)
case_query(pymongo.Cursor)
limit(int): Maximum number of cases to display
Returns:
data(dict): includes the ... |
def _writeText(self, image, text, pos):
"""Write morphed text in Image object."""
offset = 0
x, y = pos
for c in text:
# Write letter
c_size = self.font.getsize(c)
c_image = Image.new('RGBA', c_size, (0, 0, 0, 0))
c_draw = ImageDraw.Draw(c... | def function[_writeText, parameter[self, image, text, pos]]:
constant[Write morphed text in Image object.]
variable[offset] assign[=] constant[0]
<ast.Tuple object at 0x7da1b1b7d300> assign[=] name[pos]
for taget[name[c]] in starred[name[text]] begin[:]
variable[c_size] a... | keyword[def] identifier[_writeText] ( identifier[self] , identifier[image] , identifier[text] , identifier[pos] ):
literal[string]
identifier[offset] = literal[int]
identifier[x] , identifier[y] = identifier[pos]
keyword[for] identifier[c] keyword[in] identifier[text] :
... | def _writeText(self, image, text, pos):
"""Write morphed text in Image object."""
offset = 0
(x, y) = pos
for c in text:
# Write letter
c_size = self.font.getsize(c)
c_image = Image.new('RGBA', c_size, (0, 0, 0, 0))
c_draw = ImageDraw.Draw(c_image)
c_draw.text((0,... |
def sort_js_files(js_files):
"""Sorts JavaScript files in `js_files`.
It sorts JavaScript files in a given `js_files`
into source files, mock files and spec files based on file extension.
Output:
* sources: source files for production. The order of source files
is significant and should be... | def function[sort_js_files, parameter[js_files]]:
constant[Sorts JavaScript files in `js_files`.
It sorts JavaScript files in a given `js_files`
into source files, mock files and spec files based on file extension.
Output:
* sources: source files for production. The order of source files
... | keyword[def] identifier[sort_js_files] ( identifier[js_files] ):
literal[string]
identifier[modules] =[ identifier[f] keyword[for] identifier[f] keyword[in] identifier[js_files] keyword[if] identifier[f] . identifier[endswith] ( identifier[MODULE_EXT] )]
identifier[mocks] =[ identifier[f] keywo... | def sort_js_files(js_files):
"""Sorts JavaScript files in `js_files`.
It sorts JavaScript files in a given `js_files`
into source files, mock files and spec files based on file extension.
Output:
* sources: source files for production. The order of source files
is significant and should be... |
def cfg_factory(filename):
"""Config Factory"""
try:
# try to load config as yaml file.
with open(filename, 'rb') as stream:
return yaml.load(stream)
except StandardError as error:
# In case of error we use the **__argpi__** builtin to exit from
# script
_... | def function[cfg_factory, parameter[filename]]:
constant[Config Factory]
<ast.Try object at 0x7da18f813670> | keyword[def] identifier[cfg_factory] ( identifier[filename] ):
literal[string]
keyword[try] :
keyword[with] identifier[open] ( identifier[filename] , literal[string] ) keyword[as] identifier[stream] :
keyword[return] identifier[yaml] . identifier[load] ( identifier[stream] )
... | def cfg_factory(filename):
"""Config Factory"""
try:
# try to load config as yaml file.
with open(filename, 'rb') as stream:
return yaml.load(stream) # depends on [control=['with'], data=['stream']] # depends on [control=['try'], data=[]]
except StandardError as error:
... |
def _iter_config_props(cls):
"""Iterate over all ConfigProperty attributes, yielding (attr_name, config_property) """
props = inspect.getmembers(cls, lambda a: isinstance(a, ConfigProperty))
for attr_name, config_prop in props:
yield attr_name, config_prop | def function[_iter_config_props, parameter[cls]]:
constant[Iterate over all ConfigProperty attributes, yielding (attr_name, config_property) ]
variable[props] assign[=] call[name[inspect].getmembers, parameter[name[cls], <ast.Lambda object at 0x7da1b24baad0>]]
for taget[tuple[[<ast.Name object a... | keyword[def] identifier[_iter_config_props] ( identifier[cls] ):
literal[string]
identifier[props] = identifier[inspect] . identifier[getmembers] ( identifier[cls] , keyword[lambda] identifier[a] : identifier[isinstance] ( identifier[a] , identifier[ConfigProperty] ))
keyword[for] identi... | def _iter_config_props(cls):
"""Iterate over all ConfigProperty attributes, yielding (attr_name, config_property) """
props = inspect.getmembers(cls, lambda a: isinstance(a, ConfigProperty))
for (attr_name, config_prop) in props:
yield (attr_name, config_prop) # depends on [control=['for'], data=[]... |
def extract_intro_and_title(filename, docstring):
""" Extract the first paragraph of module-level docstring. max:95 char"""
# lstrip is just in case docstring has a '\n\n' at the beginning
paragraphs = docstring.lstrip().split('\n\n')
# remove comments and other syntax like `.. _link:`
paragraphs =... | def function[extract_intro_and_title, parameter[filename, docstring]]:
constant[ Extract the first paragraph of module-level docstring. max:95 char]
variable[paragraphs] assign[=] call[call[name[docstring].lstrip, parameter[]].split, parameter[constant[
]]]
variable[paragraphs] assign[=] <ast.L... | keyword[def] identifier[extract_intro_and_title] ( identifier[filename] , identifier[docstring] ):
literal[string]
identifier[paragraphs] = identifier[docstring] . identifier[lstrip] (). identifier[split] ( literal[string] )
identifier[paragraphs] =[ identifier[p] keyword[for] identifier[... | def extract_intro_and_title(filename, docstring):
""" Extract the first paragraph of module-level docstring. max:95 char"""
# lstrip is just in case docstring has a '\n\n' at the beginning
paragraphs = docstring.lstrip().split('\n\n')
# remove comments and other syntax like `.. _link:`
paragraphs = ... |
def configure(name, path=None):
""" Configure logging and return a logger and the location of its logging
configuration file.
This function expects:
+ A Splunk app directory structure::
<app-root>
bin
...
default
...
local
... | def function[configure, parameter[name, path]]:
constant[ Configure logging and return a logger and the location of its logging
configuration file.
This function expects:
+ A Splunk app directory structure::
<app-root>
bin
...
default
... | keyword[def] identifier[configure] ( identifier[name] , identifier[path] = keyword[None] ):
literal[string]
identifier[app_directory] = identifier[os] . identifier[path] . identifier[dirname] ( identifier[os] . identifier[path] . identifier[dirname] ( identifier[os] . identifier[path] . identifier[realpath... | def configure(name, path=None):
""" Configure logging and return a logger and the location of its logging
configuration file.
This function expects:
+ A Splunk app directory structure::
<app-root>
bin
...
default
...
local
... |
def _make_instance(cls, element_class, webelement):
"""
Firefox uses another implementation of element. This method
switch base of wrapped element to firefox one.
"""
if isinstance(webelement, FirefoxWebElement):
element_class = copy.deepcopy(element_class)
... | def function[_make_instance, parameter[cls, element_class, webelement]]:
constant[
Firefox uses another implementation of element. This method
switch base of wrapped element to firefox one.
]
if call[name[isinstance], parameter[name[webelement], name[FirefoxWebElement]]] begin[:]... | keyword[def] identifier[_make_instance] ( identifier[cls] , identifier[element_class] , identifier[webelement] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[webelement] , identifier[FirefoxWebElement] ):
identifier[element_class] = identifier[copy] . identifier[de... | def _make_instance(cls, element_class, webelement):
"""
Firefox uses another implementation of element. This method
switch base of wrapped element to firefox one.
"""
if isinstance(webelement, FirefoxWebElement):
element_class = copy.deepcopy(element_class)
element_class.... |
def deepcopy_sqla_objects(
startobjs: List[object],
session: Session,
flush: bool = True,
debug: bool = False,
debug_walk: bool = True,
debug_rewrite_rel: bool = False,
objmap: Dict[object, object] = None) -> None:
"""
Makes a copy of the specified SQLAlch... | def function[deepcopy_sqla_objects, parameter[startobjs, session, flush, debug, debug_walk, debug_rewrite_rel, objmap]]:
constant[
Makes a copy of the specified SQLAlchemy ORM objects, inserting them into a
new session.
This function operates in several passes:
1. Walk the ORM tree through all... | keyword[def] identifier[deepcopy_sqla_objects] (
identifier[startobjs] : identifier[List] [ identifier[object] ],
identifier[session] : identifier[Session] ,
identifier[flush] : identifier[bool] = keyword[True] ,
identifier[debug] : identifier[bool] = keyword[False] ,
identifier[debug_walk] : identifier[bool] = ... | def deepcopy_sqla_objects(startobjs: List[object], session: Session, flush: bool=True, debug: bool=False, debug_walk: bool=True, debug_rewrite_rel: bool=False, objmap: Dict[object, object]=None) -> None:
"""
Makes a copy of the specified SQLAlchemy ORM objects, inserting them into a
new session.
This f... |
async def remove_ssh_key(self, user, key):
"""Remove a public SSH key(s) from this model.
:param str key: Full ssh key
:param str user: Juju user to which the key is registered
"""
key_facade = client.KeyManagerFacade.from_connection(self.connection())
key = base64.b64d... | <ast.AsyncFunctionDef object at 0x7da1b0ef9810> | keyword[async] keyword[def] identifier[remove_ssh_key] ( identifier[self] , identifier[user] , identifier[key] ):
literal[string]
identifier[key_facade] = identifier[client] . identifier[KeyManagerFacade] . identifier[from_connection] ( identifier[self] . identifier[connection] ())
identi... | async def remove_ssh_key(self, user, key):
"""Remove a public SSH key(s) from this model.
:param str key: Full ssh key
:param str user: Juju user to which the key is registered
"""
key_facade = client.KeyManagerFacade.from_connection(self.connection())
key = base64.b64decode(bytes(... |
def create(data, cert, pkey, flags=Flags.BINARY, certs=None):
"""
Creates SignedData message by signing data with pkey and
certificate.
@param data - data to sign
@param cert - signer's certificate
@param pkey - pkey object with private key to sign
... | def function[create, parameter[data, cert, pkey, flags, certs]]:
constant[
Creates SignedData message by signing data with pkey and
certificate.
@param data - data to sign
@param cert - signer's certificate
@param pkey - pkey object with private key t... | keyword[def] identifier[create] ( identifier[data] , identifier[cert] , identifier[pkey] , identifier[flags] = identifier[Flags] . identifier[BINARY] , identifier[certs] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[pkey] . identifier[cansign] :
keyword[raise... | def create(data, cert, pkey, flags=Flags.BINARY, certs=None):
"""
Creates SignedData message by signing data with pkey and
certificate.
@param data - data to sign
@param cert - signer's certificate
@param pkey - pkey object with private key to sign
... |
def electric_field_amplitude_top(P, a, Omega=1e6, units="ad-hoc"):
"""Return the amplitude of the electric field for a top hat beam.
This is the amplitude of a laser beam of power P (in Watts) and a top-hat\
intensity distribution of radius a (in meters). The value of E0 is given in\
rescaled units acco... | def function[electric_field_amplitude_top, parameter[P, a, Omega, units]]:
constant[Return the amplitude of the electric field for a top hat beam.
This is the amplitude of a laser beam of power P (in Watts) and a top-hat intensity distribution of radius a (in meters). The value of E0 is given in rescaled u... | keyword[def] identifier[electric_field_amplitude_top] ( identifier[P] , identifier[a] , identifier[Omega] = literal[int] , identifier[units] = literal[string] ):
literal[string]
identifier[e0] = identifier[hbar] * identifier[Omega] /( identifier[e] * identifier[a0] )
identifier[E0] = identifier[sqr... | def electric_field_amplitude_top(P, a, Omega=1000000.0, units='ad-hoc'):
"""Return the amplitude of the electric field for a top hat beam.
This is the amplitude of a laser beam of power P (in Watts) and a top-hat intensity distribution of radius a (in meters). The value of E0 is given in rescaled units accordi... |
def input(self, data):
"""Reset the lexer and feed in new input.
:param data:
String of input data.
"""
# input(..) doesn't reset the lineno. We have to do that manually.
self._lexer.lineno = 1
return self._lexer.input(data) | def function[input, parameter[self, data]]:
constant[Reset the lexer and feed in new input.
:param data:
String of input data.
]
name[self]._lexer.lineno assign[=] constant[1]
return[call[name[self]._lexer.input, parameter[name[data]]]] | keyword[def] identifier[input] ( identifier[self] , identifier[data] ):
literal[string]
identifier[self] . identifier[_lexer] . identifier[lineno] = literal[int]
keyword[return] identifier[self] . identifier[_lexer] . identifier[input] ( identifier[data] ) | def input(self, data):
"""Reset the lexer and feed in new input.
:param data:
String of input data.
"""
# input(..) doesn't reset the lineno. We have to do that manually.
self._lexer.lineno = 1
return self._lexer.input(data) |
def create_user(server_context, email, container_path=None, send_email=False):
"""
Create new account
:param server_context: A LabKey server context. See utils.create_server_context.
:param email:
:param container_path:
:param send_email: true to send email notification to user
:return:
... | def function[create_user, parameter[server_context, email, container_path, send_email]]:
constant[
Create new account
:param server_context: A LabKey server context. See utils.create_server_context.
:param email:
:param container_path:
:param send_email: true to send email notification to us... | keyword[def] identifier[create_user] ( identifier[server_context] , identifier[email] , identifier[container_path] = keyword[None] , identifier[send_email] = keyword[False] ):
literal[string]
identifier[url] = identifier[server_context] . identifier[build_url] ( identifier[security_controller] , literal[st... | def create_user(server_context, email, container_path=None, send_email=False):
"""
Create new account
:param server_context: A LabKey server context. See utils.create_server_context.
:param email:
:param container_path:
:param send_email: true to send email notification to user
:return:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.