code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def parse_line(string):
"""Parse a single string as traceback line"""
match = line_regexp().match(string)
if match:
matches = match.groupdict()
line_number = matches['line_number']
path_to_python = matches['path_to_python']
spaceless_path_to_python = matches['spaceless_path_t... | def function[parse_line, parameter[string]]:
constant[Parse a single string as traceback line]
variable[match] assign[=] call[call[name[line_regexp], parameter[]].match, parameter[name[string]]]
if name[match] begin[:]
variable[matches] assign[=] call[name[match].groupdict, param... | keyword[def] identifier[parse_line] ( identifier[string] ):
literal[string]
identifier[match] = identifier[line_regexp] (). identifier[match] ( identifier[string] )
keyword[if] identifier[match] :
identifier[matches] = identifier[match] . identifier[groupdict] ()
identifier[line_num... | def parse_line(string):
"""Parse a single string as traceback line"""
match = line_regexp().match(string)
if match:
matches = match.groupdict()
line_number = matches['line_number']
path_to_python = matches['path_to_python']
spaceless_path_to_python = matches['spaceless_path_t... |
def parse_second_row(row, url):
"""
Static method that parses a given table row element by using helper methods `Parser.parse_category_subcategory_and_or_quality`,
`Parser.parse_torrent_link` and scrapping torrent's category, subcategory, quality, language, user, user url, torrent link, size,
... | def function[parse_second_row, parameter[row, url]]:
constant[
Static method that parses a given table row element by using helper methods `Parser.parse_category_subcategory_and_or_quality`,
`Parser.parse_torrent_link` and scrapping torrent's category, subcategory, quality, language, user, user ... | keyword[def] identifier[parse_second_row] ( identifier[row] , identifier[url] ):
literal[string]
identifier[tags] = identifier[row] . identifier[findall] ( literal[string] )
identifier[category] , identifier[subcategory] , identifier[quality] , identifier[language] = identifier[Parser] . i... | def parse_second_row(row, url):
"""
Static method that parses a given table row element by using helper methods `Parser.parse_category_subcategory_and_or_quality`,
`Parser.parse_torrent_link` and scrapping torrent's category, subcategory, quality, language, user, user url, torrent link, size,
... |
def create_calc_dh_d_shape(estimator):
"""
Return the function that can be used in the various gradient and hessian
calculations to calculate the derivative of the transformation with respect
to the shape parameters.
Parameters
----------
estimator : an instance of the estimation.LogitTypeE... | def function[create_calc_dh_d_shape, parameter[estimator]]:
constant[
Return the function that can be used in the various gradient and hessian
calculations to calculate the derivative of the transformation with respect
to the shape parameters.
Parameters
----------
estimator : an instan... | keyword[def] identifier[create_calc_dh_d_shape] ( identifier[estimator] ):
literal[string]
identifier[dh_d_shape] = identifier[estimator] . identifier[rows_to_alts] . identifier[copy] ()
identifier[calc_dh_d_shape] = identifier[partial] ( identifier[_uneven_transform_deriv_shape] ,
... | def create_calc_dh_d_shape(estimator):
"""
Return the function that can be used in the various gradient and hessian
calculations to calculate the derivative of the transformation with respect
to the shape parameters.
Parameters
----------
estimator : an instance of the estimation.LogitTypeE... |
def access_vlan(self, inter_type, inter, vlan_id):
"""
Add a L2 Interface to a specific VLAN.
Args:
inter_type: The type of interface you want to configure. Ex.
tengigabitethernet, gigabitethernet, fortygigabitethernet.
inter: The ID for the interface you... | def function[access_vlan, parameter[self, inter_type, inter, vlan_id]]:
constant[
Add a L2 Interface to a specific VLAN.
Args:
inter_type: The type of interface you want to configure. Ex.
tengigabitethernet, gigabitethernet, fortygigabitethernet.
inter: T... | keyword[def] identifier[access_vlan] ( identifier[self] , identifier[inter_type] , identifier[inter] , identifier[vlan_id] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[interface] = identifier[ET] . identifier[SubElement] ( iden... | def access_vlan(self, inter_type, inter, vlan_id):
"""
Add a L2 Interface to a specific VLAN.
Args:
inter_type: The type of interface you want to configure. Ex.
tengigabitethernet, gigabitethernet, fortygigabitethernet.
inter: The ID for the interface you wan... |
def translate(self, dx, dy):
"""
Move the polygons from one place to another
Parameters
----------
dx : number
distance to move in the x-direction
dy : number
distance to move in the y-direction
Returns
-------
out : ``Pol... | def function[translate, parameter[self, dx, dy]]:
constant[
Move the polygons from one place to another
Parameters
----------
dx : number
distance to move in the x-direction
dy : number
distance to move in the y-direction
Returns
... | keyword[def] identifier[translate] ( identifier[self] , identifier[dx] , identifier[dy] ):
literal[string]
identifier[vec] = identifier[numpy] . identifier[array] (( identifier[dx] , identifier[dy] ))
identifier[self] . identifier[polygons] =[ identifier[points] + identifier[vec] keyword[... | def translate(self, dx, dy):
"""
Move the polygons from one place to another
Parameters
----------
dx : number
distance to move in the x-direction
dy : number
distance to move in the y-direction
Returns
-------
out : ``Polygon... |
def create_from_response_pdu(resp_pdu):
""" Create instance from response PDU.
:param resp_pdu: Byte array with request PDU.
:return: Instance of :class:`WriteSingleRegister`.
"""
write_single_register = WriteSingleRegister()
address, value = struct.unpack('>H' + conf.T... | def function[create_from_response_pdu, parameter[resp_pdu]]:
constant[ Create instance from response PDU.
:param resp_pdu: Byte array with request PDU.
:return: Instance of :class:`WriteSingleRegister`.
]
variable[write_single_register] assign[=] call[name[WriteSingleRegister], ... | keyword[def] identifier[create_from_response_pdu] ( identifier[resp_pdu] ):
literal[string]
identifier[write_single_register] = identifier[WriteSingleRegister] ()
identifier[address] , identifier[value] = identifier[struct] . identifier[unpack] ( literal[string] + identifier[conf] . ident... | def create_from_response_pdu(resp_pdu):
""" Create instance from response PDU.
:param resp_pdu: Byte array with request PDU.
:return: Instance of :class:`WriteSingleRegister`.
"""
write_single_register = WriteSingleRegister()
(address, value) = struct.unpack('>H' + conf.TYPE_CHAR, r... |
def json_numpy_obj_hook(dct):
"""Decodes a previously encoded numpy ndarray with proper shape and dtype.
And decompresses the data with blosc
:param dct: (dict) json encoded ndarray
:return: (ndarray) if input was an encoded ndarray
"""
if isinstance(dct, dict) and '__ndarray__' in dct:
... | def function[json_numpy_obj_hook, parameter[dct]]:
constant[Decodes a previously encoded numpy ndarray with proper shape and dtype.
And decompresses the data with blosc
:param dct: (dict) json encoded ndarray
:return: (ndarray) if input was an encoded ndarray
]
if <ast.BoolOp object at ... | keyword[def] identifier[json_numpy_obj_hook] ( identifier[dct] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[dct] , identifier[dict] ) keyword[and] literal[string] keyword[in] identifier[dct] :
identifier[array] = identifier[dct] [ literal[string] ]
keywo... | def json_numpy_obj_hook(dct):
"""Decodes a previously encoded numpy ndarray with proper shape and dtype.
And decompresses the data with blosc
:param dct: (dict) json encoded ndarray
:return: (ndarray) if input was an encoded ndarray
"""
if isinstance(dct, dict) and '__ndarray__' in dct:
... |
def __appendActivities(self, periodicActivities):
"""
periodicActivities: A sequence of PeriodicActivityRequest elements
"""
for req in periodicActivities:
act = self.Activity(repeating=req.repeating,
period=req.period,
cb=req.cb,
... | def function[__appendActivities, parameter[self, periodicActivities]]:
constant[
periodicActivities: A sequence of PeriodicActivityRequest elements
]
for taget[name[req]] in starred[name[periodicActivities]] begin[:]
variable[act] assign[=] call[name[self].Activity, parameter[]]
... | keyword[def] identifier[__appendActivities] ( identifier[self] , identifier[periodicActivities] ):
literal[string]
keyword[for] identifier[req] keyword[in] identifier[periodicActivities] :
identifier[act] = identifier[self] . identifier[Activity] ( identifier[repeating] = identifier[req] . ident... | def __appendActivities(self, periodicActivities):
"""
periodicActivities: A sequence of PeriodicActivityRequest elements
"""
for req in periodicActivities:
act = self.Activity(repeating=req.repeating, period=req.period, cb=req.cb, iteratorHolder=[iter(xrange(req.period - 1))])
self.__act... |
def main(arguments=None):
'''Runs thumbor server with the specified arguments.'''
if arguments is None:
arguments = sys.argv[1:]
server_parameters = get_server_parameters(arguments)
config = get_config(server_parameters.config_path, server_parameters.use_environment)
configure_log(config, s... | def function[main, parameter[arguments]]:
constant[Runs thumbor server with the specified arguments.]
if compare[name[arguments] is constant[None]] begin[:]
variable[arguments] assign[=] call[name[sys].argv][<ast.Slice object at 0x7da1b1cd4f70>]
variable[server_parameters] assign... | keyword[def] identifier[main] ( identifier[arguments] = keyword[None] ):
literal[string]
keyword[if] identifier[arguments] keyword[is] keyword[None] :
identifier[arguments] = identifier[sys] . identifier[argv] [ literal[int] :]
identifier[server_parameters] = identifier[get_server_paramet... | def main(arguments=None):
"""Runs thumbor server with the specified arguments."""
if arguments is None:
arguments = sys.argv[1:] # depends on [control=['if'], data=['arguments']]
server_parameters = get_server_parameters(arguments)
config = get_config(server_parameters.config_path, server_param... |
def gpr(data, xseq, **params):
"""
Fit gaussian process
"""
try:
from sklearn import gaussian_process
except ImportError:
raise PlotnineError(
"To use gaussian process smoothing, "
"You need to install scikit-learn.")
kwargs = params['method_args']
if... | def function[gpr, parameter[data, xseq]]:
constant[
Fit gaussian process
]
<ast.Try object at 0x7da204564fa0>
variable[kwargs] assign[=] call[name[params]][constant[method_args]]
if <ast.UnaryOp object at 0x7da204566560> begin[:]
call[name[warnings].warn, parameter[co... | keyword[def] identifier[gpr] ( identifier[data] , identifier[xseq] ,** identifier[params] ):
literal[string]
keyword[try] :
keyword[from] identifier[sklearn] keyword[import] identifier[gaussian_process]
keyword[except] identifier[ImportError] :
keyword[raise] identifier[Plotnin... | def gpr(data, xseq, **params):
"""
Fit gaussian process
"""
try:
from sklearn import gaussian_process # depends on [control=['try'], data=[]]
except ImportError:
raise PlotnineError('To use gaussian process smoothing, You need to install scikit-learn.') # depends on [control=['exce... |
def Send(self, message):
"""Send one message.
Deprecated, users should migrate to call self.outgoing.InsertMessage
directly.
"""
if not self.outgoing:
raise NotConfigured("Send address not provided.")
self.outgoing.InsertMessage(message) | def function[Send, parameter[self, message]]:
constant[Send one message.
Deprecated, users should migrate to call self.outgoing.InsertMessage
directly.
]
if <ast.UnaryOp object at 0x7da2054a6410> begin[:]
<ast.Raise object at 0x7da1b1389930>
call[name[self].outgoing.InsertMe... | keyword[def] identifier[Send] ( identifier[self] , identifier[message] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[outgoing] :
keyword[raise] identifier[NotConfigured] ( literal[string] )
identifier[self] . identifier[outgoing] . identifier[InsertMessage] ( iden... | def Send(self, message):
"""Send one message.
Deprecated, users should migrate to call self.outgoing.InsertMessage
directly.
"""
if not self.outgoing:
raise NotConfigured('Send address not provided.') # depends on [control=['if'], data=[]]
self.outgoing.InsertMessage(message) |
def json(self, path, schema=None, primitivesAsString=None, prefersDecimal=None,
allowComments=None, allowUnquotedFieldNames=None, allowSingleQuotes=None,
allowNumericLeadingZero=None, allowBackslashEscapingAnyCharacter=None,
mode=None, columnNameOfCorruptRecord=None, dateFormat=No... | def function[json, parameter[self, path, schema, primitivesAsString, prefersDecimal, allowComments, allowUnquotedFieldNames, allowSingleQuotes, allowNumericLeadingZero, allowBackslashEscapingAnyCharacter, mode, columnNameOfCorruptRecord, dateFormat, timestampFormat, multiLine, allowUnquotedControlChars, lineSep, sampli... | keyword[def] identifier[json] ( identifier[self] , identifier[path] , identifier[schema] = keyword[None] , identifier[primitivesAsString] = keyword[None] , identifier[prefersDecimal] = keyword[None] ,
identifier[allowComments] = keyword[None] , identifier[allowUnquotedFieldNames] = keyword[None] , identifier[allowSi... | def json(self, path, schema=None, primitivesAsString=None, prefersDecimal=None, allowComments=None, allowUnquotedFieldNames=None, allowSingleQuotes=None, allowNumericLeadingZero=None, allowBackslashEscapingAnyCharacter=None, mode=None, columnNameOfCorruptRecord=None, dateFormat=None, timestampFormat=None, multiLine=Non... |
def safe_group_name(group_name, group_max_length=100, ellipsis=True):
"""Truncate group name to match limit breaking on space and optionally add an ellipsis.
.. note:: Currently the ThreatConnect group name limit is 100 characters.
Args:
group_name (string): The raw group name to be... | def function[safe_group_name, parameter[group_name, group_max_length, ellipsis]]:
constant[Truncate group name to match limit breaking on space and optionally add an ellipsis.
.. note:: Currently the ThreatConnect group name limit is 100 characters.
Args:
group_name (string): The ra... | keyword[def] identifier[safe_group_name] ( identifier[group_name] , identifier[group_max_length] = literal[int] , identifier[ellipsis] = keyword[True] ):
literal[string]
identifier[ellipsis_value] = literal[string]
keyword[if] identifier[ellipsis] :
identifier[ellipsis_value... | def safe_group_name(group_name, group_max_length=100, ellipsis=True):
"""Truncate group name to match limit breaking on space and optionally add an ellipsis.
.. note:: Currently the ThreatConnect group name limit is 100 characters.
Args:
group_name (string): The raw group name to be tru... |
def get(self, attr, value=None, resolve=True):
"""Get the value of an attribute from submit description file.
Args:
attr (str): The name of the attribute whose value should be returned.
value (str, optional): A default value to return if 'attr' doesn't exist. Defaults to None.
... | def function[get, parameter[self, attr, value, resolve]]:
constant[Get the value of an attribute from submit description file.
Args:
attr (str): The name of the attribute whose value should be returned.
value (str, optional): A default value to return if 'attr' doesn't exist. De... | keyword[def] identifier[get] ( identifier[self] , identifier[attr] , identifier[value] = keyword[None] , identifier[resolve] = keyword[True] ):
literal[string]
keyword[try] :
keyword[if] identifier[resolve] :
identifier[value] = identifier[self] . identifier[_resolve_... | def get(self, attr, value=None, resolve=True):
"""Get the value of an attribute from submit description file.
Args:
attr (str): The name of the attribute whose value should be returned.
value (str, optional): A default value to return if 'attr' doesn't exist. Defaults to None.
... |
def OnDoubleClick(self, event):
"""Double click on a given square in the map"""
node = HotMapNavigator.findNodeAtPosition(self.hot_map, event.GetPosition())
if node:
wx.PostEvent( self, SquareActivationEvent( node=node, point=event.GetPosition(), map=self ) ) | def function[OnDoubleClick, parameter[self, event]]:
constant[Double click on a given square in the map]
variable[node] assign[=] call[name[HotMapNavigator].findNodeAtPosition, parameter[name[self].hot_map, call[name[event].GetPosition, parameter[]]]]
if name[node] begin[:]
call[... | keyword[def] identifier[OnDoubleClick] ( identifier[self] , identifier[event] ):
literal[string]
identifier[node] = identifier[HotMapNavigator] . identifier[findNodeAtPosition] ( identifier[self] . identifier[hot_map] , identifier[event] . identifier[GetPosition] ())
keyword[if] identifie... | def OnDoubleClick(self, event):
"""Double click on a given square in the map"""
node = HotMapNavigator.findNodeAtPosition(self.hot_map, event.GetPosition())
if node:
wx.PostEvent(self, SquareActivationEvent(node=node, point=event.GetPosition(), map=self)) # depends on [control=['if'], data=[]] |
def expect_re(regexp, buf, pos):
"""Require a regular expression at the current buffer position."""
match = regexp.match(buf, pos)
if not match:
return None, len(buf)
return buf[match.start(1):match.end(1)], match.end(0) | def function[expect_re, parameter[regexp, buf, pos]]:
constant[Require a regular expression at the current buffer position.]
variable[match] assign[=] call[name[regexp].match, parameter[name[buf], name[pos]]]
if <ast.UnaryOp object at 0x7da1b0274760> begin[:]
return[tuple[[<ast.Constant ... | keyword[def] identifier[expect_re] ( identifier[regexp] , identifier[buf] , identifier[pos] ):
literal[string]
identifier[match] = identifier[regexp] . identifier[match] ( identifier[buf] , identifier[pos] )
keyword[if] keyword[not] identifier[match] :
keyword[return] keyword[None] , ident... | def expect_re(regexp, buf, pos):
"""Require a regular expression at the current buffer position."""
match = regexp.match(buf, pos)
if not match:
return (None, len(buf)) # depends on [control=['if'], data=[]]
return (buf[match.start(1):match.end(1)], match.end(0)) |
def applyCommand(self):
"""
Applies the current line of code as an interactive python command.
"""
# generate the command information
cursor = self.textCursor()
cursor.movePosition(cursor.EndOfLine)
line = projex.text.nativestring(curs... | def function[applyCommand, parameter[self]]:
constant[
Applies the current line of code as an interactive python command.
]
variable[cursor] assign[=] call[name[self].textCursor, parameter[]]
call[name[cursor].movePosition, parameter[name[cursor].EndOfLine]]
variable[line... | keyword[def] identifier[applyCommand] ( identifier[self] ):
literal[string]
identifier[cursor] = identifier[self] . identifier[textCursor] ()
identifier[cursor] . identifier[movePosition] ( identifier[cursor] . identifier[EndOfLine] )
identifier[line] = identifier[... | def applyCommand(self):
"""
Applies the current line of code as an interactive python command.
""" # generate the command information
cursor = self.textCursor()
cursor.movePosition(cursor.EndOfLine)
line = projex.text.nativestring(cursor.block().text())
at_end = cursor.atEnd()
m... |
def is_able_to_parse_detailed(self, desired_type: Type[Any], desired_ext: str, strict: bool) -> Tuple[bool, bool]:
"""
Utility method to check if a parser is able to parse a given type, either in
* strict mode (desired_type must be one of the supported ones, or the parser should be generic)
... | def function[is_able_to_parse_detailed, parameter[self, desired_type, desired_ext, strict]]:
constant[
Utility method to check if a parser is able to parse a given type, either in
* strict mode (desired_type must be one of the supported ones, or the parser should be generic)
* inference ... | keyword[def] identifier[is_able_to_parse_detailed] ( identifier[self] , identifier[desired_type] : identifier[Type] [ identifier[Any] ], identifier[desired_ext] : identifier[str] , identifier[strict] : identifier[bool] )-> identifier[Tuple] [ identifier[bool] , identifier[bool] ]:
literal[string]
... | def is_able_to_parse_detailed(self, desired_type: Type[Any], desired_ext: str, strict: bool) -> Tuple[bool, bool]:
"""
Utility method to check if a parser is able to parse a given type, either in
* strict mode (desired_type must be one of the supported ones, or the parser should be generic)
... |
def _calculate_fnr_fdr(group):
"""Calculate the false negative rate (1 - sensitivity) and false discovery rate (1 - precision).
"""
data = {k: d["value"] for k, d in group.set_index("metric").T.to_dict().items()}
return pd.DataFrame([{"fnr": data["fn"] / float(data["tp"] + data["fn"]) * 100.0 if data["t... | def function[_calculate_fnr_fdr, parameter[group]]:
constant[Calculate the false negative rate (1 - sensitivity) and false discovery rate (1 - precision).
]
variable[data] assign[=] <ast.DictComp object at 0x7da20c6a9c30>
return[call[name[pd].DataFrame, parameter[list[[<ast.Dict object at 0x7da2... | keyword[def] identifier[_calculate_fnr_fdr] ( identifier[group] ):
literal[string]
identifier[data] ={ identifier[k] : identifier[d] [ literal[string] ] keyword[for] identifier[k] , identifier[d] keyword[in] identifier[group] . identifier[set_index] ( literal[string] ). identifier[T] . identifier[to_dic... | def _calculate_fnr_fdr(group):
"""Calculate the false negative rate (1 - sensitivity) and false discovery rate (1 - precision).
"""
data = {k: d['value'] for (k, d) in group.set_index('metric').T.to_dict().items()}
return pd.DataFrame([{'fnr': data['fn'] / float(data['tp'] + data['fn']) * 100.0 if data[... |
def copytree(self, target, symlinks=False):
"""Recursively copies this directory to the `target` location.
The permissions and times are copied (like
:meth:`~rpaths.Path.copystat`).
If the optional `symlinks` flag is true, symbolic links in the source
tree result in symbolic li... | def function[copytree, parameter[self, target, symlinks]]:
constant[Recursively copies this directory to the `target` location.
The permissions and times are copied (like
:meth:`~rpaths.Path.copystat`).
If the optional `symlinks` flag is true, symbolic links in the source
tree ... | keyword[def] identifier[copytree] ( identifier[self] , identifier[target] , identifier[symlinks] = keyword[False] ):
literal[string]
identifier[shutil] . identifier[copytree] ( identifier[self] . identifier[path] , identifier[self] . identifier[_to_backend] ( identifier[target] ), identifier[symlin... | def copytree(self, target, symlinks=False):
"""Recursively copies this directory to the `target` location.
The permissions and times are copied (like
:meth:`~rpaths.Path.copystat`).
If the optional `symlinks` flag is true, symbolic links in the source
tree result in symbolic links ... |
def _generate_message_error(cls, response_code, messages, response_id):
"""
:type response_code: int
:type messages: list[str]
:type response_id: str
:rtype: str
"""
line_response_code = cls._FORMAT_RESPONSE_CODE_LINE \
.format(response_code)
... | def function[_generate_message_error, parameter[cls, response_code, messages, response_id]]:
constant[
:type response_code: int
:type messages: list[str]
:type response_id: str
:rtype: str
]
variable[line_response_code] assign[=] call[name[cls]._FORMAT_RESPONSE_C... | keyword[def] identifier[_generate_message_error] ( identifier[cls] , identifier[response_code] , identifier[messages] , identifier[response_id] ):
literal[string]
identifier[line_response_code] = identifier[cls] . identifier[_FORMAT_RESPONSE_CODE_LINE] . identifier[format] ( identifier[response_co... | def _generate_message_error(cls, response_code, messages, response_id):
"""
:type response_code: int
:type messages: list[str]
:type response_id: str
:rtype: str
"""
line_response_code = cls._FORMAT_RESPONSE_CODE_LINE.format(response_code)
line_response_id = cls._FOR... |
def unroll_auth_headers(self, authheaders, exclude_signature=False, sep=",", quote=True):
"""Converts an authorization header dict-like object into a string representing the authorization.
Keyword arguments:
authheaders -- A string-indexable object which contains the headers appropriate for thi... | def function[unroll_auth_headers, parameter[self, authheaders, exclude_signature, sep, quote]]:
constant[Converts an authorization header dict-like object into a string representing the authorization.
Keyword arguments:
authheaders -- A string-indexable object which contains the headers appropr... | keyword[def] identifier[unroll_auth_headers] ( identifier[self] , identifier[authheaders] , identifier[exclude_signature] = keyword[False] , identifier[sep] = literal[string] , identifier[quote] = keyword[True] ):
literal[string]
identifier[res] = literal[string]
identifier[ordered] = ide... | def unroll_auth_headers(self, authheaders, exclude_signature=False, sep=',', quote=True):
"""Converts an authorization header dict-like object into a string representing the authorization.
Keyword arguments:
authheaders -- A string-indexable object which contains the headers appropriate for this si... |
def _get_from_riak(self, key):
"""
Args:
key (str): riak key
Returns:
(tuple): riak obj json data and riak key
"""
obj = self.bucket.get(key)
if obj.exists:
return obj.data, obj.key
raise ObjectDoesNotExist("%s %s" % (key, se... | def function[_get_from_riak, parameter[self, key]]:
constant[
Args:
key (str): riak key
Returns:
(tuple): riak obj json data and riak key
]
variable[obj] assign[=] call[name[self].bucket.get, parameter[name[key]]]
if name[obj].exists begin[:]
... | keyword[def] identifier[_get_from_riak] ( identifier[self] , identifier[key] ):
literal[string]
identifier[obj] = identifier[self] . identifier[bucket] . identifier[get] ( identifier[key] )
keyword[if] identifier[obj] . identifier[exists] :
keyword[return] identifier[obj] ... | def _get_from_riak(self, key):
"""
Args:
key (str): riak key
Returns:
(tuple): riak obj json data and riak key
"""
obj = self.bucket.get(key)
if obj.exists:
return (obj.data, obj.key) # depends on [control=['if'], data=[]]
raise ObjectDoesNotExist... |
def UpdateUser(username, password=None, is_admin=False):
"""Updates the password or privilege-level for a user."""
user_type, password = _GetUserTypeAndPassword(
username, password=password, is_admin=is_admin)
grr_api = maintenance_utils.InitGRRRootAPI()
grr_user = grr_api.GrrUser(username).Get()
grr_us... | def function[UpdateUser, parameter[username, password, is_admin]]:
constant[Updates the password or privilege-level for a user.]
<ast.Tuple object at 0x7da1b1c0dd80> assign[=] call[name[_GetUserTypeAndPassword], parameter[name[username]]]
variable[grr_api] assign[=] call[name[maintenance_utils].... | keyword[def] identifier[UpdateUser] ( identifier[username] , identifier[password] = keyword[None] , identifier[is_admin] = keyword[False] ):
literal[string]
identifier[user_type] , identifier[password] = identifier[_GetUserTypeAndPassword] (
identifier[username] , identifier[password] = identifier[password]... | def UpdateUser(username, password=None, is_admin=False):
"""Updates the password or privilege-level for a user."""
(user_type, password) = _GetUserTypeAndPassword(username, password=password, is_admin=is_admin)
grr_api = maintenance_utils.InitGRRRootAPI()
grr_user = grr_api.GrrUser(username).Get()
g... |
def DbPutDeviceAttributeProperty2(self, argin):
""" Put device attribute property. This command adds the possibility to have attribute property
which are arrays. Not possible with the old DbPutDeviceAttributeProperty command.
This old command is not deleted for compatibility reasons.
:p... | def function[DbPutDeviceAttributeProperty2, parameter[self, argin]]:
constant[ Put device attribute property. This command adds the possibility to have attribute property
which are arrays. Not possible with the old DbPutDeviceAttributeProperty command.
This old command is not deleted for compati... | keyword[def] identifier[DbPutDeviceAttributeProperty2] ( identifier[self] , identifier[argin] ):
literal[string]
identifier[self] . identifier[_log] . identifier[debug] ( literal[string] )
identifier[device_name] = identifier[argin] [ literal[int] ]
identifier[nb_attributes] = ide... | def DbPutDeviceAttributeProperty2(self, argin):
""" Put device attribute property. This command adds the possibility to have attribute property
which are arrays. Not possible with the old DbPutDeviceAttributeProperty command.
This old command is not deleted for compatibility reasons.
:param... |
def interactive_output(f, controls):
"""Connect widget controls to a function.
This function does not generate a user interface for the widgets (unlike `interact`).
This enables customisation of the widget user interface layout.
The user interface layout must be defined and displayed manually.
"""
... | def function[interactive_output, parameter[f, controls]]:
constant[Connect widget controls to a function.
This function does not generate a user interface for the widgets (unlike `interact`).
This enables customisation of the widget user interface layout.
The user interface layout must be defined a... | keyword[def] identifier[interactive_output] ( identifier[f] , identifier[controls] ):
literal[string]
identifier[out] = identifier[Output] ()
keyword[def] identifier[observer] ( identifier[change] ):
identifier[kwargs] ={ identifier[k] : identifier[v] . identifier[value] keyword[for] iden... | def interactive_output(f, controls):
"""Connect widget controls to a function.
This function does not generate a user interface for the widgets (unlike `interact`).
This enables customisation of the widget user interface layout.
The user interface layout must be defined and displayed manually.
"""
... |
def _clean_freebayes_output(line):
"""Clean FreeBayes output to make post-processing with GATK happy.
XXX Not applied on recent versions which fix issues to be more compatible
with bgzip output, but retained in case of need.
- Remove lines from FreeBayes outputs where REF/ALT are identical:
2 ... | def function[_clean_freebayes_output, parameter[line]]:
constant[Clean FreeBayes output to make post-processing with GATK happy.
XXX Not applied on recent versions which fix issues to be more compatible
with bgzip output, but retained in case of need.
- Remove lines from FreeBayes outputs where RE... | keyword[def] identifier[_clean_freebayes_output] ( identifier[line] ):
literal[string]
keyword[if] identifier[line] . identifier[startswith] ( literal[string] ):
identifier[line] = identifier[line] . identifier[replace] ( literal[string] , literal[string] )
keyword[return] identifier[li... | def _clean_freebayes_output(line):
"""Clean FreeBayes output to make post-processing with GATK happy.
XXX Not applied on recent versions which fix issues to be more compatible
with bgzip output, but retained in case of need.
- Remove lines from FreeBayes outputs where REF/ALT are identical:
2 ... |
def setup_auth_paths(app, auth, prefix, params):
"""Add URL rules for auth paths."""
base = urljoin('/', prefix + '/') # Must end in slash
app.add_url_rule(base + 'login', prefix + 'login_handler',
auth.login_handler, defaults=params)
app.add_url_rule(base + 'logout', prefix + 'log... | def function[setup_auth_paths, parameter[app, auth, prefix, params]]:
constant[Add URL rules for auth paths.]
variable[base] assign[=] call[name[urljoin], parameter[constant[/], binary_operation[name[prefix] + constant[/]]]]
call[name[app].add_url_rule, parameter[binary_operation[name[base] + co... | keyword[def] identifier[setup_auth_paths] ( identifier[app] , identifier[auth] , identifier[prefix] , identifier[params] ):
literal[string]
identifier[base] = identifier[urljoin] ( literal[string] , identifier[prefix] + literal[string] )
identifier[app] . identifier[add_url_rule] ( identifier[base] + ... | def setup_auth_paths(app, auth, prefix, params):
"""Add URL rules for auth paths."""
base = urljoin('/', prefix + '/') # Must end in slash
app.add_url_rule(base + 'login', prefix + 'login_handler', auth.login_handler, defaults=params)
app.add_url_rule(base + 'logout', prefix + 'logout_handler', auth.lo... |
def date_created(self):
"""Date the Scopus record was created."""
date_created = self.xml.find('institution-profile/date-created')
if date_created is not None:
date_created = (int(date_created.attrib['year']),
int(date_created.attrib['month']),
... | def function[date_created, parameter[self]]:
constant[Date the Scopus record was created.]
variable[date_created] assign[=] call[name[self].xml.find, parameter[constant[institution-profile/date-created]]]
if compare[name[date_created] is_not constant[None]] begin[:]
variable[date... | keyword[def] identifier[date_created] ( identifier[self] ):
literal[string]
identifier[date_created] = identifier[self] . identifier[xml] . identifier[find] ( literal[string] )
keyword[if] identifier[date_created] keyword[is] keyword[not] keyword[None] :
identifier[date_cr... | def date_created(self):
"""Date the Scopus record was created."""
date_created = self.xml.find('institution-profile/date-created')
if date_created is not None:
date_created = (int(date_created.attrib['year']), int(date_created.attrib['month']), int(date_created.attrib['day'])) # depends on [control... |
def validatePopElement(self, ctxt, elem, qname):
"""Pop the element end from the validation stack. """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
if elem is None: elem__o = None
else: elem__o = elem._o
ret = libxml2mod.xmlValidatePopElement(ctxt__o, self._o, ... | def function[validatePopElement, parameter[self, ctxt, elem, qname]]:
constant[Pop the element end from the validation stack. ]
if compare[name[ctxt] is constant[None]] begin[:]
variable[ctxt__o] assign[=] constant[None]
if compare[name[elem] is constant[None]] begin[:]
... | keyword[def] identifier[validatePopElement] ( identifier[self] , identifier[ctxt] , identifier[elem] , identifier[qname] ):
literal[string]
keyword[if] identifier[ctxt] keyword[is] keyword[None] : identifier[ctxt__o] = keyword[None]
keyword[else] : identifier[ctxt__o] = identifier[ctxt... | def validatePopElement(self, ctxt, elem, qname):
"""Pop the element end from the validation stack. """
if ctxt is None:
ctxt__o = None # depends on [control=['if'], data=[]]
else:
ctxt__o = ctxt._o
if elem is None:
elem__o = None # depends on [control=['if'], data=[]]
else:... |
def copy_resources_to_log_dir(log_dir):
"""Copies the necessary static assets to the log_dir and returns the path
of the main css file."""
css_path = resource_filename(Requirement.parse("egat"), "/egat/data/default.css")
header_path = resource_filename(Requirement.parse("egat"), "/egat/... | def function[copy_resources_to_log_dir, parameter[log_dir]]:
constant[Copies the necessary static assets to the log_dir and returns the path
of the main css file.]
variable[css_path] assign[=] call[name[resource_filename], parameter[call[name[Requirement].parse, parameter[constant[egat]]], cons... | keyword[def] identifier[copy_resources_to_log_dir] ( identifier[log_dir] ):
literal[string]
identifier[css_path] = identifier[resource_filename] ( identifier[Requirement] . identifier[parse] ( literal[string] ), literal[string] )
identifier[header_path] = identifier[resource_filename] ( id... | def copy_resources_to_log_dir(log_dir):
"""Copies the necessary static assets to the log_dir and returns the path
of the main css file."""
css_path = resource_filename(Requirement.parse('egat'), '/egat/data/default.css')
header_path = resource_filename(Requirement.parse('egat'), '/egat/data/egat_he... |
def UnregisterMessageHandler(self, timeout=None):
"""Unregisters any registered message handler."""
if self.handler_thread:
self.handler_stop = True
self.handler_thread.join(timeout)
if self.handler_thread.isAlive():
raise RuntimeError("Message handler thread did not join in time.")
... | def function[UnregisterMessageHandler, parameter[self, timeout]]:
constant[Unregisters any registered message handler.]
if name[self].handler_thread begin[:]
name[self].handler_stop assign[=] constant[True]
call[name[self].handler_thread.join, parameter[name[timeout]]]
... | keyword[def] identifier[UnregisterMessageHandler] ( identifier[self] , identifier[timeout] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[handler_thread] :
identifier[self] . identifier[handler_stop] = keyword[True]
identifier[self] . identifier[handler_thread]... | def UnregisterMessageHandler(self, timeout=None):
"""Unregisters any registered message handler."""
if self.handler_thread:
self.handler_stop = True
self.handler_thread.join(timeout)
if self.handler_thread.isAlive():
raise RuntimeError('Message handler thread did not join in ... |
def bbox(img):
"""Find the bounding box around nonzero elements in the given array
Copied from https://stackoverflow.com/a/31402351/5703449 .
Returns:
rowmin, rowmax, colmin, colmax
"""
rows = np.any(img, axis=1)
cols = np.any(img, axis=0)
rmin, rmax = np.where(rows)[0][[0, -1]]
... | def function[bbox, parameter[img]]:
constant[Find the bounding box around nonzero elements in the given array
Copied from https://stackoverflow.com/a/31402351/5703449 .
Returns:
rowmin, rowmax, colmin, colmax
]
variable[rows] assign[=] call[name[np].any, parameter[name[img]]]
... | keyword[def] identifier[bbox] ( identifier[img] ):
literal[string]
identifier[rows] = identifier[np] . identifier[any] ( identifier[img] , identifier[axis] = literal[int] )
identifier[cols] = identifier[np] . identifier[any] ( identifier[img] , identifier[axis] = literal[int] )
identifier[rmin] ,... | def bbox(img):
"""Find the bounding box around nonzero elements in the given array
Copied from https://stackoverflow.com/a/31402351/5703449 .
Returns:
rowmin, rowmax, colmin, colmax
"""
rows = np.any(img, axis=1)
cols = np.any(img, axis=0)
(rmin, rmax) = np.where(rows)[0][[0, -1]]
... |
def offset(self, num_to_skip):
"""Skip to an offset in a query with this collection as parent.
See
:meth:`~.firestore_v1beta1.query.Query.offset` for
more information on this method.
Args:
num_to_skip (int): The number of results to skip at the beginning
... | def function[offset, parameter[self, num_to_skip]]:
constant[Skip to an offset in a query with this collection as parent.
See
:meth:`~.firestore_v1beta1.query.Query.offset` for
more information on this method.
Args:
num_to_skip (int): The number of results to skip a... | keyword[def] identifier[offset] ( identifier[self] , identifier[num_to_skip] ):
literal[string]
identifier[query] = identifier[query_mod] . identifier[Query] ( identifier[self] )
keyword[return] identifier[query] . identifier[offset] ( identifier[num_to_skip] ) | def offset(self, num_to_skip):
"""Skip to an offset in a query with this collection as parent.
See
:meth:`~.firestore_v1beta1.query.Query.offset` for
more information on this method.
Args:
num_to_skip (int): The number of results to skip at the beginning
... |
def _Complete(self):
"""Marks the hunt as completed."""
self._RemoveForemanRule()
if "w" in self.hunt_obj.mode:
self.hunt_obj.Set(self.hunt_obj.Schema.STATE("COMPLETED"))
self.hunt_obj.Flush() | def function[_Complete, parameter[self]]:
constant[Marks the hunt as completed.]
call[name[self]._RemoveForemanRule, parameter[]]
if compare[constant[w] in name[self].hunt_obj.mode] begin[:]
call[name[self].hunt_obj.Set, parameter[call[name[self].hunt_obj.Schema.STATE, parameter[... | keyword[def] identifier[_Complete] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_RemoveForemanRule] ()
keyword[if] literal[string] keyword[in] identifier[self] . identifier[hunt_obj] . identifier[mode] :
identifier[self] . identifier[hunt_obj] . identifier[Set] ( ident... | def _Complete(self):
"""Marks the hunt as completed."""
self._RemoveForemanRule()
if 'w' in self.hunt_obj.mode:
self.hunt_obj.Set(self.hunt_obj.Schema.STATE('COMPLETED'))
self.hunt_obj.Flush() # depends on [control=['if'], data=[]] |
def find_definition(project, code, offset, resource=None, maxfixes=1):
"""Return the definition location of the python name at `offset`
A `Location` object is returned if the definition location can be
determined, otherwise ``None`` is returned.
"""
fixer = fixsyntax.FixSyntax(project, code, resour... | def function[find_definition, parameter[project, code, offset, resource, maxfixes]]:
constant[Return the definition location of the python name at `offset`
A `Location` object is returned if the definition location can be
determined, otherwise ``None`` is returned.
]
variable[fixer] assign[... | keyword[def] identifier[find_definition] ( identifier[project] , identifier[code] , identifier[offset] , identifier[resource] = keyword[None] , identifier[maxfixes] = literal[int] ):
literal[string]
identifier[fixer] = identifier[fixsyntax] . identifier[FixSyntax] ( identifier[project] , identifier[code] ,... | def find_definition(project, code, offset, resource=None, maxfixes=1):
"""Return the definition location of the python name at `offset`
A `Location` object is returned if the definition location can be
determined, otherwise ``None`` is returned.
"""
fixer = fixsyntax.FixSyntax(project, code, resour... |
def handle_oauth1_response(self, args):
"""Handles an oauth1 authorization response."""
client = self.make_client()
client.verifier = args.get('oauth_verifier')
tup = session.get('%s_oauthtok' % self.name)
if not tup:
raise OAuthException(
'Token not f... | def function[handle_oauth1_response, parameter[self, args]]:
constant[Handles an oauth1 authorization response.]
variable[client] assign[=] call[name[self].make_client, parameter[]]
name[client].verifier assign[=] call[name[args].get, parameter[constant[oauth_verifier]]]
variable[tup] as... | keyword[def] identifier[handle_oauth1_response] ( identifier[self] , identifier[args] ):
literal[string]
identifier[client] = identifier[self] . identifier[make_client] ()
identifier[client] . identifier[verifier] = identifier[args] . identifier[get] ( literal[string] )
identifier... | def handle_oauth1_response(self, args):
"""Handles an oauth1 authorization response."""
client = self.make_client()
client.verifier = args.get('oauth_verifier')
tup = session.get('%s_oauthtok' % self.name)
if not tup:
raise OAuthException('Token not found, maybe you disabled cookie', type='t... |
def Query(self, queue, limit=1):
"""Retrieves tasks from a queue without leasing them.
This is good for a read only snapshot of the tasks.
Args:
queue: The task queue that this task belongs to, usually client.Queue()
where client is the ClientURN object you want to schedule msgs on.
... | def function[Query, parameter[self, queue, limit]]:
constant[Retrieves tasks from a queue without leasing them.
This is good for a read only snapshot of the tasks.
Args:
queue: The task queue that this task belongs to, usually client.Queue()
where client is the ClientURN object you wan... | keyword[def] identifier[Query] ( identifier[self] , identifier[queue] , identifier[limit] = literal[int] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[queue] , identifier[rdf_client] . identifier[ClientURN] ):
identifier[queue] = identifier[queue] . identifier[Queue] ... | def Query(self, queue, limit=1):
"""Retrieves tasks from a queue without leasing them.
This is good for a read only snapshot of the tasks.
Args:
queue: The task queue that this task belongs to, usually client.Queue()
where client is the ClientURN object you want to schedule msgs on.
... |
def _set_raise_on_bulk_item_failure(self, raise_on_bulk_item_failure):
"""
Set the raise_on_bulk_item_failure parameter
:param raise_on_bulk_item_failure a bool the status of the raise_on_bulk_item_failure
"""
self._raise_on_bulk_item_failure = raise_on_bulk_item_failure
... | def function[_set_raise_on_bulk_item_failure, parameter[self, raise_on_bulk_item_failure]]:
constant[
Set the raise_on_bulk_item_failure parameter
:param raise_on_bulk_item_failure a bool the status of the raise_on_bulk_item_failure
]
name[self]._raise_on_bulk_item_failure assig... | keyword[def] identifier[_set_raise_on_bulk_item_failure] ( identifier[self] , identifier[raise_on_bulk_item_failure] ):
literal[string]
identifier[self] . identifier[_raise_on_bulk_item_failure] = identifier[raise_on_bulk_item_failure]
identifier[self] . identifier[bulker] . identifier[ra... | def _set_raise_on_bulk_item_failure(self, raise_on_bulk_item_failure):
"""
Set the raise_on_bulk_item_failure parameter
:param raise_on_bulk_item_failure a bool the status of the raise_on_bulk_item_failure
"""
self._raise_on_bulk_item_failure = raise_on_bulk_item_failure
self.bulker... |
def make_dist(toxinidir, toxdir, package):
"""zip up the package into the toxdir."""
dist = os.path.join(toxdir, "dist")
# Suppress warnings.
success = safe_shell_out(["python", "setup.py", "sdist", "--quiet",
"--formats=zip", "--dist-dir", dist],
... | def function[make_dist, parameter[toxinidir, toxdir, package]]:
constant[zip up the package into the toxdir.]
variable[dist] assign[=] call[name[os].path.join, parameter[name[toxdir], constant[dist]]]
variable[success] assign[=] call[name[safe_shell_out], parameter[list[[<ast.Constant object at ... | keyword[def] identifier[make_dist] ( identifier[toxinidir] , identifier[toxdir] , identifier[package] ):
literal[string]
identifier[dist] = identifier[os] . identifier[path] . identifier[join] ( identifier[toxdir] , literal[string] )
identifier[success] = identifier[safe_shell_out] ([ literal[str... | def make_dist(toxinidir, toxdir, package):
"""zip up the package into the toxdir."""
dist = os.path.join(toxdir, 'dist')
# Suppress warnings.
success = safe_shell_out(['python', 'setup.py', 'sdist', '--quiet', '--formats=zip', '--dist-dir', dist], cwd=toxinidir)
if success:
return os.path.jo... |
def compare(self, buf, offset=0, length=1, ignore=""):
"""Compare buffer"""
for i in range(offset, offset + length):
if isinstance(self.m_types, (type(Union), type(Structure))):
if compare(self.m_buf[i], buf[i], ignore=ignore):
return 1
elif s... | def function[compare, parameter[self, buf, offset, length, ignore]]:
constant[Compare buffer]
for taget[name[i]] in starred[call[name[range], parameter[name[offset], binary_operation[name[offset] + name[length]]]]] begin[:]
if call[name[isinstance], parameter[name[self].m_types, tuple[[<... | keyword[def] identifier[compare] ( identifier[self] , identifier[buf] , identifier[offset] = literal[int] , identifier[length] = literal[int] , identifier[ignore] = literal[string] ):
literal[string]
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[offset] , identifier[offs... | def compare(self, buf, offset=0, length=1, ignore=''):
"""Compare buffer"""
for i in range(offset, offset + length):
if isinstance(self.m_types, (type(Union), type(Structure))):
if compare(self.m_buf[i], buf[i], ignore=ignore):
return 1 # depends on [control=['if'], data=[]]... |
def close(self):
""" Close the link. """
# Stop the comm thread
self._thread.stop()
# Close the USB dongle
try:
if self.cfusb:
self.cfusb.set_crtp_to_usb(False)
self.cfusb.close()
except Exception as e:
# If we pull... | def function[close, parameter[self]]:
constant[ Close the link. ]
call[name[self]._thread.stop, parameter[]]
<ast.Try object at 0x7da1b1687550>
name[self].cfusb assign[=] constant[None] | keyword[def] identifier[close] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_thread] . identifier[stop] ()
keyword[try] :
keyword[if] identifier[self] . identifier[cfusb] :
identifier[self] . identifier[cfusb] . ident... | def close(self):
""" Close the link. """
# Stop the comm thread
self._thread.stop()
# Close the USB dongle
try:
if self.cfusb:
self.cfusb.set_crtp_to_usb(False)
self.cfusb.close() # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]]
exc... |
def set_ovs_view(self, asset_data, view_name):
"""
view_name should be frontView, sideView, or topView
"""
if not isinstance(asset_data, DataInputStream):
raise InvalidArgument('view file must be an ' +
'osid.transport.DataInputStream object'... | def function[set_ovs_view, parameter[self, asset_data, view_name]]:
constant[
view_name should be frontView, sideView, or topView
]
if <ast.UnaryOp object at 0x7da20c6aa770> begin[:]
<ast.Raise object at 0x7da20c6a9ab0>
if compare[name[view_name] <ast.NotIn object at 0x7d... | keyword[def] identifier[set_ovs_view] ( identifier[self] , identifier[asset_data] , identifier[view_name] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[asset_data] , identifier[DataInputStream] ):
keyword[raise] identifier[InvalidArgument] ( literal... | def set_ovs_view(self, asset_data, view_name):
"""
view_name should be frontView, sideView, or topView
"""
if not isinstance(asset_data, DataInputStream):
raise InvalidArgument('view file must be an ' + 'osid.transport.DataInputStream object') # depends on [control=['if'], data=[]]
... |
def get_analysis_and_structure(self,
structure,
calculate_valences=True,
guesstimate_spin=False,
op_threshold=0.1):
"""
Obtain an analysis of a given structure and ... | def function[get_analysis_and_structure, parameter[self, structure, calculate_valences, guesstimate_spin, op_threshold]]:
constant[
Obtain an analysis of a given structure and if it may be Jahn-Teller
active or not. This is a heuristic, and may give false positives and
false negatives (f... | keyword[def] identifier[get_analysis_and_structure] ( identifier[self] ,
identifier[structure] ,
identifier[calculate_valences] = keyword[True] ,
identifier[guesstimate_spin] = keyword[False] ,
identifier[op_threshold] = literal[int] ):
literal[string]
identifier[structure] = identifier[struct... | def get_analysis_and_structure(self, structure, calculate_valences=True, guesstimate_spin=False, op_threshold=0.1):
"""
Obtain an analysis of a given structure and if it may be Jahn-Teller
active or not. This is a heuristic, and may give false positives and
false negatives (false positives a... |
def _handle_kernel_died(self, since_last_heartbeat):
""" Handle the kernel's death by asking if the user wants to restart.
"""
self.log.debug("kernel died: %s", since_last_heartbeat)
if self.custom_restart:
self.custom_restart_kernel_died.emit(since_last_heartbeat)
el... | def function[_handle_kernel_died, parameter[self, since_last_heartbeat]]:
constant[ Handle the kernel's death by asking if the user wants to restart.
]
call[name[self].log.debug, parameter[constant[kernel died: %s], name[since_last_heartbeat]]]
if name[self].custom_restart begin[:]
... | keyword[def] identifier[_handle_kernel_died] ( identifier[self] , identifier[since_last_heartbeat] ):
literal[string]
identifier[self] . identifier[log] . identifier[debug] ( literal[string] , identifier[since_last_heartbeat] )
keyword[if] identifier[self] . identifier[custom_restart] :
... | def _handle_kernel_died(self, since_last_heartbeat):
""" Handle the kernel's death by asking if the user wants to restart.
"""
self.log.debug('kernel died: %s', since_last_heartbeat)
if self.custom_restart:
self.custom_restart_kernel_died.emit(since_last_heartbeat) # depends on [control=['i... |
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop... | def function[hmset, parameter[key]]:
constant[
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
]
variable[host] assign[=] call[name[fieldsv... | keyword[def] identifier[hmset] ( identifier[key] ,** identifier[fieldsvals] ):
literal[string]
identifier[host] = identifier[fieldsvals] . identifier[pop] ( literal[string] , keyword[None] )
identifier[port] = identifier[fieldsvals] . identifier[pop] ( literal[string] , keyword[None] )
identifier... | def hmset(key, **fieldsvals):
"""
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
"""
host = fieldsvals.pop('host', None)
port = fieldsvals.pop... |
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1] | def function[_set_repo_option, parameter[repo, option]]:
constant[
Set the option to repo
]
if <ast.UnaryOp object at 0x7da18eb545e0> begin[:]
return[None]
variable[opt] assign[=] call[name[option].split, parameter[constant[=]]]
if compare[call[name[len], parameter[name[o... | keyword[def] identifier[_set_repo_option] ( identifier[repo] , identifier[option] ):
literal[string]
keyword[if] keyword[not] identifier[option] :
keyword[return]
identifier[opt] = identifier[option] . identifier[split] ( literal[string] )
keyword[if] identifier[len] ( identifier[opt... | def _set_repo_option(repo, option):
"""
Set the option to repo
"""
if not option:
return # depends on [control=['if'], data=[]]
opt = option.split('=')
if len(opt) != 2:
return # depends on [control=['if'], data=[]]
if opt[0] == 'trusted':
repo['trusted'] = opt[1] =... |
def modified_lines(filename, extra_data, commit=None):
"""Returns the lines that have been modifed for this file.
Args:
filename: the file to check.
extra_data: is the extra_data returned by modified_files. Additionally, a
value of None means that the file was not modified.
commit: th... | def function[modified_lines, parameter[filename, extra_data, commit]]:
constant[Returns the lines that have been modifed for this file.
Args:
filename: the file to check.
extra_data: is the extra_data returned by modified_files. Additionally, a
value of None means that the file was not ... | keyword[def] identifier[modified_lines] ( identifier[filename] , identifier[extra_data] , identifier[commit] = keyword[None] ):
literal[string]
keyword[if] identifier[extra_data] keyword[is] keyword[None] :
keyword[return] []
keyword[if] identifier[extra_data] != literal[string] :
... | def modified_lines(filename, extra_data, commit=None):
"""Returns the lines that have been modifed for this file.
Args:
filename: the file to check.
extra_data: is the extra_data returned by modified_files. Additionally, a
value of None means that the file was not modified.
commit: th... |
def delete(self, dataset):
"""The method is deleting dataset by it's id"""
url = self._get_url('/api/1.0/meta/dataset/{}/delete'.format(dataset))
json_data = ''
binary_data = json_data.encode()
headers = self._get_request_headers()
req = urllib.request.Request... | def function[delete, parameter[self, dataset]]:
constant[The method is deleting dataset by it's id]
variable[url] assign[=] call[name[self]._get_url, parameter[call[constant[/api/1.0/meta/dataset/{}/delete].format, parameter[name[dataset]]]]]
variable[json_data] assign[=] constant[]
vari... | keyword[def] identifier[delete] ( identifier[self] , identifier[dataset] ):
literal[string]
identifier[url] = identifier[self] . identifier[_get_url] ( literal[string] . identifier[format] ( identifier[dataset] ))
identifier[json_data] = literal[string]
identifier[binary_... | def delete(self, dataset):
"""The method is deleting dataset by it's id"""
url = self._get_url('/api/1.0/meta/dataset/{}/delete'.format(dataset))
json_data = ''
binary_data = json_data.encode()
headers = self._get_request_headers()
req = urllib.request.Request(url, binary_data, headers)
resp... |
def list(connection):
""" List watched EBS volumes
:type connection: boto.ec2.connection.EC2Connection
:param connection: EC2 connection object
:returns: None
"""
volumes = get_watched_volumes(connection)
if not volumes:
logger.info('No watched volumes found')
return
l... | def function[list, parameter[connection]]:
constant[ List watched EBS volumes
:type connection: boto.ec2.connection.EC2Connection
:param connection: EC2 connection object
:returns: None
]
variable[volumes] assign[=] call[name[get_watched_volumes], parameter[name[connection]]]
if... | keyword[def] identifier[list] ( identifier[connection] ):
literal[string]
identifier[volumes] = identifier[get_watched_volumes] ( identifier[connection] )
keyword[if] keyword[not] identifier[volumes] :
identifier[logger] . identifier[info] ( literal[string] )
keyword[return]
... | def list(connection):
""" List watched EBS volumes
:type connection: boto.ec2.connection.EC2Connection
:param connection: EC2 connection object
:returns: None
"""
volumes = get_watched_volumes(connection)
if not volumes:
logger.info('No watched volumes found')
return # depe... |
def dump_service(self, sc):
"""Read all data blocks of a given service.
:meth:`dump_service` reads all data blocks from the service
with service code *sc* and returns a list of strings suitable
for printing. The number of strings returned does not
necessarily reflect the number ... | def function[dump_service, parameter[self, sc]]:
constant[Read all data blocks of a given service.
:meth:`dump_service` reads all data blocks from the service
with service code *sc* and returns a list of strings suitable
for printing. The number of strings returned does not
nece... | keyword[def] identifier[dump_service] ( identifier[self] , identifier[sc] ):
literal[string]
keyword[def] identifier[lprint] ( identifier[fmt] , identifier[data] , identifier[index] ):
identifier[ispchr] = keyword[lambda] identifier[x] : identifier[x] >= literal[int] keyword[and] i... | def dump_service(self, sc):
"""Read all data blocks of a given service.
:meth:`dump_service` reads all data blocks from the service
with service code *sc* and returns a list of strings suitable
for printing. The number of strings returned does not
necessarily reflect the number of d... |
def update_row(self, key, value):
"""Update a column named `header` in the table.
If length of column is smaller than number of rows, lets say
`k`, only the first `k` values in the column is updated.
Parameters
----------
key : int or slice
index of the row,... | def function[update_row, parameter[self, key, value]]:
constant[Update a column named `header` in the table.
If length of column is smaller than number of rows, lets say
`k`, only the first `k` values in the column is updated.
Parameters
----------
key : int or slice
... | keyword[def] identifier[update_row] ( identifier[self] , identifier[key] , identifier[value] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[key] , identifier[int] ):
identifier[row] = identifier[self] . identifier[_validate_row] ( identifier[value] , identifier[ini... | def update_row(self, key, value):
"""Update a column named `header` in the table.
If length of column is smaller than number of rows, lets say
`k`, only the first `k` values in the column is updated.
Parameters
----------
key : int or slice
index of the row, or ... |
def select_action(self, q_values):
"""Return the selected action
# Arguments
q_values (np.ndarray): List of the estimations of Q for each action
# Returns
Selection action
"""
assert q_values.ndim == 1
nb_actions = q_values.shape[0]
if n... | def function[select_action, parameter[self, q_values]]:
constant[Return the selected action
# Arguments
q_values (np.ndarray): List of the estimations of Q for each action
# Returns
Selection action
]
assert[compare[name[q_values].ndim equal[==] constant[1]]... | keyword[def] identifier[select_action] ( identifier[self] , identifier[q_values] ):
literal[string]
keyword[assert] identifier[q_values] . identifier[ndim] == literal[int]
identifier[nb_actions] = identifier[q_values] . identifier[shape] [ literal[int] ]
keyword[if] identifier... | def select_action(self, q_values):
"""Return the selected action
# Arguments
q_values (np.ndarray): List of the estimations of Q for each action
# Returns
Selection action
"""
assert q_values.ndim == 1
nb_actions = q_values.shape[0]
if np.random.uniform(... |
def send_command(self, device_id, action):
"""Send device command to rflink gateway."""
command = deserialize_packet_id(device_id)
command['command'] = action
log.debug('sending command: %s', command)
self.send_packet(command) | def function[send_command, parameter[self, device_id, action]]:
constant[Send device command to rflink gateway.]
variable[command] assign[=] call[name[deserialize_packet_id], parameter[name[device_id]]]
call[name[command]][constant[command]] assign[=] name[action]
call[name[log].debug, p... | keyword[def] identifier[send_command] ( identifier[self] , identifier[device_id] , identifier[action] ):
literal[string]
identifier[command] = identifier[deserialize_packet_id] ( identifier[device_id] )
identifier[command] [ literal[string] ]= identifier[action]
identifier[log] .... | def send_command(self, device_id, action):
"""Send device command to rflink gateway."""
command = deserialize_packet_id(device_id)
command['command'] = action
log.debug('sending command: %s', command)
self.send_packet(command) |
def scale(input_value, input_min, input_max, out_min, out_max):
""" scale a value from one range to another
"""
# Figure out how 'wide' each range is
input_span = input_max - input_min
output_span = out_max - out_min
# Convert the left range into a 0-1 range (float)
valuescaled = float(input... | def function[scale, parameter[input_value, input_min, input_max, out_min, out_max]]:
constant[ scale a value from one range to another
]
variable[input_span] assign[=] binary_operation[name[input_max] - name[input_min]]
variable[output_span] assign[=] binary_operation[name[out_max] - name[ou... | keyword[def] identifier[scale] ( identifier[input_value] , identifier[input_min] , identifier[input_max] , identifier[out_min] , identifier[out_max] ):
literal[string]
identifier[input_span] = identifier[input_max] - identifier[input_min]
identifier[output_span] = identifier[out_max] - identifie... | def scale(input_value, input_min, input_max, out_min, out_max):
""" scale a value from one range to another
"""
# Figure out how 'wide' each range is
input_span = input_max - input_min
output_span = out_max - out_min
# Convert the left range into a 0-1 range (float)
valuescaled = float(input... |
def wait(self):
"""
wait for all actions to complete on a droplet
"""
interval_seconds = 5
while True:
actions = self.actions()
slept = False
for a in actions:
if a['status'] == 'in-progress':
# n.b. gevent w... | def function[wait, parameter[self]]:
constant[
wait for all actions to complete on a droplet
]
variable[interval_seconds] assign[=] constant[5]
while constant[True] begin[:]
variable[actions] assign[=] call[name[self].actions, parameter[]]
variable... | keyword[def] identifier[wait] ( identifier[self] ):
literal[string]
identifier[interval_seconds] = literal[int]
keyword[while] keyword[True] :
identifier[actions] = identifier[self] . identifier[actions] ()
identifier[slept] = keyword[False]
keywor... | def wait(self):
"""
wait for all actions to complete on a droplet
"""
interval_seconds = 5
while True:
actions = self.actions()
slept = False
for a in actions:
if a['status'] == 'in-progress':
# n.b. gevent will monkey patch
... |
def _get_observed_mmax(catalogue, config):
'''Check see if observed mmax values are input, if not then take
from the catalogue'''
if config['input_mmax']:
obsmax = config['input_mmax']
if config['input_mmax_uncertainty']:
return config['input_mmax'], config['input_mmax_uncertaint... | def function[_get_observed_mmax, parameter[catalogue, config]]:
constant[Check see if observed mmax values are input, if not then take
from the catalogue]
if call[name[config]][constant[input_mmax]] begin[:]
variable[obsmax] assign[=] call[name[config]][constant[input_mmax]]
... | keyword[def] identifier[_get_observed_mmax] ( identifier[catalogue] , identifier[config] ):
literal[string]
keyword[if] identifier[config] [ literal[string] ]:
identifier[obsmax] = identifier[config] [ literal[string] ]
keyword[if] identifier[config] [ literal[string] ]:
ke... | def _get_observed_mmax(catalogue, config):
"""Check see if observed mmax values are input, if not then take
from the catalogue"""
if config['input_mmax']:
obsmax = config['input_mmax']
if config['input_mmax_uncertainty']:
return (config['input_mmax'], config['input_mmax_uncertain... |
def map(self, map_fn, name="Map"):
"""Applies a map operator to the stream.
Attributes:
map_fn (function): The user-defined logic of the map.
"""
op = Operator(
_generate_uuid(),
OpType.Map,
name,
map_fn,
num_insta... | def function[map, parameter[self, map_fn, name]]:
constant[Applies a map operator to the stream.
Attributes:
map_fn (function): The user-defined logic of the map.
]
variable[op] assign[=] call[name[Operator], parameter[call[name[_generate_uuid], parameter[]], name[OpType].M... | keyword[def] identifier[map] ( identifier[self] , identifier[map_fn] , identifier[name] = literal[string] ):
literal[string]
identifier[op] = identifier[Operator] (
identifier[_generate_uuid] (),
identifier[OpType] . identifier[Map] ,
identifier[name] ,
identifie... | def map(self, map_fn, name='Map'):
"""Applies a map operator to the stream.
Attributes:
map_fn (function): The user-defined logic of the map.
"""
op = Operator(_generate_uuid(), OpType.Map, name, map_fn, num_instances=self.env.config.parallelism)
return self.__register(op) |
def print_traceback(self, always_print=False):
"""
Prints the traceback to console - if there is any traceback, otherwise does nothing.
:param always_print: print the traceback, even if there is nothing in the buffer (default: false)
"""
if self._exception or always_print:
... | def function[print_traceback, parameter[self, always_print]]:
constant[
Prints the traceback to console - if there is any traceback, otherwise does nothing.
:param always_print: print the traceback, even if there is nothing in the buffer (default: false)
]
if <ast.BoolOp object... | keyword[def] identifier[print_traceback] ( identifier[self] , identifier[always_print] = keyword[False] ):
literal[string]
keyword[if] identifier[self] . identifier[_exception] keyword[or] identifier[always_print] :
identifier[self] . identifier[__echo] . identifier[critical] ( lite... | def print_traceback(self, always_print=False):
"""
Prints the traceback to console - if there is any traceback, otherwise does nothing.
:param always_print: print the traceback, even if there is nothing in the buffer (default: false)
"""
if self._exception or always_print:
self... |
def get_conn(self):
"""Returns a Google Cloud Dataproc service object."""
http_authorized = self._authorize()
return build(
'dataproc', self.api_version, http=http_authorized,
cache_discovery=False) | def function[get_conn, parameter[self]]:
constant[Returns a Google Cloud Dataproc service object.]
variable[http_authorized] assign[=] call[name[self]._authorize, parameter[]]
return[call[name[build], parameter[constant[dataproc], name[self].api_version]]] | keyword[def] identifier[get_conn] ( identifier[self] ):
literal[string]
identifier[http_authorized] = identifier[self] . identifier[_authorize] ()
keyword[return] identifier[build] (
literal[string] , identifier[self] . identifier[api_version] , identifier[http] = identifier[http... | def get_conn(self):
"""Returns a Google Cloud Dataproc service object."""
http_authorized = self._authorize()
return build('dataproc', self.api_version, http=http_authorized, cache_discovery=False) |
def requires_ROOT(version, exception=False):
"""
A decorator for functions or methods that require a minimum ROOT version.
If `exception` is False (the default) a warning is issued and None is
returned, otherwise a `NotImplementedError` exception is raised.
`exception` may also be an `Exception` in ... | def function[requires_ROOT, parameter[version, exception]]:
constant[
A decorator for functions or methods that require a minimum ROOT version.
If `exception` is False (the default) a warning is issued and None is
returned, otherwise a `NotImplementedError` exception is raised.
`exception` may a... | keyword[def] identifier[requires_ROOT] ( identifier[version] , identifier[exception] = keyword[False] ):
literal[string]
keyword[def] identifier[decorator] ( identifier[f] ):
@ identifier[wraps] ( identifier[f] )
keyword[def] identifier[wrapper] (* identifier[args] ,** identifier[kwargs]... | def requires_ROOT(version, exception=False):
"""
A decorator for functions or methods that require a minimum ROOT version.
If `exception` is False (the default) a warning is issued and None is
returned, otherwise a `NotImplementedError` exception is raised.
`exception` may also be an `Exception` in ... |
def importSafeElementTree(module_names=None):
"""Find a working ElementTree implementation that is not vulnerable
to XXE, using `defusedxml`.
>>> XXESafeElementTree = importSafeElementTree()
@param module_names: The names of modules to try to use as
a safe ElementTree. Defaults to C{L{xxe_safe... | def function[importSafeElementTree, parameter[module_names]]:
constant[Find a working ElementTree implementation that is not vulnerable
to XXE, using `defusedxml`.
>>> XXESafeElementTree = importSafeElementTree()
@param module_names: The names of modules to try to use as
a safe ElementTree... | keyword[def] identifier[importSafeElementTree] ( identifier[module_names] = keyword[None] ):
literal[string]
keyword[if] identifier[module_names] keyword[is] keyword[None] :
identifier[module_names] = identifier[xxe_safe_elementtree_modules]
keyword[try] :
keyword[return] identi... | def importSafeElementTree(module_names=None):
"""Find a working ElementTree implementation that is not vulnerable
to XXE, using `defusedxml`.
>>> XXESafeElementTree = importSafeElementTree()
@param module_names: The names of modules to try to use as
a safe ElementTree. Defaults to C{L{xxe_safe... |
def _read_amino_acids():
"""Read the amino acid information from a resource file."""
this_dir = os.path.dirname(os.path.abspath(__file__))
aa_file = os.path.join(this_dir, os.pardir, 'resources', 'amino_acids.tsv')
amino_acids = {}
amino_acids_reverse = {}
with open(aa_file, 'rt') as fh:
... | def function[_read_amino_acids, parameter[]]:
constant[Read the amino acid information from a resource file.]
variable[this_dir] assign[=] call[name[os].path.dirname, parameter[call[name[os].path.abspath, parameter[name[__file__]]]]]
variable[aa_file] assign[=] call[name[os].path.join, parameter... | keyword[def] identifier[_read_amino_acids] ():
literal[string]
identifier[this_dir] = identifier[os] . identifier[path] . identifier[dirname] ( identifier[os] . identifier[path] . identifier[abspath] ( identifier[__file__] ))
identifier[aa_file] = identifier[os] . identifier[path] . identifier[join] (... | def _read_amino_acids():
"""Read the amino acid information from a resource file."""
this_dir = os.path.dirname(os.path.abspath(__file__))
aa_file = os.path.join(this_dir, os.pardir, 'resources', 'amino_acids.tsv')
amino_acids = {}
amino_acids_reverse = {}
with open(aa_file, 'rt') as fh:
... |
def custom_showwarning(
message, category, filename="", lineno=-1, file=None, line=None
):
"""Hook to override default showwarning.
https://stackoverflow.com/questions/2187269/python-print-only-the-message-on-warnings
"""
if file is None:
file = sys.stderr
if file is None:
... | def function[custom_showwarning, parameter[message, category, filename, lineno, file, line]]:
constant[Hook to override default showwarning.
https://stackoverflow.com/questions/2187269/python-print-only-the-message-on-warnings
]
if compare[name[file] is constant[None]] begin[:]
... | keyword[def] identifier[custom_showwarning] (
identifier[message] , identifier[category] , identifier[filename] = literal[string] , identifier[lineno] =- literal[int] , identifier[file] = keyword[None] , identifier[line] = keyword[None]
):
literal[string]
keyword[if] identifier[file] keyword[is] keyw... | def custom_showwarning(message, category, filename='', lineno=-1, file=None, line=None):
"""Hook to override default showwarning.
https://stackoverflow.com/questions/2187269/python-print-only-the-message-on-warnings
"""
if file is None:
file = sys.stderr
if file is None:
# s... |
def remove(self, pkgs):
"""Remove packages from queue
"""
print("\nRemove packages from the queue:\n")
with open(self.queue_list, "w") as queue:
for line in self.queued.splitlines():
if line not in pkgs:
queue.write(line + "\n")
... | def function[remove, parameter[self, pkgs]]:
constant[Remove packages from queue
]
call[name[print], parameter[constant[
Remove packages from the queue:
]]]
with call[name[open], parameter[name[self].queue_list, constant[w]]] begin[:]
for taget[name[line]] in starred[call... | keyword[def] identifier[remove] ( identifier[self] , identifier[pkgs] ):
literal[string]
identifier[print] ( literal[string] )
keyword[with] identifier[open] ( identifier[self] . identifier[queue_list] , literal[string] ) keyword[as] identifier[queue] :
keyword[for] identif... | def remove(self, pkgs):
"""Remove packages from queue
"""
print('\nRemove packages from the queue:\n')
with open(self.queue_list, 'w') as queue:
for line in self.queued.splitlines():
if line not in pkgs:
queue.write(line + '\n') # depends on [control=['if'], data... |
def get_share(self, group_id, resource_id, depth=1):
"""
Retrieves a specific resource share available to a group.
:param group_id: The unique ID of the group.
:type group_id: ``str``
:param resource_id: The unique ID of the resource.
:type resourc... | def function[get_share, parameter[self, group_id, resource_id, depth]]:
constant[
Retrieves a specific resource share available to a group.
:param group_id: The unique ID of the group.
:type group_id: ``str``
:param resource_id: The unique ID of the resource.
... | keyword[def] identifier[get_share] ( identifier[self] , identifier[group_id] , identifier[resource_id] , identifier[depth] = literal[int] ):
literal[string]
identifier[response] = identifier[self] . identifier[_perform_request] (
literal[string]
%( identifier[group_id] , identifie... | def get_share(self, group_id, resource_id, depth=1):
"""
Retrieves a specific resource share available to a group.
:param group_id: The unique ID of the group.
:type group_id: ``str``
:param resource_id: The unique ID of the resource.
:type resource_id... |
def acquisition_function_withGradients(self, x):
"""
Returns the acquisition function and its its gradient at x.
"""
aqu_x = self.acquisition_function(x)
aqu_x_grad = self.d_acquisition_function(x)
return aqu_x, aqu_x_grad | def function[acquisition_function_withGradients, parameter[self, x]]:
constant[
Returns the acquisition function and its its gradient at x.
]
variable[aqu_x] assign[=] call[name[self].acquisition_function, parameter[name[x]]]
variable[aqu_x_grad] assign[=] call[name[self].d_acqui... | keyword[def] identifier[acquisition_function_withGradients] ( identifier[self] , identifier[x] ):
literal[string]
identifier[aqu_x] = identifier[self] . identifier[acquisition_function] ( identifier[x] )
identifier[aqu_x_grad] = identifier[self] . identifier[d_acquisition_function] ( ident... | def acquisition_function_withGradients(self, x):
"""
Returns the acquisition function and its its gradient at x.
"""
aqu_x = self.acquisition_function(x)
aqu_x_grad = self.d_acquisition_function(x)
return (aqu_x, aqu_x_grad) |
def getDbNames(self):
"""This function returns the list of open databases"""
request = []
request.append(uu({'-dbnames': '' }))
result = self._doRequest(request)
result = FMResultset.FMResultset(result)
dbNames = []
for dbName in result.resultset:
dbNames.append(string.lower(dbName['DATABASE_NAME'])... | def function[getDbNames, parameter[self]]:
constant[This function returns the list of open databases]
variable[request] assign[=] list[[]]
call[name[request].append, parameter[call[name[uu], parameter[dictionary[[<ast.Constant object at 0x7da1b28194b0>], [<ast.Constant object at 0x7da1b281a8c0>]... | keyword[def] identifier[getDbNames] ( identifier[self] ):
literal[string]
identifier[request] =[]
identifier[request] . identifier[append] ( identifier[uu] ({ literal[string] : literal[string] }))
identifier[result] = identifier[self] . identifier[_doRequest] ( identifier[request] )
identifier[resul... | def getDbNames(self):
"""This function returns the list of open databases"""
request = []
request.append(uu({'-dbnames': ''}))
result = self._doRequest(request)
result = FMResultset.FMResultset(result)
dbNames = []
for dbName in result.resultset:
dbNames.append(string.lower(dbName['D... |
def insert_entry(self, entry):
"""!
@brief Insert new clustering feature to the leaf node.
@param[in] entry (cfentry): Clustering feature.
"""
self.feature += entry;
self.entries.append(entry); | def function[insert_entry, parameter[self, entry]]:
constant[!
@brief Insert new clustering feature to the leaf node.
@param[in] entry (cfentry): Clustering feature.
]
<ast.AugAssign object at 0x7da20e9553f0>
call[name[self].entries.append, parameter[name[en... | keyword[def] identifier[insert_entry] ( identifier[self] , identifier[entry] ):
literal[string]
identifier[self] . identifier[feature] += identifier[entry] ;
identifier[self] . identifier[entries] . identifier[append] ( identifier[entry] ); | def insert_entry(self, entry):
"""!
@brief Insert new clustering feature to the leaf node.
@param[in] entry (cfentry): Clustering feature.
"""
self.feature += entry
self.entries.append(entry) |
async def set_message(
self, text=None, reply_to=0, parse_mode=(),
link_preview=None):
"""
Changes the draft message on the Telegram servers. The changes are
reflected in this object.
:param str text: New text of the draft.
Preserved if l... | <ast.AsyncFunctionDef object at 0x7da18eb56890> | keyword[async] keyword[def] identifier[set_message] (
identifier[self] , identifier[text] = keyword[None] , identifier[reply_to] = literal[int] , identifier[parse_mode] =(),
identifier[link_preview] = keyword[None] ):
literal[string]
keyword[if] identifier[text] keyword[is] keyword[None] :
... | async def set_message(self, text=None, reply_to=0, parse_mode=(), link_preview=None):
"""
Changes the draft message on the Telegram servers. The changes are
reflected in this object.
:param str text: New text of the draft.
Preserved if left as None.
:param ... |
def hash(self):
'''
:rtype: int
:return: hash of the field
'''
hashed = super(String, self).hash()
return khash(hashed, self._max_size) | def function[hash, parameter[self]]:
constant[
:rtype: int
:return: hash of the field
]
variable[hashed] assign[=] call[call[name[super], parameter[name[String], name[self]]].hash, parameter[]]
return[call[name[khash], parameter[name[hashed], name[self]._max_size]]] | keyword[def] identifier[hash] ( identifier[self] ):
literal[string]
identifier[hashed] = identifier[super] ( identifier[String] , identifier[self] ). identifier[hash] ()
keyword[return] identifier[khash] ( identifier[hashed] , identifier[self] . identifier[_max_size] ) | def hash(self):
"""
:rtype: int
:return: hash of the field
"""
hashed = super(String, self).hash()
return khash(hashed, self._max_size) |
def connect_to_region(cls, region, session=None, access_key=None,
secret_key=None, **kwargs):
"""
Connect to an AWS region.
This method has been deprecated in favor of :meth:`~.connect`
Parameters
----------
region : str
Name of an ... | def function[connect_to_region, parameter[cls, region, session, access_key, secret_key]]:
constant[
Connect to an AWS region.
This method has been deprecated in favor of :meth:`~.connect`
Parameters
----------
region : str
Name of an AWS region
sessi... | keyword[def] identifier[connect_to_region] ( identifier[cls] , identifier[region] , identifier[session] = keyword[None] , identifier[access_key] = keyword[None] ,
identifier[secret_key] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[warnings] . identifier[warn] ( literal[stri... | def connect_to_region(cls, region, session=None, access_key=None, secret_key=None, **kwargs):
"""
Connect to an AWS region.
This method has been deprecated in favor of :meth:`~.connect`
Parameters
----------
region : str
Name of an AWS region
session : :... |
def exec_args(f):
"""decorator for adding block/targets args for execution
applied to %pxconfig and %%px
"""
args = [
magic_arguments.argument('-b', '--block', action="store_const",
const=True, dest='block',
help="use blocking (sync) execution",
),
ma... | def function[exec_args, parameter[f]]:
constant[decorator for adding block/targets args for execution
applied to %pxconfig and %%px
]
variable[args] assign[=] list[[<ast.Call object at 0x7da1b26ac820>, <ast.Call object at 0x7da1b26ae380>, <ast.Call object at 0x7da1b26aeef0>, <ast.Call objec... | keyword[def] identifier[exec_args] ( identifier[f] ):
literal[string]
identifier[args] =[
identifier[magic_arguments] . identifier[argument] ( literal[string] , literal[string] , identifier[action] = literal[string] ,
identifier[const] = keyword[True] , identifier[dest] = literal[string] ,
i... | def exec_args(f):
"""decorator for adding block/targets args for execution
applied to %pxconfig and %%px
"""
args = [magic_arguments.argument('-b', '--block', action='store_const', const=True, dest='block', help='use blocking (sync) execution'), magic_arguments.argument('-a', '--noblock', action='s... |
def get_contents_debug_adapter_protocol(self, lst, fmt=None):
'''
This method is to be used in the case where the variables are all saved by its id (and as
such don't need to have the `resolve` method called later on, so, keys don't need to
embed the reference in the key).
Note ... | def function[get_contents_debug_adapter_protocol, parameter[self, lst, fmt]]:
constant[
This method is to be used in the case where the variables are all saved by its id (and as
such don't need to have the `resolve` method called later on, so, keys don't need to
embed the reference in th... | keyword[def] identifier[get_contents_debug_adapter_protocol] ( identifier[self] , identifier[lst] , identifier[fmt] = keyword[None] ):
literal[string]
identifier[l] = identifier[len] ( identifier[lst] )
identifier[ret] =[]
identifier[format_str] = literal[string] + identifier[str... | def get_contents_debug_adapter_protocol(self, lst, fmt=None):
"""
This method is to be used in the case where the variables are all saved by its id (and as
such don't need to have the `resolve` method called later on, so, keys don't need to
embed the reference in the key).
Note that... |
def adjust_memory(val, magnitude, direction="increase", out_modifier="", maximum=None):
"""Adjust memory based on number of cores utilized.
"""
modifier = val[-1:]
amount = float(val[:-1])
if direction == "decrease":
new_amount = amount / float(magnitude)
# dealing with a specifier l... | def function[adjust_memory, parameter[val, magnitude, direction, out_modifier, maximum]]:
constant[Adjust memory based on number of cores utilized.
]
variable[modifier] assign[=] call[name[val]][<ast.Slice object at 0x7da1b2344340>]
variable[amount] assign[=] call[name[float], parameter[call... | keyword[def] identifier[adjust_memory] ( identifier[val] , identifier[magnitude] , identifier[direction] = literal[string] , identifier[out_modifier] = literal[string] , identifier[maximum] = keyword[None] ):
literal[string]
identifier[modifier] = identifier[val] [- literal[int] :]
identifier[amount] ... | def adjust_memory(val, magnitude, direction='increase', out_modifier='', maximum=None):
"""Adjust memory based on number of cores utilized.
"""
modifier = val[-1:]
amount = float(val[:-1])
if direction == 'decrease':
new_amount = amount / float(magnitude)
# dealing with a specifier l... |
def EXCHANGE(classical_reg1, classical_reg2):
"""
Produce an EXCHANGE instruction.
:param classical_reg1: The first classical register, which gets modified.
:param classical_reg2: The second classical register, which gets modified.
:return: A ClassicalExchange instance.
"""
left = unpack_cl... | def function[EXCHANGE, parameter[classical_reg1, classical_reg2]]:
constant[
Produce an EXCHANGE instruction.
:param classical_reg1: The first classical register, which gets modified.
:param classical_reg2: The second classical register, which gets modified.
:return: A ClassicalExchange instanc... | keyword[def] identifier[EXCHANGE] ( identifier[classical_reg1] , identifier[classical_reg2] ):
literal[string]
identifier[left] = identifier[unpack_classical_reg] ( identifier[classical_reg1] )
identifier[right] = identifier[unpack_classical_reg] ( identifier[classical_reg2] )
keyword[return] id... | def EXCHANGE(classical_reg1, classical_reg2):
"""
Produce an EXCHANGE instruction.
:param classical_reg1: The first classical register, which gets modified.
:param classical_reg2: The second classical register, which gets modified.
:return: A ClassicalExchange instance.
"""
left = unpack_cl... |
def do_unmute(self, sender, body, args):
"""Unmutes the chatroom for a user"""
if sender.get('MUTED'):
sender['MUTED'] = False
self.broadcast('%s has unmuted this chatroom' % (sender['NICK'],))
for msg in sender.get('QUEUED_MESSAGES', []):
self.send_me... | def function[do_unmute, parameter[self, sender, body, args]]:
constant[Unmutes the chatroom for a user]
if call[name[sender].get, parameter[constant[MUTED]]] begin[:]
call[name[sender]][constant[MUTED]] assign[=] constant[False]
call[name[self].broadcast, parameter[binary... | keyword[def] identifier[do_unmute] ( identifier[self] , identifier[sender] , identifier[body] , identifier[args] ):
literal[string]
keyword[if] identifier[sender] . identifier[get] ( literal[string] ):
identifier[sender] [ literal[string] ]= keyword[False]
identifier[sel... | def do_unmute(self, sender, body, args):
"""Unmutes the chatroom for a user"""
if sender.get('MUTED'):
sender['MUTED'] = False
self.broadcast('%s has unmuted this chatroom' % (sender['NICK'],))
for msg in sender.get('QUEUED_MESSAGES', []):
self.send_message(msg, sender) # de... |
def extract_arguments(args, prefix=DATA_PREFIX):
"""Return a dict of arguments created by `add_parser_arguments`.
If the key in `args` contains two underscores, a nested dictionary will be
created. Only keys starting with given prefix are examined. The prefix is
stripped away and does not appear in the... | def function[extract_arguments, parameter[args, prefix]]:
constant[Return a dict of arguments created by `add_parser_arguments`.
If the key in `args` contains two underscores, a nested dictionary will be
created. Only keys starting with given prefix are examined. The prefix is
stripped away and doe... | keyword[def] identifier[extract_arguments] ( identifier[args] , identifier[prefix] = identifier[DATA_PREFIX] ):
literal[string]
identifier[data] ={}
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[iteritems] ( identifier[args] . identifier[__dict__] ):
keyword[if] ... | def extract_arguments(args, prefix=DATA_PREFIX):
"""Return a dict of arguments created by `add_parser_arguments`.
If the key in `args` contains two underscores, a nested dictionary will be
created. Only keys starting with given prefix are examined. The prefix is
stripped away and does not appear in the... |
def _update_cred(self):
"""
Updates the reduced costs with the values from the
dual solution
"""
ui = self.c[self._inds, self._x] - self._v[self._x]
self.cred = self.c - ui[:, None] - self._v[None, :] | def function[_update_cred, parameter[self]]:
constant[
Updates the reduced costs with the values from the
dual solution
]
variable[ui] assign[=] binary_operation[call[name[self].c][tuple[[<ast.Attribute object at 0x7da18eb57910>, <ast.Attribute object at 0x7da18eb573d0>]]] - call... | keyword[def] identifier[_update_cred] ( identifier[self] ):
literal[string]
identifier[ui] = identifier[self] . identifier[c] [ identifier[self] . identifier[_inds] , identifier[self] . identifier[_x] ]- identifier[self] . identifier[_v] [ identifier[self] . identifier[_x] ]
identifier[sel... | def _update_cred(self):
"""
Updates the reduced costs with the values from the
dual solution
"""
ui = self.c[self._inds, self._x] - self._v[self._x]
self.cred = self.c - ui[:, None] - self._v[None, :] |
def infer_domain(terms):
"""
Infer the domain from a collection of terms.
The algorithm for inferring domains is as follows:
- If all input terms have a domain of GENERIC, the result is GENERIC.
- If there is exactly one non-generic domain in the input terms, the result
is that domain.
... | def function[infer_domain, parameter[terms]]:
constant[
Infer the domain from a collection of terms.
The algorithm for inferring domains is as follows:
- If all input terms have a domain of GENERIC, the result is GENERIC.
- If there is exactly one non-generic domain in the input terms, the re... | keyword[def] identifier[infer_domain] ( identifier[terms] ):
literal[string]
identifier[domains] ={ identifier[t] . identifier[domain] keyword[for] identifier[t] keyword[in] identifier[terms] }
identifier[num_domains] = identifier[len] ( identifier[domains] )
keyword[if] identifier[num_doma... | def infer_domain(terms):
"""
Infer the domain from a collection of terms.
The algorithm for inferring domains is as follows:
- If all input terms have a domain of GENERIC, the result is GENERIC.
- If there is exactly one non-generic domain in the input terms, the result
is that domain.
... |
def _prepare_uri(self, service_name, **parameters):
"""Prepare the URI for a request
:param service_name: The target service
:type service_name: str
:param kwargs: query parameters
:return: The uri of the request
"""
query_parameters = []
for key, value i... | def function[_prepare_uri, parameter[self, service_name]]:
constant[Prepare the URI for a request
:param service_name: The target service
:type service_name: str
:param kwargs: query parameters
:return: The uri of the request
]
variable[query_parameters] assign[=... | keyword[def] identifier[_prepare_uri] ( identifier[self] , identifier[service_name] ,** identifier[parameters] ):
literal[string]
identifier[query_parameters] =[]
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[parameters] . identifier[items] ():
key... | def _prepare_uri(self, service_name, **parameters):
"""Prepare the URI for a request
:param service_name: The target service
:type service_name: str
:param kwargs: query parameters
:return: The uri of the request
"""
query_parameters = []
for (key, value) in paramete... |
def validate(
message,
get_certificate=lambda url: urlopen(url).read(),
certificate_url_regex=DEFAULT_CERTIFICATE_URL_REGEX,
max_age=DEFAULT_MAX_AGE
):
"""
Validate a decoded SNS message.
Parameters:
message:
Decoded SNS message.
get_certificate:
Fun... | def function[validate, parameter[message, get_certificate, certificate_url_regex, max_age]]:
constant[
Validate a decoded SNS message.
Parameters:
message:
Decoded SNS message.
get_certificate:
Function that receives a URL, and returns the certificate from that
... | keyword[def] identifier[validate] (
identifier[message] ,
identifier[get_certificate] = keyword[lambda] identifier[url] : identifier[urlopen] ( identifier[url] ). identifier[read] (),
identifier[certificate_url_regex] = identifier[DEFAULT_CERTIFICATE_URL_REGEX] ,
identifier[max_age] = identifier[DEFAULT_MAX_AGE]... | def validate(message, get_certificate=lambda url: urlopen(url).read(), certificate_url_regex=DEFAULT_CERTIFICATE_URL_REGEX, max_age=DEFAULT_MAX_AGE):
"""
Validate a decoded SNS message.
Parameters:
message:
Decoded SNS message.
get_certificate:
Function that receive... |
def calc_scores_for_node(G, node, depth_limit=22,
number_of_recommendations=None, impact_mode=10):
"""Calculate the score of multiple records."""
n, w, dep, _ = dfs_edges(G, node, depth_limit, "Record")
count_total_ways = len(n)
# print "Number of paths {}".format(len(n))
if... | def function[calc_scores_for_node, parameter[G, node, depth_limit, number_of_recommendations, impact_mode]]:
constant[Calculate the score of multiple records.]
<ast.Tuple object at 0x7da1b1629ed0> assign[=] call[name[dfs_edges], parameter[name[G], name[node], name[depth_limit], constant[Record]]]
... | keyword[def] identifier[calc_scores_for_node] ( identifier[G] , identifier[node] , identifier[depth_limit] = literal[int] ,
identifier[number_of_recommendations] = keyword[None] , identifier[impact_mode] = literal[int] ):
literal[string]
identifier[n] , identifier[w] , identifier[dep] , identifier[_] = id... | def calc_scores_for_node(G, node, depth_limit=22, number_of_recommendations=None, impact_mode=10):
"""Calculate the score of multiple records."""
(n, w, dep, _) = dfs_edges(G, node, depth_limit, 'Record')
count_total_ways = len(n)
# print "Number of paths {}".format(len(n))
if impact_mode == 0:
... |
def is_progressive(image):
"""
Check to see if an image is progressive.
"""
if not isinstance(image, Image.Image):
# Can only check PIL images for progressive encoding.
return False
return ('progressive' in image.info) or ('progression' in image.info) | def function[is_progressive, parameter[image]]:
constant[
Check to see if an image is progressive.
]
if <ast.UnaryOp object at 0x7da18c4cd4b0> begin[:]
return[constant[False]]
return[<ast.BoolOp object at 0x7da20c6ab4f0>] | keyword[def] identifier[is_progressive] ( identifier[image] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[image] , identifier[Image] . identifier[Image] ):
keyword[return] keyword[False]
keyword[return] ( literal[string] keyword[in] identifier[imag... | def is_progressive(image):
"""
Check to see if an image is progressive.
"""
if not isinstance(image, Image.Image):
# Can only check PIL images for progressive encoding.
return False # depends on [control=['if'], data=[]]
return 'progressive' in image.info or 'progression' in image.i... |
def _binary_temporary_file(self, delete):
""":return: a binary temporary file where the content is dumped to."""
file = NamedTemporaryFile("wb+", delete=delete)
self._binary_file(file)
return file | def function[_binary_temporary_file, parameter[self, delete]]:
constant[:return: a binary temporary file where the content is dumped to.]
variable[file] assign[=] call[name[NamedTemporaryFile], parameter[constant[wb+]]]
call[name[self]._binary_file, parameter[name[file]]]
return[name[file]] | keyword[def] identifier[_binary_temporary_file] ( identifier[self] , identifier[delete] ):
literal[string]
identifier[file] = identifier[NamedTemporaryFile] ( literal[string] , identifier[delete] = identifier[delete] )
identifier[self] . identifier[_binary_file] ( identifier[file] )
... | def _binary_temporary_file(self, delete):
""":return: a binary temporary file where the content is dumped to."""
file = NamedTemporaryFile('wb+', delete=delete)
self._binary_file(file)
return file |
def split_storage(path, default='osfstorage'):
"""Extract storage name from file path.
If a path begins with a known storage provider the name is removed
from the path. Otherwise the `default` storage provider is returned
and the path is not modified.
"""
path = norm_remote_path(path)
for ... | def function[split_storage, parameter[path, default]]:
constant[Extract storage name from file path.
If a path begins with a known storage provider the name is removed
from the path. Otherwise the `default` storage provider is returned
and the path is not modified.
]
variable[path] assi... | keyword[def] identifier[split_storage] ( identifier[path] , identifier[default] = literal[string] ):
literal[string]
identifier[path] = identifier[norm_remote_path] ( identifier[path] )
keyword[for] identifier[provider] keyword[in] identifier[KNOWN_PROVIDERS] :
keyword[if] identifier[pat... | def split_storage(path, default='osfstorage'):
"""Extract storage name from file path.
If a path begins with a known storage provider the name is removed
from the path. Otherwise the `default` storage provider is returned
and the path is not modified.
"""
path = norm_remote_path(path)
for p... |
def to_download():
"""
Build interval of urls to download.
We always get the first file of the next day.
Ex: 2013-01-01 => 2013-01-02.0000
"""
first_day = parse(interval_first)
last_day = parse(interval_last)
format_change = parse('2010-06-14')
one_day = datetime.timedelt... | def function[to_download, parameter[]]:
constant[
Build interval of urls to download.
We always get the first file of the next day.
Ex: 2013-01-01 => 2013-01-02.0000
]
variable[first_day] assign[=] call[name[parse], parameter[name[interval_first]]]
variable[last_day] ... | keyword[def] identifier[to_download] ():
literal[string]
identifier[first_day] = identifier[parse] ( identifier[interval_first] )
identifier[last_day] = identifier[parse] ( identifier[interval_last] )
identifier[format_change] = identifier[parse] ( literal[string] )
identifier[one_day] = ide... | def to_download():
"""
Build interval of urls to download.
We always get the first file of the next day.
Ex: 2013-01-01 => 2013-01-02.0000
"""
first_day = parse(interval_first)
last_day = parse(interval_last)
format_change = parse('2010-06-14')
one_day = datetime.timedelt... |
def _condition_as_sql(self, qn, connection):
'''
Return sql for condition.
'''
def escape(value):
if isinstance(value, bool):
value = str(int(value))
if isinstance(value, six.string_types):
# Escape params used with LIKE
... | def function[_condition_as_sql, parameter[self, qn, connection]]:
constant[
Return sql for condition.
]
def function[escape, parameter[value]]:
if call[name[isinstance], parameter[name[value], name[bool]]] begin[:]
variable[value] assign[=] call[na... | keyword[def] identifier[_condition_as_sql] ( identifier[self] , identifier[qn] , identifier[connection] ):
literal[string]
keyword[def] identifier[escape] ( identifier[value] ):
keyword[if] identifier[isinstance] ( identifier[value] , identifier[bool] ):
identifier[v... | def _condition_as_sql(self, qn, connection):
"""
Return sql for condition.
"""
def escape(value):
if isinstance(value, bool):
value = str(int(value)) # depends on [control=['if'], data=[]]
if isinstance(value, six.string_types):
# Escape params used with... |
def loadstack(self):
print("Loading stack from: %s" % self.stack_fn)
data = np.load(self.stack_fn, encoding='latin1')
#self.fn_list = list([i.decode("utf-8") for i in data['fn_list']])
self.fn_list = data['fn_list']
#Load flags originally used for stack creation
#self.fla... | def function[loadstack, parameter[self]]:
call[name[print], parameter[binary_operation[constant[Loading stack from: %s] <ast.Mod object at 0x7da2590d6920> name[self].stack_fn]]]
variable[data] assign[=] call[name[np].load, parameter[name[self].stack_fn]]
name[self].fn_list assign[=] call[name[da... | keyword[def] identifier[loadstack] ( identifier[self] ):
identifier[print] ( literal[string] % identifier[self] . identifier[stack_fn] )
identifier[data] = identifier[np] . identifier[load] ( identifier[self] . identifier[stack_fn] , identifier[encoding] = literal[string] )
identif... | def loadstack(self):
print('Loading stack from: %s' % self.stack_fn)
data = np.load(self.stack_fn, encoding='latin1')
#self.fn_list = list([i.decode("utf-8") for i in data['fn_list']])
self.fn_list = data['fn_list']
#Load flags originally used for stack creation
#self.flags = data['flags']
#... |
def get_ad_leads(self, start_date=None, end_date=None, filtering=(), page=1, page_size=100, version='v1.0'):
"""
获取朋友圈销售线索数据接口
:param start_date: 开始日期 默认今天
:param end_date: 结束日期 默认今天
:param filtering: 过滤条件 [{field: 过滤字段, operator: 操作符, values: 字段取值}]
:param page: 页码,获取指... | def function[get_ad_leads, parameter[self, start_date, end_date, filtering, page, page_size, version]]:
constant[
获取朋友圈销售线索数据接口
:param start_date: 开始日期 默认今天
:param end_date: 结束日期 默认今天
:param filtering: 过滤条件 [{field: 过滤字段, operator: 操作符, values: 字段取值}]
:param page: 页码,获取... | keyword[def] identifier[get_ad_leads] ( identifier[self] , identifier[start_date] = keyword[None] , identifier[end_date] = keyword[None] , identifier[filtering] =(), identifier[page] = literal[int] , identifier[page_size] = literal[int] , identifier[version] = literal[string] ):
literal[string]
ide... | def get_ad_leads(self, start_date=None, end_date=None, filtering=(), page=1, page_size=100, version='v1.0'):
"""
获取朋友圈销售线索数据接口
:param start_date: 开始日期 默认今天
:param end_date: 结束日期 默认今天
:param filtering: 过滤条件 [{field: 过滤字段, operator: 操作符, values: 字段取值}]
:param page: 页码,获取指定页数据... |
def show_subnetpool(self, subnetpool, **_params):
"""Fetches information of a certain subnetpool."""
return self.get(self.subnetpool_path % (subnetpool), params=_params) | def function[show_subnetpool, parameter[self, subnetpool]]:
constant[Fetches information of a certain subnetpool.]
return[call[name[self].get, parameter[binary_operation[name[self].subnetpool_path <ast.Mod object at 0x7da2590d6920> name[subnetpool]]]]] | keyword[def] identifier[show_subnetpool] ( identifier[self] , identifier[subnetpool] ,** identifier[_params] ):
literal[string]
keyword[return] identifier[self] . identifier[get] ( identifier[self] . identifier[subnetpool_path] %( identifier[subnetpool] ), identifier[params] = identifier[_params] ... | def show_subnetpool(self, subnetpool, **_params):
"""Fetches information of a certain subnetpool."""
return self.get(self.subnetpool_path % subnetpool, params=_params) |
def make_encoder(activation, num_topics, layer_sizes):
"""Create the encoder function.
Args:
activation: Activation function to use.
num_topics: The number of topics.
layer_sizes: The number of hidden units per layer in the encoder.
Returns:
encoder: A `callable` mapping a bag-of-words `Tensor` ... | def function[make_encoder, parameter[activation, num_topics, layer_sizes]]:
constant[Create the encoder function.
Args:
activation: Activation function to use.
num_topics: The number of topics.
layer_sizes: The number of hidden units per layer in the encoder.
Returns:
encoder: A `callable`... | keyword[def] identifier[make_encoder] ( identifier[activation] , identifier[num_topics] , identifier[layer_sizes] ):
literal[string]
identifier[encoder_net] = identifier[tf] . identifier[keras] . identifier[Sequential] ()
keyword[for] identifier[num_hidden_units] keyword[in] identifier[layer_sizes] :
... | def make_encoder(activation, num_topics, layer_sizes):
"""Create the encoder function.
Args:
activation: Activation function to use.
num_topics: The number of topics.
layer_sizes: The number of hidden units per layer in the encoder.
Returns:
encoder: A `callable` mapping a bag-of-words `Tensor... |
def pelix_bundles(self):
"""
List of installed bundles
"""
framework = self.__context.get_framework()
return {
bundle.get_bundle_id(): {
"name": bundle.get_symbolic_name(),
"version": bundle.get_version(),
"state": bundl... | def function[pelix_bundles, parameter[self]]:
constant[
List of installed bundles
]
variable[framework] assign[=] call[name[self].__context.get_framework, parameter[]]
return[<ast.DictComp object at 0x7da1b0349540>] | keyword[def] identifier[pelix_bundles] ( identifier[self] ):
literal[string]
identifier[framework] = identifier[self] . identifier[__context] . identifier[get_framework] ()
keyword[return] {
identifier[bundle] . identifier[get_bundle_id] ():{
literal[string] : identifier[... | def pelix_bundles(self):
"""
List of installed bundles
"""
framework = self.__context.get_framework()
return {bundle.get_bundle_id(): {'name': bundle.get_symbolic_name(), 'version': bundle.get_version(), 'state': bundle.get_state(), 'location': bundle.get_location()} for bundle in framework.... |
def serialize(self,
node: SchemaNode,
appstruct: Union[PotentialDatetimeType,
ColanderNullType]) \
-> Union[str, ColanderNullType]:
"""
Serializes Python object to string representation.
"""
if not appstru... | def function[serialize, parameter[self, node, appstruct]]:
constant[
Serializes Python object to string representation.
]
if <ast.UnaryOp object at 0x7da1b172b220> begin[:]
return[name[colander].null]
<ast.Try object at 0x7da1b172be20>
return[call[name[appstruct].isoforma... | keyword[def] identifier[serialize] ( identifier[self] ,
identifier[node] : identifier[SchemaNode] ,
identifier[appstruct] : identifier[Union] [ identifier[PotentialDatetimeType] ,
identifier[ColanderNullType] ])-> identifier[Union] [ identifier[str] , identifier[ColanderNullType] ]:
literal[string]
... | def serialize(self, node: SchemaNode, appstruct: Union[PotentialDatetimeType, ColanderNullType]) -> Union[str, ColanderNullType]:
"""
Serializes Python object to string representation.
"""
if not appstruct:
return colander.null # depends on [control=['if'], data=[]]
try:
app... |
def pop(self, till=None, priority=None):
"""
WAIT FOR NEXT ITEM ON THE QUEUE
RETURN THREAD_STOP IF QUEUE IS CLOSED
RETURN None IF till IS REACHED AND QUEUE IS STILL EMPTY
:param till: A `Signal` to stop waiting and return None
:return: A value, or a THREAD_STOP or None... | def function[pop, parameter[self, till, priority]]:
constant[
WAIT FOR NEXT ITEM ON THE QUEUE
RETURN THREAD_STOP IF QUEUE IS CLOSED
RETURN None IF till IS REACHED AND QUEUE IS STILL EMPTY
:param till: A `Signal` to stop waiting and return None
:return: A value, or a TH... | keyword[def] identifier[pop] ( identifier[self] , identifier[till] = keyword[None] , identifier[priority] = keyword[None] ):
literal[string]
keyword[if] identifier[till] keyword[is] keyword[not] keyword[None] keyword[and] keyword[not] identifier[isinstance] ( identifier[till] , identifier[Si... | def pop(self, till=None, priority=None):
"""
WAIT FOR NEXT ITEM ON THE QUEUE
RETURN THREAD_STOP IF QUEUE IS CLOSED
RETURN None IF till IS REACHED AND QUEUE IS STILL EMPTY
:param till: A `Signal` to stop waiting and return None
:return: A value, or a THREAD_STOP or None
... |
def get_isd_filenames(self, year=None, with_host=False):
""" Get filenames of raw ISD station data. """
return get_isd_filenames(self.usaf_id, year, with_host=with_host) | def function[get_isd_filenames, parameter[self, year, with_host]]:
constant[ Get filenames of raw ISD station data. ]
return[call[name[get_isd_filenames], parameter[name[self].usaf_id, name[year]]]] | keyword[def] identifier[get_isd_filenames] ( identifier[self] , identifier[year] = keyword[None] , identifier[with_host] = keyword[False] ):
literal[string]
keyword[return] identifier[get_isd_filenames] ( identifier[self] . identifier[usaf_id] , identifier[year] , identifier[with_host] = identifie... | def get_isd_filenames(self, year=None, with_host=False):
""" Get filenames of raw ISD station data. """
return get_isd_filenames(self.usaf_id, year, with_host=with_host) |
def start_slave_nodes(slaves, cl_args):
'''
Star slave nodes
'''
pids = []
for slave in slaves:
Log.info("Starting slave on %s" % slave)
cmd = "%s agent -config %s >> /tmp/nomad_client.log 2>&1 &" \
% (get_nomad_path(cl_args), get_nomad_slave_config_file(cl_args))
if not is_self(slave):
... | def function[start_slave_nodes, parameter[slaves, cl_args]]:
constant[
Star slave nodes
]
variable[pids] assign[=] list[[]]
for taget[name[slave]] in starred[name[slaves]] begin[:]
call[name[Log].info, parameter[binary_operation[constant[Starting slave on %s] <ast.Mod object ... | keyword[def] identifier[start_slave_nodes] ( identifier[slaves] , identifier[cl_args] ):
literal[string]
identifier[pids] =[]
keyword[for] identifier[slave] keyword[in] identifier[slaves] :
identifier[Log] . identifier[info] ( literal[string] % identifier[slave] )
identifier[cmd] = literal[stri... | def start_slave_nodes(slaves, cl_args):
"""
Star slave nodes
"""
pids = []
for slave in slaves:
Log.info('Starting slave on %s' % slave)
cmd = '%s agent -config %s >> /tmp/nomad_client.log 2>&1 &' % (get_nomad_path(cl_args), get_nomad_slave_config_file(cl_args))
if not is_self(sl... |
def calc_spectrogram(self, fmin=None,
method='scipy-fourier', deg=False,
window='hann', detrend='linear',
nperseg=None, noverlap=None,
boundary='constant', padded=True,
wave='morlet', warn=True):... | def function[calc_spectrogram, parameter[self, fmin, method, deg, window, detrend, nperseg, noverlap, boundary, padded, wave, warn]]:
constant[ Return the power spectrum density for each channel
The power spectrum density is computed with the chosen method
Parameters
----------
... | keyword[def] identifier[calc_spectrogram] ( identifier[self] , identifier[fmin] = keyword[None] ,
identifier[method] = literal[string] , identifier[deg] = keyword[False] ,
identifier[window] = literal[string] , identifier[detrend] = literal[string] ,
identifier[nperseg] = keyword[None] , identifier[noverlap] = key... | def calc_spectrogram(self, fmin=None, method='scipy-fourier', deg=False, window='hann', detrend='linear', nperseg=None, noverlap=None, boundary='constant', padded=True, wave='morlet', warn=True):
""" Return the power spectrum density for each channel
The power spectrum density is computed with the chosen m... |
def source_file(self):
"""Return an open file for reading the source of the code unit."""
if os.path.exists(self.filename):
# A regular text file: open it.
return open_source(self.filename)
# Maybe it's in a zip file?
source = self.file_locator.get_zip_data(self.... | def function[source_file, parameter[self]]:
constant[Return an open file for reading the source of the code unit.]
if call[name[os].path.exists, parameter[name[self].filename]] begin[:]
return[call[name[open_source], parameter[name[self].filename]]]
variable[source] assign[=] call[name[s... | keyword[def] identifier[source_file] ( identifier[self] ):
literal[string]
keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[self] . identifier[filename] ):
keyword[return] identifier[open_source] ( identifier[self] . identifier[filename] )
... | def source_file(self):
"""Return an open file for reading the source of the code unit."""
if os.path.exists(self.filename):
# A regular text file: open it.
return open_source(self.filename) # depends on [control=['if'], data=[]]
# Maybe it's in a zip file?
source = self.file_locator.get... |
def tryAccessModifiers(self, block):
"""Check for private, protected, public, signals etc... and assume we are in a
class definition. Try to find a previous private/protected/private... or
class and return its indentation or null if not found.
"""
if CFG_ACCESS_MODIFIERS < 0:
... | def function[tryAccessModifiers, parameter[self, block]]:
constant[Check for private, protected, public, signals etc... and assume we are in a
class definition. Try to find a previous private/protected/private... or
class and return its indentation or null if not found.
]
if comp... | keyword[def] identifier[tryAccessModifiers] ( identifier[self] , identifier[block] ):
literal[string]
keyword[if] identifier[CFG_ACCESS_MODIFIERS] < literal[int] :
keyword[return] keyword[None]
keyword[if] keyword[not] identifier[re] . identifier[match] ( literal[string... | def tryAccessModifiers(self, block):
"""Check for private, protected, public, signals etc... and assume we are in a
class definition. Try to find a previous private/protected/private... or
class and return its indentation or null if not found.
"""
if CFG_ACCESS_MODIFIERS < 0:
ret... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.