code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _kernel(kernel_spec):
"""Expands the kernel spec into a length 2 list.
Args:
kernel_spec: An integer or a length 1 or 2 sequence that is expanded to a
list.
Returns:
A length 2 list.
"""
if isinstance(kernel_spec, tf.compat.integral_types):
return [kernel_spec, kernel_spec]
elif len(k... | def function[_kernel, parameter[kernel_spec]]:
constant[Expands the kernel spec into a length 2 list.
Args:
kernel_spec: An integer or a length 1 or 2 sequence that is expanded to a
list.
Returns:
A length 2 list.
]
if call[name[isinstance], parameter[name[kernel_spec], name[tf].com... | keyword[def] identifier[_kernel] ( identifier[kernel_spec] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[kernel_spec] , identifier[tf] . identifier[compat] . identifier[integral_types] ):
keyword[return] [ identifier[kernel_spec] , identifier[kernel_spec] ]
keyword[elif] identifi... | def _kernel(kernel_spec):
"""Expands the kernel spec into a length 2 list.
Args:
kernel_spec: An integer or a length 1 or 2 sequence that is expanded to a
list.
Returns:
A length 2 list.
"""
if isinstance(kernel_spec, tf.compat.integral_types):
return [kernel_spec, kernel_spec] # d... |
def haurwitz(apparent_zenith):
'''
Determine clear sky GHI using the Haurwitz model.
Implements the Haurwitz clear sky model for global horizontal
irradiance (GHI) as presented in [1, 2]. A report on clear
sky models found the Haurwitz model to have the best performance
in terms of average mont... | def function[haurwitz, parameter[apparent_zenith]]:
constant[
Determine clear sky GHI using the Haurwitz model.
Implements the Haurwitz clear sky model for global horizontal
irradiance (GHI) as presented in [1, 2]. A report on clear
sky models found the Haurwitz model to have the best performan... | keyword[def] identifier[haurwitz] ( identifier[apparent_zenith] ):
literal[string]
identifier[cos_zenith] = identifier[tools] . identifier[cosd] ( identifier[apparent_zenith] . identifier[values] )
identifier[clearsky_ghi] = identifier[np] . identifier[zeros_like] ( identifier[apparent_zenith] . iden... | def haurwitz(apparent_zenith):
"""
Determine clear sky GHI using the Haurwitz model.
Implements the Haurwitz clear sky model for global horizontal
irradiance (GHI) as presented in [1, 2]. A report on clear
sky models found the Haurwitz model to have the best performance
in terms of average mont... |
def reverse_whois(self, query, exclude=[], scope='current', mode=None, **kwargs):
"""List of one or more terms to search for in the Whois record,
as a Python list or separated with the pipe character ( | ).
"""
return self._results('reverse-whois', '/v1/reverse-whois', terms=delimited... | def function[reverse_whois, parameter[self, query, exclude, scope, mode]]:
constant[List of one or more terms to search for in the Whois record,
as a Python list or separated with the pipe character ( | ).
]
return[call[name[self]._results, parameter[constant[reverse-whois], constant[/v1/... | keyword[def] identifier[reverse_whois] ( identifier[self] , identifier[query] , identifier[exclude] =[], identifier[scope] = literal[string] , identifier[mode] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[_results] ( literal[string] , lite... | def reverse_whois(self, query, exclude=[], scope='current', mode=None, **kwargs):
"""List of one or more terms to search for in the Whois record,
as a Python list or separated with the pipe character ( | ).
"""
return self._results('reverse-whois', '/v1/reverse-whois', terms=delimited(query),... |
def loads(string):
"""
Deserializes Java objects and primitive data serialized by ObjectOutputStream
from a string.
"""
f = StringIO.StringIO(string)
marshaller = JavaObjectUnmarshaller(f)
marshaller.add_transformer(DefaultObjectTransformer())
return marshaller.readObject() | def function[loads, parameter[string]]:
constant[
Deserializes Java objects and primitive data serialized by ObjectOutputStream
from a string.
]
variable[f] assign[=] call[name[StringIO].StringIO, parameter[name[string]]]
variable[marshaller] assign[=] call[name[JavaObjectUnmarshaller], pa... | keyword[def] identifier[loads] ( identifier[string] ):
literal[string]
identifier[f] = identifier[StringIO] . identifier[StringIO] ( identifier[string] )
identifier[marshaller] = identifier[JavaObjectUnmarshaller] ( identifier[f] )
identifier[marshaller] . identifier[add_transformer] ( identifier[Default... | def loads(string):
"""
Deserializes Java objects and primitive data serialized by ObjectOutputStream
from a string.
"""
f = StringIO.StringIO(string)
marshaller = JavaObjectUnmarshaller(f)
marshaller.add_transformer(DefaultObjectTransformer())
return marshaller.readObject() |
def get_frequency_grid(times,
samplesperpeak=5,
nyquistfactor=5,
minfreq=None,
maxfreq=None,
returnf0dfnf=False):
'''This calculates a frequency grid for the period finding functions in this
module... | def function[get_frequency_grid, parameter[times, samplesperpeak, nyquistfactor, minfreq, maxfreq, returnf0dfnf]]:
constant[This calculates a frequency grid for the period finding functions in this
module.
Based on the autofrequency function in astropy.stats.lombscargle.
http://docs.astropy.org/en... | keyword[def] identifier[get_frequency_grid] ( identifier[times] ,
identifier[samplesperpeak] = literal[int] ,
identifier[nyquistfactor] = literal[int] ,
identifier[minfreq] = keyword[None] ,
identifier[maxfreq] = keyword[None] ,
identifier[returnf0dfnf] = keyword[False] ):
literal[string]
identifier[... | def get_frequency_grid(times, samplesperpeak=5, nyquistfactor=5, minfreq=None, maxfreq=None, returnf0dfnf=False):
"""This calculates a frequency grid for the period finding functions in this
module.
Based on the autofrequency function in astropy.stats.lombscargle.
http://docs.astropy.org/en/stable/_mo... |
def remove_file_data(file_id, silent=True):
"""Remove file instance and associated data.
:param file_id: The :class:`invenio_files_rest.models.FileInstance` ID.
:param silent: It stops propagation of a possible arised IntegrityError
exception. (Default: ``True``)
:raises sqlalchemy.exc.Integrit... | def function[remove_file_data, parameter[file_id, silent]]:
constant[Remove file instance and associated data.
:param file_id: The :class:`invenio_files_rest.models.FileInstance` ID.
:param silent: It stops propagation of a possible arised IntegrityError
exception. (Default: ``True``)
:rais... | keyword[def] identifier[remove_file_data] ( identifier[file_id] , identifier[silent] = keyword[True] ):
literal[string]
keyword[try] :
identifier[f] = identifier[FileInstance] . identifier[get] ( identifier[file_id] )
keyword[if] keyword[not] identifier[f] . identifier[writabl... | def remove_file_data(file_id, silent=True):
"""Remove file instance and associated data.
:param file_id: The :class:`invenio_files_rest.models.FileInstance` ID.
:param silent: It stops propagation of a possible arised IntegrityError
exception. (Default: ``True``)
:raises sqlalchemy.exc.Integrit... |
def add_lvl_to_ui(self, level, header):
"""Insert the level and header into the ui.
:param level: a newly created level
:type level: :class:`jukeboxcore.gui.widgets.browser.AbstractLevel`
:param header: a newly created header
:type header: QtCore.QWidget|None
:returns: N... | def function[add_lvl_to_ui, parameter[self, level, header]]:
constant[Insert the level and header into the ui.
:param level: a newly created level
:type level: :class:`jukeboxcore.gui.widgets.browser.AbstractLevel`
:param header: a newly created header
:type header: QtCore.QWidg... | keyword[def] identifier[add_lvl_to_ui] ( identifier[self] , identifier[level] , identifier[header] ):
literal[string]
identifier[lay] = identifier[self] . identifier[layout] ()
identifier[rc] = identifier[lay] . identifier[rowCount] ()
identifier[lay] . identifier[addWidget] ( ide... | def add_lvl_to_ui(self, level, header):
"""Insert the level and header into the ui.
:param level: a newly created level
:type level: :class:`jukeboxcore.gui.widgets.browser.AbstractLevel`
:param header: a newly created header
:type header: QtCore.QWidget|None
:returns: None
... |
def load_healthchecks(self):
"""
Loads healthchecks.
"""
self.load_default_healthchecks()
if getattr(settings, 'AUTODISCOVER_HEALTHCHECKS', True):
self.autodiscover_healthchecks()
self._registry_loaded = True | def function[load_healthchecks, parameter[self]]:
constant[
Loads healthchecks.
]
call[name[self].load_default_healthchecks, parameter[]]
if call[name[getattr], parameter[name[settings], constant[AUTODISCOVER_HEALTHCHECKS], constant[True]]] begin[:]
call[name[self... | keyword[def] identifier[load_healthchecks] ( identifier[self] ):
literal[string]
identifier[self] . identifier[load_default_healthchecks] ()
keyword[if] identifier[getattr] ( identifier[settings] , literal[string] , keyword[True] ):
identifier[self] . identifier[autodiscover_... | def load_healthchecks(self):
"""
Loads healthchecks.
"""
self.load_default_healthchecks()
if getattr(settings, 'AUTODISCOVER_HEALTHCHECKS', True):
self.autodiscover_healthchecks() # depends on [control=['if'], data=[]]
self._registry_loaded = True |
def is_valid_bucket_notification_config(notifications):
"""
Validate the notifications config structure
:param notifications: Dictionary with specific structure.
:return: True if input is a valid bucket notifications structure.
Raise :exc:`InvalidArgumentError` otherwise.
"""
# check if ... | def function[is_valid_bucket_notification_config, parameter[notifications]]:
constant[
Validate the notifications config structure
:param notifications: Dictionary with specific structure.
:return: True if input is a valid bucket notifications structure.
Raise :exc:`InvalidArgumentError` oth... | keyword[def] identifier[is_valid_bucket_notification_config] ( identifier[notifications] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[notifications] , identifier[dict] ):
keyword[raise] identifier[TypeError] ( literal[string] )
keyword[if] identifi... | def is_valid_bucket_notification_config(notifications):
"""
Validate the notifications config structure
:param notifications: Dictionary with specific structure.
:return: True if input is a valid bucket notifications structure.
Raise :exc:`InvalidArgumentError` otherwise.
"""
# check if ... |
def parse(input_string, prefix=''):
"""Parses the given DSL string and returns parsed results.
Args:
input_string (str): DSL string
prefix (str): Optional prefix to add to every element name, useful to namespace things
Returns:
dict: Parsed content
"""
tree = parser.parse(input_string)
visit... | def function[parse, parameter[input_string, prefix]]:
constant[Parses the given DSL string and returns parsed results.
Args:
input_string (str): DSL string
prefix (str): Optional prefix to add to every element name, useful to namespace things
Returns:
dict: Parsed content
]
variable... | keyword[def] identifier[parse] ( identifier[input_string] , identifier[prefix] = literal[string] ):
literal[string]
identifier[tree] = identifier[parser] . identifier[parse] ( identifier[input_string] )
identifier[visitor] = identifier[ChatlVisitor] ( identifier[prefix] )
identifier[visit_parse_tree] (... | def parse(input_string, prefix=''):
"""Parses the given DSL string and returns parsed results.
Args:
input_string (str): DSL string
prefix (str): Optional prefix to add to every element name, useful to namespace things
Returns:
dict: Parsed content
"""
tree = parser.parse(input_string)
... |
def exempt(self, obj):
"""
decorator to mark a view as exempt from htmlmin.
"""
name = '%s.%s' % (obj.__module__, obj.__name__)
@wraps(obj)
def __inner(*a, **k):
return obj(*a, **k)
self._exempt_routes.add(name)
return __inner | def function[exempt, parameter[self, obj]]:
constant[
decorator to mark a view as exempt from htmlmin.
]
variable[name] assign[=] binary_operation[constant[%s.%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da18ede6890>, <ast.Attribute object at 0x7da18ede6860>]... | keyword[def] identifier[exempt] ( identifier[self] , identifier[obj] ):
literal[string]
identifier[name] = literal[string] %( identifier[obj] . identifier[__module__] , identifier[obj] . identifier[__name__] )
@ identifier[wraps] ( identifier[obj] )
keyword[def] identifier[__inne... | def exempt(self, obj):
"""
decorator to mark a view as exempt from htmlmin.
"""
name = '%s.%s' % (obj.__module__, obj.__name__)
@wraps(obj)
def __inner(*a, **k):
return obj(*a, **k)
self._exempt_routes.add(name)
return __inner |
def _write_response_to_file(self, response):
"""
Write response to the appropriate section of the file at self.local_path.
:param response: requests.Response: response containing stream-able data
"""
with open(self.local_path, 'r+b') as outfile: # open file for read/write (no tr... | def function[_write_response_to_file, parameter[self, response]]:
constant[
Write response to the appropriate section of the file at self.local_path.
:param response: requests.Response: response containing stream-able data
]
with call[name[open], parameter[name[self].local_path, ... | keyword[def] identifier[_write_response_to_file] ( identifier[self] , identifier[response] ):
literal[string]
keyword[with] identifier[open] ( identifier[self] . identifier[local_path] , literal[string] ) keyword[as] identifier[outfile] :
identifier[outfile] . identifier[seek] ( iden... | def _write_response_to_file(self, response):
"""
Write response to the appropriate section of the file at self.local_path.
:param response: requests.Response: response containing stream-able data
"""
with open(self.local_path, 'r+b') as outfile: # open file for read/write (no truncate)
... |
def compute_checksum(line):
"""Compute the TLE checksum for the given line."""
return sum((int(c) if c.isdigit() else c == '-') for c in line[0:68]) % 10 | def function[compute_checksum, parameter[line]]:
constant[Compute the TLE checksum for the given line.]
return[binary_operation[call[name[sum], parameter[<ast.GeneratorExp object at 0x7da1b0c35840>]] <ast.Mod object at 0x7da2590d6920> constant[10]]] | keyword[def] identifier[compute_checksum] ( identifier[line] ):
literal[string]
keyword[return] identifier[sum] (( identifier[int] ( identifier[c] ) keyword[if] identifier[c] . identifier[isdigit] () keyword[else] identifier[c] == literal[string] ) keyword[for] identifier[c] keyword[in] identifier[li... | def compute_checksum(line):
"""Compute the TLE checksum for the given line."""
return sum((int(c) if c.isdigit() else c == '-' for c in line[0:68])) % 10 |
def commandify(use_argcomplete=False, exit=True, *args, **kwargs):
'''Turns decorated functions into command line args
Finds the main_command and all commands and generates command line args
from these.'''
parser = CommandifyArgumentParser(*args, **kwargs)
parser.setup_arguments()
if use_argcom... | def function[commandify, parameter[use_argcomplete, exit]]:
constant[Turns decorated functions into command line args
Finds the main_command and all commands and generates command line args
from these.]
variable[parser] assign[=] call[name[CommandifyArgumentParser], parameter[<ast.Starred objec... | keyword[def] identifier[commandify] ( identifier[use_argcomplete] = keyword[False] , identifier[exit] = keyword[True] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[parser] = identifier[CommandifyArgumentParser] (* identifier[args] ,** identifier[kwargs] )
identifier[parser] ... | def commandify(use_argcomplete=False, exit=True, *args, **kwargs):
"""Turns decorated functions into command line args
Finds the main_command and all commands and generates command line args
from these."""
parser = CommandifyArgumentParser(*args, **kwargs)
parser.setup_arguments()
if use_argcom... |
def init_instance(self, key):
"""
Create an empty instance if it doesn't exist.
If the instance already exists, this is a noop.
"""
with self._lock:
if key not in self._metadata:
self._metadata[key] = {}
self._metric_ids[key] = [] | def function[init_instance, parameter[self, key]]:
constant[
Create an empty instance if it doesn't exist.
If the instance already exists, this is a noop.
]
with name[self]._lock begin[:]
if compare[name[key] <ast.NotIn object at 0x7da2590d7190> name[self]._metada... | keyword[def] identifier[init_instance] ( identifier[self] , identifier[key] ):
literal[string]
keyword[with] identifier[self] . identifier[_lock] :
keyword[if] identifier[key] keyword[not] keyword[in] identifier[self] . identifier[_metadata] :
identifier[self] . i... | def init_instance(self, key):
"""
Create an empty instance if it doesn't exist.
If the instance already exists, this is a noop.
"""
with self._lock:
if key not in self._metadata:
self._metadata[key] = {}
self._metric_ids[key] = [] # depends on [control=['... |
def inurl(needles, haystack, position='any'):
"""convenience function to make string.find return bool"""
count = 0
# lowercase everything to do case-insensitive search
haystack2 = haystack.lower()
for needle in needles:
needle2 = needle.lower()
if position == 'any':
if... | def function[inurl, parameter[needles, haystack, position]]:
constant[convenience function to make string.find return bool]
variable[count] assign[=] constant[0]
variable[haystack2] assign[=] call[name[haystack].lower, parameter[]]
for taget[name[needle]] in starred[name[needles]] begin[... | keyword[def] identifier[inurl] ( identifier[needles] , identifier[haystack] , identifier[position] = literal[string] ):
literal[string]
identifier[count] = literal[int]
identifier[haystack2] = identifier[haystack] . identifier[lower] ()
keyword[for] identifier[needle] keyword[in] iden... | def inurl(needles, haystack, position='any'):
"""convenience function to make string.find return bool"""
count = 0
# lowercase everything to do case-insensitive search
haystack2 = haystack.lower()
for needle in needles:
needle2 = needle.lower()
if position == 'any':
if ha... |
def get_defaults(self):
"""Get a dictionary that contains all the available defaults."""
defaults = self._defaults.copy()
for field_key, default in self._default_callables.items():
defaults[field_key] = default()
return defaults | def function[get_defaults, parameter[self]]:
constant[Get a dictionary that contains all the available defaults.]
variable[defaults] assign[=] call[name[self]._defaults.copy, parameter[]]
for taget[tuple[[<ast.Name object at 0x7da204567970>, <ast.Name object at 0x7da2045677f0>]]] in starred[call... | keyword[def] identifier[get_defaults] ( identifier[self] ):
literal[string]
identifier[defaults] = identifier[self] . identifier[_defaults] . identifier[copy] ()
keyword[for] identifier[field_key] , identifier[default] keyword[in] identifier[self] . identifier[_default_callables] . iden... | def get_defaults(self):
"""Get a dictionary that contains all the available defaults."""
defaults = self._defaults.copy()
for (field_key, default) in self._default_callables.items():
defaults[field_key] = default() # depends on [control=['for'], data=[]]
return defaults |
def translate(self, addr):
"""
Reverse DNS the public broadcast_address, then lookup that hostname to get the AWS-resolved IP, which
will point to the private IP address within the same datacenter.
"""
# get family of this address so we translate to the same
family = sock... | def function[translate, parameter[self, addr]]:
constant[
Reverse DNS the public broadcast_address, then lookup that hostname to get the AWS-resolved IP, which
will point to the private IP address within the same datacenter.
]
variable[family] assign[=] call[call[call[name[socket... | keyword[def] identifier[translate] ( identifier[self] , identifier[addr] ):
literal[string]
identifier[family] = identifier[socket] . identifier[getaddrinfo] ( identifier[addr] , literal[int] , identifier[socket] . identifier[AF_UNSPEC] , identifier[socket] . identifier[SOCK_STREAM] )[ lit... | def translate(self, addr):
"""
Reverse DNS the public broadcast_address, then lookup that hostname to get the AWS-resolved IP, which
will point to the private IP address within the same datacenter.
"""
# get family of this address so we translate to the same
family = socket.getaddrin... |
def export_csv(self, table, output=None, columns="*", **kwargs):
"""
Export a table to a CSV file.
If an output path is provided, write to file. Else, return a
string.
Wrapper around pandas.sql.to_csv(). See:
http://pandas.pydata.org/pandas-docs/stable/io.html#io-store-... | def function[export_csv, parameter[self, table, output, columns]]:
constant[
Export a table to a CSV file.
If an output path is provided, write to file. Else, return a
string.
Wrapper around pandas.sql.to_csv(). See:
http://pandas.pydata.org/pandas-docs/stable/io.html#i... | keyword[def] identifier[export_csv] ( identifier[self] , identifier[table] , identifier[output] = keyword[None] , identifier[columns] = literal[string] ,** identifier[kwargs] ):
literal[string]
keyword[import] identifier[pandas] . identifier[io] . identifier[sql] keyword[as] identifier[panda]
... | def export_csv(self, table, output=None, columns='*', **kwargs):
"""
Export a table to a CSV file.
If an output path is provided, write to file. Else, return a
string.
Wrapper around pandas.sql.to_csv(). See:
http://pandas.pydata.org/pandas-docs/stable/io.html#io-store-in-c... |
def add_terms_to_whitelist(self, terms):
"""
Add a list of terms to the user's company's whitelist.
:param terms: The list of terms to whitelist.
:return: The list of extracted |Indicator| objects that were whitelisted.
"""
resp = self._client.post("whitelist", json=ter... | def function[add_terms_to_whitelist, parameter[self, terms]]:
constant[
Add a list of terms to the user's company's whitelist.
:param terms: The list of terms to whitelist.
:return: The list of extracted |Indicator| objects that were whitelisted.
]
variable[resp] assign[... | keyword[def] identifier[add_terms_to_whitelist] ( identifier[self] , identifier[terms] ):
literal[string]
identifier[resp] = identifier[self] . identifier[_client] . identifier[post] ( literal[string] , identifier[json] = identifier[terms] )
keyword[return] [ identifier[Indicator] . ident... | def add_terms_to_whitelist(self, terms):
"""
Add a list of terms to the user's company's whitelist.
:param terms: The list of terms to whitelist.
:return: The list of extracted |Indicator| objects that were whitelisted.
"""
resp = self._client.post('whitelist', json=terms)
r... |
def firmware_download_input_protocol_type_scp_protocol_scp_file(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
firmware_download = ET.Element("firmware_download")
config = firmware_download
input = ET.SubElement(firmware_download, "input")
... | def function[firmware_download_input_protocol_type_scp_protocol_scp_file, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[firmware_download] assign[=] call[name[ET].Element, parameter[constant[firmwa... | keyword[def] identifier[firmware_download_input_protocol_type_scp_protocol_scp_file] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[firmware_download] = identifier[ET] . identifier[Elemen... | def firmware_download_input_protocol_type_scp_protocol_scp_file(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
firmware_download = ET.Element('firmware_download')
config = firmware_download
input = ET.SubElement(firmware_download, 'input')
protocol_type = ET.Su... |
def info(self):
"""Return cache information.
.. note:: This is not the cache info for the entire Redis key space.
"""
info = redis_conn.info()
return _CacheInfo(info['keyspace_hits'],
info['keyspace_misses'],
self.size()) | def function[info, parameter[self]]:
constant[Return cache information.
.. note:: This is not the cache info for the entire Redis key space.
]
variable[info] assign[=] call[name[redis_conn].info, parameter[]]
return[call[name[_CacheInfo], parameter[call[name[info]][constant[keyspace... | keyword[def] identifier[info] ( identifier[self] ):
literal[string]
identifier[info] = identifier[redis_conn] . identifier[info] ()
keyword[return] identifier[_CacheInfo] ( identifier[info] [ literal[string] ],
identifier[info] [ literal[string] ],
identifier[self] . ide... | def info(self):
"""Return cache information.
.. note:: This is not the cache info for the entire Redis key space.
"""
info = redis_conn.info()
return _CacheInfo(info['keyspace_hits'], info['keyspace_misses'], self.size()) |
def value(self,ascode=None):
"""Return text cast to the correct type or the selected type"""
if ascode is None:
ascode = self.code
return self.cast[ascode](self.text) | def function[value, parameter[self, ascode]]:
constant[Return text cast to the correct type or the selected type]
if compare[name[ascode] is constant[None]] begin[:]
variable[ascode] assign[=] name[self].code
return[call[call[name[self].cast][name[ascode]], parameter[name[self].text]... | keyword[def] identifier[value] ( identifier[self] , identifier[ascode] = keyword[None] ):
literal[string]
keyword[if] identifier[ascode] keyword[is] keyword[None] :
identifier[ascode] = identifier[self] . identifier[code]
keyword[return] identifier[self] . identifier[cast... | def value(self, ascode=None):
"""Return text cast to the correct type or the selected type"""
if ascode is None:
ascode = self.code # depends on [control=['if'], data=['ascode']]
return self.cast[ascode](self.text) |
def send_message(self, message):
"""Send chat message to this steam user
:param message: message to send
:type message: str
"""
self._steam.send(MsgProto(EMsg.ClientFriendMsg), {
'steamid': self.steam_id,
'chat_entry_type': EChatEntryType.ChatMsg,
... | def function[send_message, parameter[self, message]]:
constant[Send chat message to this steam user
:param message: message to send
:type message: str
]
call[name[self]._steam.send, parameter[call[name[MsgProto], parameter[name[EMsg].ClientFriendMsg]], dictionary[[<ast.Constant ... | keyword[def] identifier[send_message] ( identifier[self] , identifier[message] ):
literal[string]
identifier[self] . identifier[_steam] . identifier[send] ( identifier[MsgProto] ( identifier[EMsg] . identifier[ClientFriendMsg] ),{
literal[string] : identifier[self] . identifier[steam_id] ,... | def send_message(self, message):
"""Send chat message to this steam user
:param message: message to send
:type message: str
"""
self._steam.send(MsgProto(EMsg.ClientFriendMsg), {'steamid': self.steam_id, 'chat_entry_type': EChatEntryType.ChatMsg, 'message': message.encode('utf8')}) |
def get_default_triple():
"""
Return the default target triple LLVM is configured to produce code for.
"""
with ffi.OutputString() as out:
ffi.lib.LLVMPY_GetDefaultTargetTriple(out)
return str(out) | def function[get_default_triple, parameter[]]:
constant[
Return the default target triple LLVM is configured to produce code for.
]
with call[name[ffi].OutputString, parameter[]] begin[:]
call[name[ffi].lib.LLVMPY_GetDefaultTargetTriple, parameter[name[out]]]
return[call[... | keyword[def] identifier[get_default_triple] ():
literal[string]
keyword[with] identifier[ffi] . identifier[OutputString] () keyword[as] identifier[out] :
identifier[ffi] . identifier[lib] . identifier[LLVMPY_GetDefaultTargetTriple] ( identifier[out] )
keyword[return] identifier[str] ( ... | def get_default_triple():
"""
Return the default target triple LLVM is configured to produce code for.
"""
with ffi.OutputString() as out:
ffi.lib.LLVMPY_GetDefaultTargetTriple(out)
return str(out) # depends on [control=['with'], data=['out']] |
def updated(self):
'return datetime.datetime'
return dateutil.parser.parse(str(self.f.latestRevision.updated)) | def function[updated, parameter[self]]:
constant[return datetime.datetime]
return[call[name[dateutil].parser.parse, parameter[call[name[str], parameter[name[self].f.latestRevision.updated]]]]] | keyword[def] identifier[updated] ( identifier[self] ):
literal[string]
keyword[return] identifier[dateutil] . identifier[parser] . identifier[parse] ( identifier[str] ( identifier[self] . identifier[f] . identifier[latestRevision] . identifier[updated] )) | def updated(self):
"""return datetime.datetime"""
return dateutil.parser.parse(str(self.f.latestRevision.updated)) |
def viewBoxAxisRange(viewBox, axisNumber):
""" Calculates the range of an axis of a viewBox.
"""
rect = viewBox.childrenBoundingRect() # taken from viewBox.autoRange()
if rect is not None:
if axisNumber == X_AXIS:
return rect.left(), rect.right()
elif axisNumber == Y_AXIS:
... | def function[viewBoxAxisRange, parameter[viewBox, axisNumber]]:
constant[ Calculates the range of an axis of a viewBox.
]
variable[rect] assign[=] call[name[viewBox].childrenBoundingRect, parameter[]]
if compare[name[rect] is_not constant[None]] begin[:]
if compare[name[axisN... | keyword[def] identifier[viewBoxAxisRange] ( identifier[viewBox] , identifier[axisNumber] ):
literal[string]
identifier[rect] = identifier[viewBox] . identifier[childrenBoundingRect] ()
keyword[if] identifier[rect] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[axisNumber... | def viewBoxAxisRange(viewBox, axisNumber):
""" Calculates the range of an axis of a viewBox.
"""
rect = viewBox.childrenBoundingRect() # taken from viewBox.autoRange()
if rect is not None:
if axisNumber == X_AXIS:
return (rect.left(), rect.right()) # depends on [control=['if'], dat... |
def start_tag(self, alt=None, empty=False):
"""Return XML start tag for the receiver."""
if alt:
name = alt
else:
name = self.name
result = "<" + name
for it in self.attr:
result += ' %s="%s"' % (it, escape(self.attr[it], {'"':""", '%': "%... | def function[start_tag, parameter[self, alt, empty]]:
constant[Return XML start tag for the receiver.]
if name[alt] begin[:]
variable[name] assign[=] name[alt]
variable[result] assign[=] binary_operation[constant[<] + name[name]]
for taget[name[it]] in starred[name[self].... | keyword[def] identifier[start_tag] ( identifier[self] , identifier[alt] = keyword[None] , identifier[empty] = keyword[False] ):
literal[string]
keyword[if] identifier[alt] :
identifier[name] = identifier[alt]
keyword[else] :
identifier[name] = identifier[self] .... | def start_tag(self, alt=None, empty=False):
"""Return XML start tag for the receiver."""
if alt:
name = alt # depends on [control=['if'], data=[]]
else:
name = self.name
result = '<' + name
for it in self.attr:
result += ' %s="%s"' % (it, escape(self.attr[it], {'"': '"'... |
def _name_to_tensor(self, tensor_name):
"""The tensor with the given name.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a tf.Tensor or mtf.Tensor
"""
id1, id2 = self._tensor_name_to_ids[tensor_name]
return self._operations[id1].outputs[id2] | def function[_name_to_tensor, parameter[self, tensor_name]]:
constant[The tensor with the given name.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a tf.Tensor or mtf.Tensor
]
<ast.Tuple object at 0x7da204564100> assign[=] call[name[self]._tensor_name_to_... | keyword[def] identifier[_name_to_tensor] ( identifier[self] , identifier[tensor_name] ):
literal[string]
identifier[id1] , identifier[id2] = identifier[self] . identifier[_tensor_name_to_ids] [ identifier[tensor_name] ]
keyword[return] identifier[self] . identifier[_operations] [ identifier[id1] ]. i... | def _name_to_tensor(self, tensor_name):
"""The tensor with the given name.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a tf.Tensor or mtf.Tensor
"""
(id1, id2) = self._tensor_name_to_ids[tensor_name]
return self._operations[id1].outputs[id2] |
def _run_cnvkit_shared(inputs, backgrounds):
"""Shared functionality to run CNVkit, parallelizing over multiple BAM files.
Handles new style cases where we have pre-normalized inputs and
old cases where we run CNVkit individually.
"""
if tz.get_in(["depth", "bins", "normalized"], inputs[0]):
... | def function[_run_cnvkit_shared, parameter[inputs, backgrounds]]:
constant[Shared functionality to run CNVkit, parallelizing over multiple BAM files.
Handles new style cases where we have pre-normalized inputs and
old cases where we run CNVkit individually.
]
if call[name[tz].get_in, parame... | keyword[def] identifier[_run_cnvkit_shared] ( identifier[inputs] , identifier[backgrounds] ):
literal[string]
keyword[if] identifier[tz] . identifier[get_in] ([ literal[string] , literal[string] , literal[string] ], identifier[inputs] [ literal[int] ]):
identifier[ckouts] =[]
keyword[for... | def _run_cnvkit_shared(inputs, backgrounds):
"""Shared functionality to run CNVkit, parallelizing over multiple BAM files.
Handles new style cases where we have pre-normalized inputs and
old cases where we run CNVkit individually.
"""
if tz.get_in(['depth', 'bins', 'normalized'], inputs[0]):
... |
def get_style_id(self, style_or_name, style_type):
"""
Return the id of the style corresponding to *style_or_name*, or
|None| if *style_or_name* is |None|. If *style_or_name* is not
a style object, the style is looked up using *style_or_name* as
a style name, raising |ValueError|... | def function[get_style_id, parameter[self, style_or_name, style_type]]:
constant[
Return the id of the style corresponding to *style_or_name*, or
|None| if *style_or_name* is |None|. If *style_or_name* is not
a style object, the style is looked up using *style_or_name* as
a style... | keyword[def] identifier[get_style_id] ( identifier[self] , identifier[style_or_name] , identifier[style_type] ):
literal[string]
keyword[if] identifier[style_or_name] keyword[is] keyword[None] :
keyword[return] keyword[None]
keyword[elif] identifier[isinstance] ( identif... | def get_style_id(self, style_or_name, style_type):
"""
Return the id of the style corresponding to *style_or_name*, or
|None| if *style_or_name* is |None|. If *style_or_name* is not
a style object, the style is looked up using *style_or_name* as
a style name, raising |ValueError| if ... |
def argshash(self, args, kwargs):
"Hash mutable arguments' containers with immutable keys and values."
a = repr(args)
b = repr(sorted((repr(k), repr(v)) for k, v in kwargs.items()))
return a + b | def function[argshash, parameter[self, args, kwargs]]:
constant[Hash mutable arguments' containers with immutable keys and values.]
variable[a] assign[=] call[name[repr], parameter[name[args]]]
variable[b] assign[=] call[name[repr], parameter[call[name[sorted], parameter[<ast.GeneratorExp object... | keyword[def] identifier[argshash] ( identifier[self] , identifier[args] , identifier[kwargs] ):
literal[string]
identifier[a] = identifier[repr] ( identifier[args] )
identifier[b] = identifier[repr] ( identifier[sorted] (( identifier[repr] ( identifier[k] ), identifier[repr] ( identifier[v... | def argshash(self, args, kwargs):
"""Hash mutable arguments' containers with immutable keys and values."""
a = repr(args)
b = repr(sorted(((repr(k), repr(v)) for (k, v) in kwargs.items())))
return a + b |
def create(cls, type):
""" Return the created tag by specifying an integer """
if type == 0: return TagEnd()
elif type == 1: return TagShowFrame()
elif type == 2: return TagDefineShape()
elif type == 4: return TagPlaceObject()
elif type == 5: return TagRemoveObject()
... | def function[create, parameter[cls, type]]:
constant[ Return the created tag by specifying an integer ]
if compare[name[type] equal[==] constant[0]] begin[:]
return[call[name[TagEnd], parameter[]]] | keyword[def] identifier[create] ( identifier[cls] , identifier[type] ):
literal[string]
keyword[if] identifier[type] == literal[int] : keyword[return] identifier[TagEnd] ()
keyword[elif] identifier[type] == literal[int] : keyword[return] identifier[TagShowFrame] ()
keyword[eli... | def create(cls, type):
""" Return the created tag by specifying an integer """
if type == 0:
return TagEnd() # depends on [control=['if'], data=[]]
elif type == 1:
return TagShowFrame() # depends on [control=['if'], data=[]]
elif type == 2:
return TagDefineShape() # depends on... |
def plotEzJz(self,*args,**kwargs):
"""
NAME:
plotEzJz
PURPOSE:
plot E_z(.)/sqrt(dens(R)) along the orbit
INPUT:
pot= Potential instance or list of instances in which the orbit was
integrated
d1= - plot Ez vs d1: e.g., 't', 'z',... | def function[plotEzJz, parameter[self]]:
constant[
NAME:
plotEzJz
PURPOSE:
plot E_z(.)/sqrt(dens(R)) along the orbit
INPUT:
pot= Potential instance or list of instances in which the orbit was
integrated
d1= - plot Ez vs d1: e.g... | keyword[def] identifier[plotEzJz] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[labeldict] ={ literal[string] : literal[string] , literal[string] : literal[string] , literal[string] : literal[string] , literal[string] : literal[string] ,
litera... | def plotEzJz(self, *args, **kwargs):
"""
NAME:
plotEzJz
PURPOSE:
plot E_z(.)/sqrt(dens(R)) along the orbit
INPUT:
pot= Potential instance or list of instances in which the orbit was
integrated
d1= - plot Ez vs d1: e.g., 't', 'z', '... |
def getChanges(self, request):
"""Catch a POST request from BitBucket and start a build process
Check the URL below if you require more information about payload
https://confluence.atlassian.com/display/BITBUCKET/POST+Service+Management
:param request: the http request Twisted object
... | def function[getChanges, parameter[self, request]]:
constant[Catch a POST request from BitBucket and start a build process
Check the URL below if you require more information about payload
https://confluence.atlassian.com/display/BITBUCKET/POST+Service+Management
:param request: the ht... | keyword[def] identifier[getChanges] ( identifier[self] , identifier[request] ):
literal[string]
identifier[event_type] = identifier[request] . identifier[getHeader] ( identifier[_HEADER_EVENT] )
identifier[event_type] = identifier[bytes2unicode] ( identifier[event_type] )
identif... | def getChanges(self, request):
"""Catch a POST request from BitBucket and start a build process
Check the URL below if you require more information about payload
https://confluence.atlassian.com/display/BITBUCKET/POST+Service+Management
:param request: the http request Twisted object
... |
def cmdline_split(s: str, platform: Union[int, str] = 'this') -> List[str]:
"""
As per
https://stackoverflow.com/questions/33560364/python-windows-parsing-command-lines-with-shlex.
Multi-platform variant of ``shlex.split()`` for command-line splitting.
For use with ``subprocess``, for ``argv`` inje... | def function[cmdline_split, parameter[s, platform]]:
constant[
As per
https://stackoverflow.com/questions/33560364/python-windows-parsing-command-lines-with-shlex.
Multi-platform variant of ``shlex.split()`` for command-line splitting.
For use with ``subprocess``, for ``argv`` injection etc. Us... | keyword[def] identifier[cmdline_split] ( identifier[s] : identifier[str] , identifier[platform] : identifier[Union] [ identifier[int] , identifier[str] ]= literal[string] )-> identifier[List] [ identifier[str] ]:
literal[string]
keyword[if] identifier[platform] == literal[string] :
identifier[pla... | def cmdline_split(s: str, platform: Union[int, str]='this') -> List[str]:
"""
As per
https://stackoverflow.com/questions/33560364/python-windows-parsing-command-lines-with-shlex.
Multi-platform variant of ``shlex.split()`` for command-line splitting.
For use with ``subprocess``, for ``argv`` inject... |
def set_optional_elements(self):
"""Sets elements considered option by RSS spec"""
self.set_categories()
self.set_copyright()
self.set_generator()
self.set_image()
self.set_language()
self.set_last_build_date()
self.set_managing_editor()
self.set_p... | def function[set_optional_elements, parameter[self]]:
constant[Sets elements considered option by RSS spec]
call[name[self].set_categories, parameter[]]
call[name[self].set_copyright, parameter[]]
call[name[self].set_generator, parameter[]]
call[name[self].set_image, parameter[]]... | keyword[def] identifier[set_optional_elements] ( identifier[self] ):
literal[string]
identifier[self] . identifier[set_categories] ()
identifier[self] . identifier[set_copyright] ()
identifier[self] . identifier[set_generator] ()
identifier[self] . identifier[set_image] (... | def set_optional_elements(self):
"""Sets elements considered option by RSS spec"""
self.set_categories()
self.set_copyright()
self.set_generator()
self.set_image()
self.set_language()
self.set_last_build_date()
self.set_managing_editor()
self.set_published_date()
self.set_pubsubh... |
def ipoib_interfaces():
"""Return a list of IPOIB capable ethernet interfaces"""
interfaces = []
for interface in network_interfaces():
try:
driver = re.search('^driver: (.+)$', subprocess.check_output([
'ethtool', '-i',
interface]), re.M).group(1)
... | def function[ipoib_interfaces, parameter[]]:
constant[Return a list of IPOIB capable ethernet interfaces]
variable[interfaces] assign[=] list[[]]
for taget[name[interface]] in starred[call[name[network_interfaces], parameter[]]] begin[:]
<ast.Try object at 0x7da18f812a40>
return[name... | keyword[def] identifier[ipoib_interfaces] ():
literal[string]
identifier[interfaces] =[]
keyword[for] identifier[interface] keyword[in] identifier[network_interfaces] ():
keyword[try] :
identifier[driver] = identifier[re] . identifier[search] ( literal[string] , identifier[su... | def ipoib_interfaces():
"""Return a list of IPOIB capable ethernet interfaces"""
interfaces = []
for interface in network_interfaces():
try:
driver = re.search('^driver: (.+)$', subprocess.check_output(['ethtool', '-i', interface]), re.M).group(1)
if driver in IPOIB_DRIVERS:
... |
def get_tab(self, model_alias, object, tab_code):
"""
Get tab for given object and tab code
:param model_alias:
:param object: Object used to render tab
:param tab_code: Tab code to use
:return:
"""
model_alias = self.get_model_alias(model_alias)
... | def function[get_tab, parameter[self, model_alias, object, tab_code]]:
constant[
Get tab for given object and tab code
:param model_alias:
:param object: Object used to render tab
:param tab_code: Tab code to use
:return:
]
variable[model_alias] assign[=]... | keyword[def] identifier[get_tab] ( identifier[self] , identifier[model_alias] , identifier[object] , identifier[tab_code] ):
literal[string]
identifier[model_alias] = identifier[self] . identifier[get_model_alias] ( identifier[model_alias] )
keyword[for] identifier[item] keyword[in] ide... | def get_tab(self, model_alias, object, tab_code):
"""
Get tab for given object and tab code
:param model_alias:
:param object: Object used to render tab
:param tab_code: Tab code to use
:return:
"""
model_alias = self.get_model_alias(model_alias)
for item in ... |
def list_all(self, per_page=10, omit=None):
"""List all groups.
Since the order of groups is determined by recent activity, this is the
recommended way to obtain a list of all groups. See
:func:`~groupy.api.groups.Groups.list` for details about ``omit``.
:param int per_page: nu... | def function[list_all, parameter[self, per_page, omit]]:
constant[List all groups.
Since the order of groups is determined by recent activity, this is the
recommended way to obtain a list of all groups. See
:func:`~groupy.api.groups.Groups.list` for details about ``omit``.
:par... | keyword[def] identifier[list_all] ( identifier[self] , identifier[per_page] = literal[int] , identifier[omit] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[list] ( identifier[per_page] = identifier[per_page] , identifier[omit] = identifier[omit] ). identifier[aut... | def list_all(self, per_page=10, omit=None):
"""List all groups.
Since the order of groups is determined by recent activity, this is the
recommended way to obtain a list of all groups. See
:func:`~groupy.api.groups.Groups.list` for details about ``omit``.
:param int per_page: number... |
def delay(
self,
identifier: typing.Any,
until: typing.Union[int, float]=-1,
) -> bool:
"""Delay a deferred function until the given time.
Args:
identifier (typing.Any): The identifier returned from a call
to defer or defer_for.
... | def function[delay, parameter[self, identifier, until]]:
constant[Delay a deferred function until the given time.
Args:
identifier (typing.Any): The identifier returned from a call
to defer or defer_for.
until (typing.Union[int, float]): A numeric value that repr... | keyword[def] identifier[delay] (
identifier[self] ,
identifier[identifier] : identifier[typing] . identifier[Any] ,
identifier[until] : identifier[typing] . identifier[Union] [ identifier[int] , identifier[float] ]=- literal[int] ,
)-> identifier[bool] :
literal[string]
keyword[raise] identifie... | def delay(self, identifier: typing.Any, until: typing.Union[int, float]=-1) -> bool:
"""Delay a deferred function until the given time.
Args:
identifier (typing.Any): The identifier returned from a call
to defer or defer_for.
until (typing.Union[int, float]): A numer... |
def session_dump(self, cell, hash, fname_session):
"""
Dump ipython session to file
:param hash: cell hash
:param fname_session: output filename
:return:
"""
logging.debug('Cell {}: Dumping session to {}'.format(hash, fname_session))
inject_code = ['impo... | def function[session_dump, parameter[self, cell, hash, fname_session]]:
constant[
Dump ipython session to file
:param hash: cell hash
:param fname_session: output filename
:return:
]
call[name[logging].debug, parameter[call[constant[Cell {}: Dumping session to {}]... | keyword[def] identifier[session_dump] ( identifier[self] , identifier[cell] , identifier[hash] , identifier[fname_session] ):
literal[string]
identifier[logging] . identifier[debug] ( literal[string] . identifier[format] ( identifier[hash] , identifier[fname_session] ))
identifier[inject... | def session_dump(self, cell, hash, fname_session):
"""
Dump ipython session to file
:param hash: cell hash
:param fname_session: output filename
:return:
"""
logging.debug('Cell {}: Dumping session to {}'.format(hash, fname_session))
inject_code = ['import dill', 'dil... |
def dist_abs(self, src, tar, *args, **kwargs):
"""Return absolute distance.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
*args
Variable length argument list.
**kwargs
... | def function[dist_abs, parameter[self, src, tar]]:
constant[Return absolute distance.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
*args
Variable length argument list.
**kw... | keyword[def] identifier[dist_abs] ( identifier[self] , identifier[src] , identifier[tar] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[dist] ( identifier[src] , identifier[tar] ,* identifier[args] ,** identifier[kwargs] ) | def dist_abs(self, src, tar, *args, **kwargs):
"""Return absolute distance.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
*args
Variable length argument list.
**kwargs
... |
def send_calibrate_accelerometer(self, simple=False):
"""Request accelerometer calibration.
:param simple: if True, perform simple accelerometer calibration
"""
calibration_command = self.message_factory.command_long_encode(
self._handler.target_system, 0, # target_system,... | def function[send_calibrate_accelerometer, parameter[self, simple]]:
constant[Request accelerometer calibration.
:param simple: if True, perform simple accelerometer calibration
]
variable[calibration_command] assign[=] call[name[self].message_factory.command_long_encode, parameter[name... | keyword[def] identifier[send_calibrate_accelerometer] ( identifier[self] , identifier[simple] = keyword[False] ):
literal[string]
identifier[calibration_command] = identifier[self] . identifier[message_factory] . identifier[command_long_encode] (
identifier[self] . identifier[_handler] . ... | def send_calibrate_accelerometer(self, simple=False):
"""Request accelerometer calibration.
:param simple: if True, perform simple accelerometer calibration
""" # target_system, target_component
# command
# confirmation
# param 1, 1: gyro calibration, 3: gyro temperature calibration
... |
def hacked_pep257(to_lint):
"""
Check for the presence of docstrings, but ignore some of the options
"""
def ignore(*args, **kwargs):
pass
pep257.check_blank_before_after_class = ignore
pep257.check_blank_after_last_paragraph = ignore
pep257.check_blank_after_summary = ignore
pe... | def function[hacked_pep257, parameter[to_lint]]:
constant[
Check for the presence of docstrings, but ignore some of the options
]
def function[ignore, parameter[]]:
pass
name[pep257].check_blank_before_after_class assign[=] name[ignore]
name[pep257].check_blank_after_last... | keyword[def] identifier[hacked_pep257] ( identifier[to_lint] ):
literal[string]
keyword[def] identifier[ignore] (* identifier[args] ,** identifier[kwargs] ):
keyword[pass]
identifier[pep257] . identifier[check_blank_before_after_class] = identifier[ignore]
identifier[pep257] . identi... | def hacked_pep257(to_lint):
"""
Check for the presence of docstrings, but ignore some of the options
"""
def ignore(*args, **kwargs):
pass
pep257.check_blank_before_after_class = ignore
pep257.check_blank_after_last_paragraph = ignore
pep257.check_blank_after_summary = ignore
pe... |
def head(self, urls=None, **overrides):
"""Sets the acceptable HTTP method to HEAD"""
if urls is not None:
overrides['urls'] = urls
return self.where(accept='HEAD', **overrides) | def function[head, parameter[self, urls]]:
constant[Sets the acceptable HTTP method to HEAD]
if compare[name[urls] is_not constant[None]] begin[:]
call[name[overrides]][constant[urls]] assign[=] name[urls]
return[call[name[self].where, parameter[]]] | keyword[def] identifier[head] ( identifier[self] , identifier[urls] = keyword[None] ,** identifier[overrides] ):
literal[string]
keyword[if] identifier[urls] keyword[is] keyword[not] keyword[None] :
identifier[overrides] [ literal[string] ]= identifier[urls]
keyword[retur... | def head(self, urls=None, **overrides):
"""Sets the acceptable HTTP method to HEAD"""
if urls is not None:
overrides['urls'] = urls # depends on [control=['if'], data=['urls']]
return self.where(accept='HEAD', **overrides) |
async def close(self) -> None:
"""Complete queued queries/cursors and close the connection."""
await self._execute(self._conn.close)
self._running = False
self._connection = None | <ast.AsyncFunctionDef object at 0x7da1b1dc77c0> | keyword[async] keyword[def] identifier[close] ( identifier[self] )-> keyword[None] :
literal[string]
keyword[await] identifier[self] . identifier[_execute] ( identifier[self] . identifier[_conn] . identifier[close] )
identifier[self] . identifier[_running] = keyword[False]
iden... | async def close(self) -> None:
"""Complete queued queries/cursors and close the connection."""
await self._execute(self._conn.close)
self._running = False
self._connection = None |
def _build_url(*args, **kwargs) -> str:
"""
Return a valid url.
"""
resource_url = API_RESOURCES_URLS
for key in args:
resource_url = resource_url[key]
if kwargs:
resource_url = resource_url.format(**kwargs)
return urljoin(URL, resource_url) | def function[_build_url, parameter[]]:
constant[
Return a valid url.
]
variable[resource_url] assign[=] name[API_RESOURCES_URLS]
for taget[name[key]] in starred[name[args]] begin[:]
variable[resource_url] assign[=] call[name[resource_url]][name[key]]
if name[kwarg... | keyword[def] identifier[_build_url] (* identifier[args] ,** identifier[kwargs] )-> identifier[str] :
literal[string]
identifier[resource_url] = identifier[API_RESOURCES_URLS]
keyword[for] identifier[key] keyword[in] identifier[args] :
identifier[resource_url] = identifier[resource_url] [ ... | def _build_url(*args, **kwargs) -> str:
"""
Return a valid url.
"""
resource_url = API_RESOURCES_URLS
for key in args:
resource_url = resource_url[key] # depends on [control=['for'], data=['key']]
if kwargs:
resource_url = resource_url.format(**kwargs) # depends on [control=['i... |
def update(self, heap):
"""Update the item descriptors and items from an incoming heap.
Parameters
----------
heap : :class:`spead2.recv.Heap`
Incoming heap
Returns
-------
dict
Items that have been updated from this heap, indexed by name... | def function[update, parameter[self, heap]]:
constant[Update the item descriptors and items from an incoming heap.
Parameters
----------
heap : :class:`spead2.recv.Heap`
Incoming heap
Returns
-------
dict
Items that have been updated from... | keyword[def] identifier[update] ( identifier[self] , identifier[heap] ):
literal[string]
keyword[for] identifier[descriptor] keyword[in] identifier[heap] . identifier[get_descriptors] ():
identifier[item] = identifier[Item] . identifier[from_raw] ( identifier[descriptor] , identifie... | def update(self, heap):
"""Update the item descriptors and items from an incoming heap.
Parameters
----------
heap : :class:`spead2.recv.Heap`
Incoming heap
Returns
-------
dict
Items that have been updated from this heap, indexed by name
... |
def solve_loop(slsp, u_span, j_coup):
"""Calculates the quasiparticle for the input loop of:
@param slsp: Slave spin Object
@param Uspan: local Couloumb interation
@param J_coup: Fraction of Uspan of Hund coupling strength"""
zet, lam, eps, hlog, mean_f = [], [], [], [], [None]
for... | def function[solve_loop, parameter[slsp, u_span, j_coup]]:
constant[Calculates the quasiparticle for the input loop of:
@param slsp: Slave spin Object
@param Uspan: local Couloumb interation
@param J_coup: Fraction of Uspan of Hund coupling strength]
<ast.Tuple object at 0x7da207... | keyword[def] identifier[solve_loop] ( identifier[slsp] , identifier[u_span] , identifier[j_coup] ):
literal[string]
identifier[zet] , identifier[lam] , identifier[eps] , identifier[hlog] , identifier[mean_f] =[],[],[],[],[ keyword[None] ]
keyword[for] identifier[u] keyword[in] identifier[u_span] ... | def solve_loop(slsp, u_span, j_coup):
"""Calculates the quasiparticle for the input loop of:
@param slsp: Slave spin Object
@param Uspan: local Couloumb interation
@param J_coup: Fraction of Uspan of Hund coupling strength"""
(zet, lam, eps, hlog, mean_f) = ([], [], [], [], [None])
f... |
def asfreq(self, freq, method=None, how=None, normalize=False,
fill_value=None):
"""
Convert TimeSeries to specified frequency.
Optionally provide filling method to pad/backfill missing values.
Returns the original data conformed to a new index with the specified
... | def function[asfreq, parameter[self, freq, method, how, normalize, fill_value]]:
constant[
Convert TimeSeries to specified frequency.
Optionally provide filling method to pad/backfill missing values.
Returns the original data conformed to a new index with the specified
frequenc... | keyword[def] identifier[asfreq] ( identifier[self] , identifier[freq] , identifier[method] = keyword[None] , identifier[how] = keyword[None] , identifier[normalize] = keyword[False] ,
identifier[fill_value] = keyword[None] ):
literal[string]
keyword[from] identifier[pandas] . identifier[core] . i... | def asfreq(self, freq, method=None, how=None, normalize=False, fill_value=None):
"""
Convert TimeSeries to specified frequency.
Optionally provide filling method to pad/backfill missing values.
Returns the original data conformed to a new index with the specified
frequency. ``resam... |
def refresh_db(full=False, **kwargs):
'''
Updates the remote repos database.
full : False
Set to ``True`` to force a refresh of the pkg DB from all publishers,
regardless of the last refresh time.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
salt '*'... | def function[refresh_db, parameter[full]]:
constant[
Updates the remote repos database.
full : False
Set to ``True`` to force a refresh of the pkg DB from all publishers,
regardless of the last refresh time.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
... | keyword[def] identifier[refresh_db] ( identifier[full] = keyword[False] ,** identifier[kwargs] ):
literal[string]
identifier[salt] . identifier[utils] . identifier[pkg] . identifier[clear_rtag] ( identifier[__opts__] )
keyword[if] identifier[full] :
keyword[return] identifier[__salt__]... | def refresh_db(full=False, **kwargs):
"""
Updates the remote repos database.
full : False
Set to ``True`` to force a refresh of the pkg DB from all publishers,
regardless of the last refresh time.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
salt '*'... |
def recv_msg(self):
'''message receive routine for UDP link'''
self.pre_message()
s = self.recv()
if len(s) > 0:
if self.first_byte:
self.auto_mavlink_version(s)
m = self.mav.parse_char(s)
if m is not None:
self.post_message(m)
... | def function[recv_msg, parameter[self]]:
constant[message receive routine for UDP link]
call[name[self].pre_message, parameter[]]
variable[s] assign[=] call[name[self].recv, parameter[]]
if compare[call[name[len], parameter[name[s]]] greater[>] constant[0]] begin[:]
if na... | keyword[def] identifier[recv_msg] ( identifier[self] ):
literal[string]
identifier[self] . identifier[pre_message] ()
identifier[s] = identifier[self] . identifier[recv] ()
keyword[if] identifier[len] ( identifier[s] )> literal[int] :
keyword[if] identifier[self] . ... | def recv_msg(self):
"""message receive routine for UDP link"""
self.pre_message()
s = self.recv()
if len(s) > 0:
if self.first_byte:
self.auto_mavlink_version(s) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]]
m = self.mav.parse_char(s)
if m is... |
def get(self, path_info):
"""Gets the checksum for the specified path info. Checksum will be
retrieved from the state database if available.
Args:
path_info (dict): path info to get the checksum for.
Returns:
str or None: checksum for the specified path info or ... | def function[get, parameter[self, path_info]]:
constant[Gets the checksum for the specified path info. Checksum will be
retrieved from the state database if available.
Args:
path_info (dict): path info to get the checksum for.
Returns:
str or None: checksum for ... | keyword[def] identifier[get] ( identifier[self] , identifier[path_info] ):
literal[string]
keyword[assert] identifier[path_info] [ literal[string] ]== literal[string]
identifier[path] = identifier[path_info] [ literal[string] ]
keyword[if] keyword[not] identifier[os] . identi... | def get(self, path_info):
"""Gets the checksum for the specified path info. Checksum will be
retrieved from the state database if available.
Args:
path_info (dict): path info to get the checksum for.
Returns:
str or None: checksum for the specified path info or None... |
def pl_resolve(ci, cj):
"""Return all clauses that can be obtained by resolving clauses ci and cj.
>>> for res in pl_resolve(to_cnf(A|B|C), to_cnf(~B|~C|F)):
... ppset(disjuncts(res))
set([A, C, F, ~C])
set([A, B, F, ~B])
"""
clauses = []
for di in disjuncts(ci):
for dj in dis... | def function[pl_resolve, parameter[ci, cj]]:
constant[Return all clauses that can be obtained by resolving clauses ci and cj.
>>> for res in pl_resolve(to_cnf(A|B|C), to_cnf(~B|~C|F)):
... ppset(disjuncts(res))
set([A, C, F, ~C])
set([A, B, F, ~B])
]
variable[clauses] assign[=] li... | keyword[def] identifier[pl_resolve] ( identifier[ci] , identifier[cj] ):
literal[string]
identifier[clauses] =[]
keyword[for] identifier[di] keyword[in] identifier[disjuncts] ( identifier[ci] ):
keyword[for] identifier[dj] keyword[in] identifier[disjuncts] ( identifier[cj] ):
... | def pl_resolve(ci, cj):
"""Return all clauses that can be obtained by resolving clauses ci and cj.
>>> for res in pl_resolve(to_cnf(A|B|C), to_cnf(~B|~C|F)):
... ppset(disjuncts(res))
set([A, C, F, ~C])
set([A, B, F, ~B])
"""
clauses = []
for di in disjuncts(ci):
for dj in dis... |
def write(self, fptr):
"""Write a fragment list box to file.
"""
self._validate(writing=True)
num_items = len(self.fragment_offset)
length = 8 + 2 + num_items * 14
fptr.write(struct.pack('>I4s', length, b'flst'))
fptr.write(struct.pack('>H', num_items))
fo... | def function[write, parameter[self, fptr]]:
constant[Write a fragment list box to file.
]
call[name[self]._validate, parameter[]]
variable[num_items] assign[=] call[name[len], parameter[name[self].fragment_offset]]
variable[length] assign[=] binary_operation[binary_operation[cons... | keyword[def] identifier[write] ( identifier[self] , identifier[fptr] ):
literal[string]
identifier[self] . identifier[_validate] ( identifier[writing] = keyword[True] )
identifier[num_items] = identifier[len] ( identifier[self] . identifier[fragment_offset] )
identifier[length] = ... | def write(self, fptr):
"""Write a fragment list box to file.
"""
self._validate(writing=True)
num_items = len(self.fragment_offset)
length = 8 + 2 + num_items * 14
fptr.write(struct.pack('>I4s', length, b'flst'))
fptr.write(struct.pack('>H', num_items))
for j in range(num_items):
... |
def CLASSDEF(self, node):
"""Check names used in a class definition, including its decorators,
base classes, and the body of its definition.
Additionally, add its name to the current scope.
"""
for deco in node.decorator_list:
self.handleNode(deco, node)
for... | def function[CLASSDEF, parameter[self, node]]:
constant[Check names used in a class definition, including its decorators,
base classes, and the body of its definition.
Additionally, add its name to the current scope.
]
for taget[name[deco]] in starred[name[node].decorator_list]... | keyword[def] identifier[CLASSDEF] ( identifier[self] , identifier[node] ):
literal[string]
keyword[for] identifier[deco] keyword[in] identifier[node] . identifier[decorator_list] :
identifier[self] . identifier[handleNode] ( identifier[deco] , identifier[node] )
keyword[for... | def CLASSDEF(self, node):
"""Check names used in a class definition, including its decorators,
base classes, and the body of its definition.
Additionally, add its name to the current scope.
"""
for deco in node.decorator_list:
self.handleNode(deco, node) # depends on [control=... |
def resolve_ssl_version(candidate):
"""
like resolve_cert_reqs
"""
if candidate is None:
return PROTOCOL_SSLv23
if isinstance(candidate, str):
res = getattr(ssl, candidate, None)
if res is None:
res = getattr(ssl, 'PROTOCOL_' + candidate)
return res
... | def function[resolve_ssl_version, parameter[candidate]]:
constant[
like resolve_cert_reqs
]
if compare[name[candidate] is constant[None]] begin[:]
return[name[PROTOCOL_SSLv23]]
if call[name[isinstance], parameter[name[candidate], name[str]]] begin[:]
variable[res]... | keyword[def] identifier[resolve_ssl_version] ( identifier[candidate] ):
literal[string]
keyword[if] identifier[candidate] keyword[is] keyword[None] :
keyword[return] identifier[PROTOCOL_SSLv23]
keyword[if] identifier[isinstance] ( identifier[candidate] , identifier[str] ):
ide... | def resolve_ssl_version(candidate):
"""
like resolve_cert_reqs
"""
if candidate is None:
return PROTOCOL_SSLv23 # depends on [control=['if'], data=[]]
if isinstance(candidate, str):
res = getattr(ssl, candidate, None)
if res is None:
res = getattr(ssl, 'PROTOCOL_... |
def _old_forney(self, omega, X, k=None):
'''Computes the error magnitudes (only works with errors or erasures under t = floor((n-k)/2), not with erasures above (n-k)//2)'''
# XXX Is floor division okay here? Should this be ceiling?
if not k: k = self.k
t = (self.n - k) // 2
Y = ... | def function[_old_forney, parameter[self, omega, X, k]]:
constant[Computes the error magnitudes (only works with errors or erasures under t = floor((n-k)/2), not with erasures above (n-k)//2)]
if <ast.UnaryOp object at 0x7da18dc07340> begin[:]
variable[k] assign[=] name[self].k
v... | keyword[def] identifier[_old_forney] ( identifier[self] , identifier[omega] , identifier[X] , identifier[k] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[k] : identifier[k] = identifier[self] . identifier[k]
identifier[t] =( identifier[self] . identifie... | def _old_forney(self, omega, X, k=None):
"""Computes the error magnitudes (only works with errors or erasures under t = floor((n-k)/2), not with erasures above (n-k)//2)"""
# XXX Is floor division okay here? Should this be ceiling?
if not k:
k = self.k # depends on [control=['if'], data=[]]
t =... |
def mean_squared_error(data, ground_truth, mask=None,
normalized=False, force_lower_is_better=True):
r"""Return mean squared L2 distance between ``data`` and ``ground_truth``.
See also `this Wikipedia article
<https://en.wikipedia.org/wiki/Mean_squared_error>`_.
Parameters
-... | def function[mean_squared_error, parameter[data, ground_truth, mask, normalized, force_lower_is_better]]:
constant[Return mean squared L2 distance between ``data`` and ``ground_truth``.
See also `this Wikipedia article
<https://en.wikipedia.org/wiki/Mean_squared_error>`_.
Parameters
----------... | keyword[def] identifier[mean_squared_error] ( identifier[data] , identifier[ground_truth] , identifier[mask] = keyword[None] ,
identifier[normalized] = keyword[False] , identifier[force_lower_is_better] = keyword[True] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[data] , ... | def mean_squared_error(data, ground_truth, mask=None, normalized=False, force_lower_is_better=True):
"""Return mean squared L2 distance between ``data`` and ``ground_truth``.
See also `this Wikipedia article
<https://en.wikipedia.org/wiki/Mean_squared_error>`_.
Parameters
----------
data : `Te... |
def convert_html_to_text(value, preserve_urls=False):
r"""
>>> convert_html_to_text(
... '''
... <html><body>
... Look & click
... <a href="https://example.com">here</a>
... </body></html>''', preserve_urls=True)
'Look & click here (https://example.com)'
... | def function[convert_html_to_text, parameter[value, preserve_urls]]:
constant[
>>> convert_html_to_text(
... '''
... <html><body>
... Look & click
... <a href="https://example.com">here</a>
... </body></html>''', preserve_urls=True)
'Look & click here ... | keyword[def] identifier[convert_html_to_text] ( identifier[value] , identifier[preserve_urls] = keyword[False] ):
literal[string]
identifier[s] = identifier[MLStripper] ( identifier[preserve_urls] = identifier[preserve_urls] )
identifier[s] . identifier[feed] ( identifier[value] )
identifier[s] .... | def convert_html_to_text(value, preserve_urls=False):
"""
>>> convert_html_to_text(
... '''
... <html><body>
... Look & click
... <a href="https://example.com">here</a>
... </body></html>''', preserve_urls=True)
'Look & click here (https://example.com)'
... |
def get_config_groups(self, groups_conf, groups_pillar_name):
'''
get info from groups in config, and from the named pillar
todo: add specification for the minion to use to recover pillar
'''
# Get groups
# Default to returning something that'll never match
ret_g... | def function[get_config_groups, parameter[self, groups_conf, groups_pillar_name]]:
constant[
get info from groups in config, and from the named pillar
todo: add specification for the minion to use to recover pillar
]
variable[ret_groups] assign[=] dictionary[[<ast.Constant objec... | keyword[def] identifier[get_config_groups] ( identifier[self] , identifier[groups_conf] , identifier[groups_pillar_name] ):
literal[string]
identifier[ret_groups] ={
literal[string] :{
literal[string] : identifier[set] (),
literal[string] : identifier[se... | def get_config_groups(self, groups_conf, groups_pillar_name):
"""
get info from groups in config, and from the named pillar
todo: add specification for the minion to use to recover pillar
"""
# Get groups
# Default to returning something that'll never match
ret_groups = {'defaul... |
def readFile(cls, filepath):
"""Try different encoding to open a file in readonly mode"""
for mode in ("utf-8", 'gbk', 'cp1252', 'windows-1252', 'latin-1'):
try:
with open(filepath, mode='r', encoding=mode) as f:
content = f.read()
cit.... | def function[readFile, parameter[cls, filepath]]:
constant[Try different encoding to open a file in readonly mode]
for taget[name[mode]] in starred[tuple[[<ast.Constant object at 0x7da20c6c4a60>, <ast.Constant object at 0x7da20c6c79d0>, <ast.Constant object at 0x7da20c6c42e0>, <ast.Constant object at 0x... | keyword[def] identifier[readFile] ( identifier[cls] , identifier[filepath] ):
literal[string]
keyword[for] identifier[mode] keyword[in] ( literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ):
keyword[try] :
keyword[with] identifi... | def readFile(cls, filepath):
"""Try different encoding to open a file in readonly mode"""
for mode in ('utf-8', 'gbk', 'cp1252', 'windows-1252', 'latin-1'):
try:
with open(filepath, mode='r', encoding=mode) as f:
content = f.read()
cit.info('以 {} 格式打开文件'.forma... |
def check_permission(permission, brain_or_object):
"""Check whether the security context allows the given permission on
the given brain or object.
N.B.: This includes also acquired permissions
:param permission: Permission name
:brain_or_object: Catalog brain or object
:returns: True if the... | def function[check_permission, parameter[permission, brain_or_object]]:
constant[Check whether the security context allows the given permission on
the given brain or object.
N.B.: This includes also acquired permissions
:param permission: Permission name
:brain_or_object: Catalog brain or o... | keyword[def] identifier[check_permission] ( identifier[permission] , identifier[brain_or_object] ):
literal[string]
identifier[sm] = identifier[get_security_manager] ()
identifier[obj] = identifier[api] . identifier[get_object] ( identifier[brain_or_object] )
keyword[return] identifier[sm] . ide... | def check_permission(permission, brain_or_object):
"""Check whether the security context allows the given permission on
the given brain or object.
N.B.: This includes also acquired permissions
:param permission: Permission name
:brain_or_object: Catalog brain or object
:returns: True if the... |
def p_expr_trig(p):
""" bexpr : math_fn bexpr %prec UMINUS
"""
p[0] = make_builtin(p.lineno(1), p[1],
make_typecast(TYPE.float_, p[2], p.lineno(1)),
{'SIN': math.sin,
'COS': math.cos,
'TAN': math.tan,
... | def function[p_expr_trig, parameter[p]]:
constant[ bexpr : math_fn bexpr %prec UMINUS
]
call[name[p]][constant[0]] assign[=] call[name[make_builtin], parameter[call[name[p].lineno, parameter[constant[1]]], call[name[p]][constant[1]], call[name[make_typecast], parameter[name[TYPE].float_, call[name[p... | keyword[def] identifier[p_expr_trig] ( identifier[p] ):
literal[string]
identifier[p] [ literal[int] ]= identifier[make_builtin] ( identifier[p] . identifier[lineno] ( literal[int] ), identifier[p] [ literal[int] ],
identifier[make_typecast] ( identifier[TYPE] . identifier[float_] , identifier[p] [ li... | def p_expr_trig(p):
""" bexpr : math_fn bexpr %prec UMINUS
""" # LN(x)
p[0] = make_builtin(p.lineno(1), p[1], make_typecast(TYPE.float_, p[2], p.lineno(1)), {'SIN': math.sin, 'COS': math.cos, 'TAN': math.tan, 'ASN': math.asin, 'ACS': math.acos, 'ATN': math.atan, 'LN': lambda y: math.log(y, math.exp(1)), 'E... |
def _parse_session_run_index(self, event):
"""Parses the session_run_index value from the event proto.
Args:
event: The event with metadata that contains the session_run_index.
Returns:
The int session_run_index value. Or
constants.SENTINEL_FOR_UNDETERMINED_STEP if it could not be determ... | def function[_parse_session_run_index, parameter[self, event]]:
constant[Parses the session_run_index value from the event proto.
Args:
event: The event with metadata that contains the session_run_index.
Returns:
The int session_run_index value. Or
constants.SENTINEL_FOR_UNDETERMINED... | keyword[def] identifier[_parse_session_run_index] ( identifier[self] , identifier[event] ):
literal[string]
identifier[metadata_string] = identifier[event] . identifier[log_message] . identifier[message]
keyword[try] :
identifier[metadata] = identifier[json] . identifier[loads] ( identifier[me... | def _parse_session_run_index(self, event):
"""Parses the session_run_index value from the event proto.
Args:
event: The event with metadata that contains the session_run_index.
Returns:
The int session_run_index value. Or
constants.SENTINEL_FOR_UNDETERMINED_STEP if it could not be determ... |
def _save_yaml_file(self, file, val):
"""
Save data to yaml file
:param file: Writable object or path to file
:type file: FileIO | str | unicode
:param val: Value or struct to save
:type val: None | int | float | str | unicode | list | dict
:raises IOError: Faile... | def function[_save_yaml_file, parameter[self, file, val]]:
constant[
Save data to yaml file
:param file: Writable object or path to file
:type file: FileIO | str | unicode
:param val: Value or struct to save
:type val: None | int | float | str | unicode | list | dict
... | keyword[def] identifier[_save_yaml_file] ( identifier[self] , identifier[file] , identifier[val] ):
literal[string]
keyword[try] :
identifier[save_yaml_file] ( identifier[file] , identifier[val] )
keyword[except] :
identifier[self] . identifier[exception] ( litera... | def _save_yaml_file(self, file, val):
"""
Save data to yaml file
:param file: Writable object or path to file
:type file: FileIO | str | unicode
:param val: Value or struct to save
:type val: None | int | float | str | unicode | list | dict
:raises IOError: Failed to... |
def safe_add(a, b):
"""safe version of add"""
if isinstance(a, str) and isinstance(b, str) and len(a) + len(b) > MAX_STR_LEN:
raise RuntimeError("String length exceeded, max string length is {}".format(MAX_STR_LEN))
return a + b | def function[safe_add, parameter[a, b]]:
constant[safe version of add]
if <ast.BoolOp object at 0x7da1b12c6d10> begin[:]
<ast.Raise object at 0x7da1b12c44c0>
return[binary_operation[name[a] + name[b]]] | keyword[def] identifier[safe_add] ( identifier[a] , identifier[b] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[a] , identifier[str] ) keyword[and] identifier[isinstance] ( identifier[b] , identifier[str] ) keyword[and] identifier[len] ( identifier[a] )+ identifier[len] ( identifier... | def safe_add(a, b):
"""safe version of add"""
if isinstance(a, str) and isinstance(b, str) and (len(a) + len(b) > MAX_STR_LEN):
raise RuntimeError('String length exceeded, max string length is {}'.format(MAX_STR_LEN)) # depends on [control=['if'], data=[]]
return a + b |
def deprecated(message=None):
"""A decorator for deprecated functions"""
def _decorator(func, message=message):
if message is None:
message = '%s is deprecated' % func.__name__
def newfunc(*args, **kwds):
warnings.warn(message, DeprecationWarning, stacklevel=2)
... | def function[deprecated, parameter[message]]:
constant[A decorator for deprecated functions]
def function[_decorator, parameter[func, message]]:
if compare[name[message] is constant[None]] begin[:]
variable[message] assign[=] binary_operation[constant[%s is deprec... | keyword[def] identifier[deprecated] ( identifier[message] = keyword[None] ):
literal[string]
keyword[def] identifier[_decorator] ( identifier[func] , identifier[message] = identifier[message] ):
keyword[if] identifier[message] keyword[is] keyword[None] :
identifier[message] = lite... | def deprecated(message=None):
"""A decorator for deprecated functions"""
def _decorator(func, message=message):
if message is None:
message = '%s is deprecated' % func.__name__ # depends on [control=['if'], data=['message']]
def newfunc(*args, **kwds):
warnings.warn(me... |
def sample_u(self, q):
r"""Extract a sample from random variates uniform on :math:`[0, 1]`.
For a univariate distribution, this is simply evaluating the inverse
CDF. To facilitate efficient sampling, this function returns a *vector*
of PPF values, one value for each variable. Ba... | def function[sample_u, parameter[self, q]]:
constant[Extract a sample from random variates uniform on :math:`[0, 1]`.
For a univariate distribution, this is simply evaluating the inverse
CDF. To facilitate efficient sampling, this function returns a *vector*
of PPF values, one v... | keyword[def] identifier[sample_u] ( identifier[self] , identifier[q] ):
literal[string]
identifier[q] = identifier[scipy] . identifier[atleast_1d] ( identifier[q] )
keyword[if] identifier[len] ( identifier[q] )!= identifier[len] ( identifier[self] . identifier[sigma] ):
keywo... | def sample_u(self, q):
"""Extract a sample from random variates uniform on :math:`[0, 1]`.
For a univariate distribution, this is simply evaluating the inverse
CDF. To facilitate efficient sampling, this function returns a *vector*
of PPF values, one value for each variable. Basical... |
def process_exception(self, request, e):
"""
Logs exception error message and sends email to ADMINS if hostname is not testserver and DEBUG=False.
:param request: HttpRequest
:param e: Exception
"""
from jutil.email import send_email
assert isinstance(request, Ht... | def function[process_exception, parameter[self, request, e]]:
constant[
Logs exception error message and sends email to ADMINS if hostname is not testserver and DEBUG=False.
:param request: HttpRequest
:param e: Exception
]
from relative_module[jutil.email] import module[send... | keyword[def] identifier[process_exception] ( identifier[self] , identifier[request] , identifier[e] ):
literal[string]
keyword[from] identifier[jutil] . identifier[email] keyword[import] identifier[send_email]
keyword[assert] identifier[isinstance] ( identifier[request] , identifier[... | def process_exception(self, request, e):
"""
Logs exception error message and sends email to ADMINS if hostname is not testserver and DEBUG=False.
:param request: HttpRequest
:param e: Exception
"""
from jutil.email import send_email
assert isinstance(request, HttpRequest)
... |
def get_offset(self):
"""
Return offset from tus server.
This is different from the instance attribute 'offset' because this makes an
http request to the tus server to retrieve the offset.
"""
resp = requests.head(self.url, headers=self.headers)
offset = resp.hea... | def function[get_offset, parameter[self]]:
constant[
Return offset from tus server.
This is different from the instance attribute 'offset' because this makes an
http request to the tus server to retrieve the offset.
]
variable[resp] assign[=] call[name[requests].head, pa... | keyword[def] identifier[get_offset] ( identifier[self] ):
literal[string]
identifier[resp] = identifier[requests] . identifier[head] ( identifier[self] . identifier[url] , identifier[headers] = identifier[self] . identifier[headers] )
identifier[offset] = identifier[resp] . identifier[head... | def get_offset(self):
"""
Return offset from tus server.
This is different from the instance attribute 'offset' because this makes an
http request to the tus server to retrieve the offset.
"""
resp = requests.head(self.url, headers=self.headers)
offset = resp.headers.get('up... |
def _flush_ignored_control(self):
"""flush ignored control replies"""
while self._ignored_control_replies > 0:
self.session.recv(self._control_socket)
self._ignored_control_replies -= 1 | def function[_flush_ignored_control, parameter[self]]:
constant[flush ignored control replies]
while compare[name[self]._ignored_control_replies greater[>] constant[0]] begin[:]
call[name[self].session.recv, parameter[name[self]._control_socket]]
<ast.AugAssign object at 0x7da1b2... | keyword[def] identifier[_flush_ignored_control] ( identifier[self] ):
literal[string]
keyword[while] identifier[self] . identifier[_ignored_control_replies] > literal[int] :
identifier[self] . identifier[session] . identifier[recv] ( identifier[self] . identifier[_control_socket] )
... | def _flush_ignored_control(self):
"""flush ignored control replies"""
while self._ignored_control_replies > 0:
self.session.recv(self._control_socket)
self._ignored_control_replies -= 1 # depends on [control=['while'], data=[]] |
def item_options(self, **kwargs):
""" Handle collection OPTIONS request.
Singular route requests are handled a bit differently because
singular views may handle POST requests despite being registered
as item routes.
"""
actions = self._item_actions.copy()
if self... | def function[item_options, parameter[self]]:
constant[ Handle collection OPTIONS request.
Singular route requests are handled a bit differently because
singular views may handle POST requests despite being registered
as item routes.
]
variable[actions] assign[=] call[nam... | keyword[def] identifier[item_options] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[actions] = identifier[self] . identifier[_item_actions] . identifier[copy] ()
keyword[if] identifier[self] . identifier[_resource] . identifier[is_singular] :
identif... | def item_options(self, **kwargs):
""" Handle collection OPTIONS request.
Singular route requests are handled a bit differently because
singular views may handle POST requests despite being registered
as item routes.
"""
actions = self._item_actions.copy()
if self._resource.i... |
def git_status_all_repos(cat, hard=True, origin=False, clean=True):
"""Perform a 'git status' in each data repository.
"""
log = cat.log
log.debug("gitter.git_status_all_repos()")
all_repos = cat.PATHS.get_all_repo_folders()
for repo_name in all_repos:
log.info("Repo in: '{}'".format(re... | def function[git_status_all_repos, parameter[cat, hard, origin, clean]]:
constant[Perform a 'git status' in each data repository.
]
variable[log] assign[=] name[cat].log
call[name[log].debug, parameter[constant[gitter.git_status_all_repos()]]]
variable[all_repos] assign[=] call[name[... | keyword[def] identifier[git_status_all_repos] ( identifier[cat] , identifier[hard] = keyword[True] , identifier[origin] = keyword[False] , identifier[clean] = keyword[True] ):
literal[string]
identifier[log] = identifier[cat] . identifier[log]
identifier[log] . identifier[debug] ( literal[string] )
... | def git_status_all_repos(cat, hard=True, origin=False, clean=True):
"""Perform a 'git status' in each data repository.
"""
log = cat.log
log.debug('gitter.git_status_all_repos()')
all_repos = cat.PATHS.get_all_repo_folders()
for repo_name in all_repos:
log.info("Repo in: '{}'".format(rep... |
def get(self, section, option):
"""Gets an option value for a given section.
Args:
section (str): section name
option (str): option name
Returns:
:class:`Option`: Option object holding key/value pair
"""
if not self.has_section(section):
... | def function[get, parameter[self, section, option]]:
constant[Gets an option value for a given section.
Args:
section (str): section name
option (str): option name
Returns:
:class:`Option`: Option object holding key/value pair
]
if <ast.Unary... | keyword[def] identifier[get] ( identifier[self] , identifier[section] , identifier[option] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[has_section] ( identifier[section] ):
keyword[raise] identifier[NoSectionError] ( identifier[section] ) keyword[from] ... | def get(self, section, option):
"""Gets an option value for a given section.
Args:
section (str): section name
option (str): option name
Returns:
:class:`Option`: Option object holding key/value pair
"""
if not self.has_section(section):
rais... |
def get_default_calendar(self):
""" Returns the default calendar for the current user
:rtype: Calendar
"""
url = self.build_url(self._endpoints.get('default_calendar'))
response = self.con.get(url)
if not response:
return None
data = response.json(... | def function[get_default_calendar, parameter[self]]:
constant[ Returns the default calendar for the current user
:rtype: Calendar
]
variable[url] assign[=] call[name[self].build_url, parameter[call[name[self]._endpoints.get, parameter[constant[default_calendar]]]]]
variable[resp... | keyword[def] identifier[get_default_calendar] ( identifier[self] ):
literal[string]
identifier[url] = identifier[self] . identifier[build_url] ( identifier[self] . identifier[_endpoints] . identifier[get] ( literal[string] ))
identifier[response] = identifier[self] . identifier[con] . id... | def get_default_calendar(self):
""" Returns the default calendar for the current user
:rtype: Calendar
"""
url = self.build_url(self._endpoints.get('default_calendar'))
response = self.con.get(url)
if not response:
return None # depends on [control=['if'], data=[]]
data = r... |
def make_csv_tables(self):
"""
Builds the report as a list of csv tables with titles.
"""
logger.info('Generate csv report tables')
report_parts = []
for sr in self.subreports:
for data_item in sr.report_data:
report_parts.append(TextPart(fmt='... | def function[make_csv_tables, parameter[self]]:
constant[
Builds the report as a list of csv tables with titles.
]
call[name[logger].info, parameter[constant[Generate csv report tables]]]
variable[report_parts] assign[=] list[[]]
for taget[name[sr]] in starred[name[self].... | keyword[def] identifier[make_csv_tables] ( identifier[self] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] )
identifier[report_parts] =[]
keyword[for] identifier[sr] keyword[in] identifier[self] . identifier[subreports] :
keyword[for] i... | def make_csv_tables(self):
"""
Builds the report as a list of csv tables with titles.
"""
logger.info('Generate csv report tables')
report_parts = []
for sr in self.subreports:
for data_item in sr.report_data:
report_parts.append(TextPart(fmt='csv', text=data_item.csv... |
def write(self, stream, message):
'''write will write a message to a stream,
first checking the encoding
'''
if isinstance(message, bytes):
message = message.decode('utf-8')
stream.write(message) | def function[write, parameter[self, stream, message]]:
constant[write will write a message to a stream,
first checking the encoding
]
if call[name[isinstance], parameter[name[message], name[bytes]]] begin[:]
variable[message] assign[=] call[name[message].decode, parameter... | keyword[def] identifier[write] ( identifier[self] , identifier[stream] , identifier[message] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[message] , identifier[bytes] ):
identifier[message] = identifier[message] . identifier[decode] ( literal[string] )
i... | def write(self, stream, message):
"""write will write a message to a stream,
first checking the encoding
"""
if isinstance(message, bytes):
message = message.decode('utf-8') # depends on [control=['if'], data=[]]
stream.write(message) |
def clone(estimator, safe=True):
"""Constructs a new estimator with the same parameters.
Clone does a deep copy of the model in an estimator
without actually copying attached data. It yields a new estimator
with the same parameters that has not been fit on any data.
Parameters
----------
est... | def function[clone, parameter[estimator, safe]]:
constant[Constructs a new estimator with the same parameters.
Clone does a deep copy of the model in an estimator
without actually copying attached data. It yields a new estimator
with the same parameters that has not been fit on any data.
Paramet... | keyword[def] identifier[clone] ( identifier[estimator] , identifier[safe] = keyword[True] ):
literal[string]
identifier[estimator_type] = identifier[type] ( identifier[estimator] )
keyword[if] identifier[estimator_type] keyword[in] ( identifier[list] , identifier[tuple] , identifier[set] , iden... | def clone(estimator, safe=True):
"""Constructs a new estimator with the same parameters.
Clone does a deep copy of the model in an estimator
without actually copying attached data. It yields a new estimator
with the same parameters that has not been fit on any data.
Parameters
----------
est... |
def add_cssfile(self, src: str) -> None:
"""Add CSS file to load at this document's header."""
self.head.appendChild(Link(rel='stylesheet', href=src)) | def function[add_cssfile, parameter[self, src]]:
constant[Add CSS file to load at this document's header.]
call[name[self].head.appendChild, parameter[call[name[Link], parameter[]]]] | keyword[def] identifier[add_cssfile] ( identifier[self] , identifier[src] : identifier[str] )-> keyword[None] :
literal[string]
identifier[self] . identifier[head] . identifier[appendChild] ( identifier[Link] ( identifier[rel] = literal[string] , identifier[href] = identifier[src] )) | def add_cssfile(self, src: str) -> None:
"""Add CSS file to load at this document's header."""
self.head.appendChild(Link(rel='stylesheet', href=src)) |
def today(self, symbol):
"""
GET /today/:symbol
curl "https://api.bitfinex.com/v1/today/btcusd"
{"low":"550.09","high":"572.2398","volume":"7305.33119836"}
"""
data = self._get(self.url_for(PATH_TODAY, (symbol)))
# convert all values to floats
return se... | def function[today, parameter[self, symbol]]:
constant[
GET /today/:symbol
curl "https://api.bitfinex.com/v1/today/btcusd"
{"low":"550.09","high":"572.2398","volume":"7305.33119836"}
]
variable[data] assign[=] call[name[self]._get, parameter[call[name[self].url_for, para... | keyword[def] identifier[today] ( identifier[self] , identifier[symbol] ):
literal[string]
identifier[data] = identifier[self] . identifier[_get] ( identifier[self] . identifier[url_for] ( identifier[PATH_TODAY] ,( identifier[symbol] )))
keyword[return] identifier[self] . identi... | def today(self, symbol):
"""
GET /today/:symbol
curl "https://api.bitfinex.com/v1/today/btcusd"
{"low":"550.09","high":"572.2398","volume":"7305.33119836"}
"""
data = self._get(self.url_for(PATH_TODAY, symbol))
# convert all values to floats
return self._convert_to_float... |
def listTheExtras(self, deleteAlso):
""" Use ConfigObj's get_extra_values() call to find any extra/unknown
parameters we may have loaded. Return a string similar to findTheLost.
If deleteAlso is True, this will also delete any extra/unknown items.
"""
# get list of extras
... | def function[listTheExtras, parameter[self, deleteAlso]]:
constant[ Use ConfigObj's get_extra_values() call to find any extra/unknown
parameters we may have loaded. Return a string similar to findTheLost.
If deleteAlso is True, this will also delete any extra/unknown items.
]
va... | keyword[def] identifier[listTheExtras] ( identifier[self] , identifier[deleteAlso] ):
literal[string]
identifier[extras] = identifier[configobj] . identifier[get_extra_values] ( identifier[self] )
identifier[expanded] ... | def listTheExtras(self, deleteAlso):
""" Use ConfigObj's get_extra_values() call to find any extra/unknown
parameters we may have loaded. Return a string similar to findTheLost.
If deleteAlso is True, this will also delete any extra/unknown items.
"""
# get list of extras
extras = c... |
def get_backend(config):
""" Returns a backend instance based on the Daemon config file. """
backend_string = get_conf(config, 'Dagobahd.backend', None)
if backend_string is None:
from ..backend.base import BaseBackend
return BaseBackend()
elif backend_string.lower() == 'mongo':
... | def function[get_backend, parameter[config]]:
constant[ Returns a backend instance based on the Daemon config file. ]
variable[backend_string] assign[=] call[name[get_conf], parameter[name[config], constant[Dagobahd.backend], constant[None]]]
if compare[name[backend_string] is constant[None]] be... | keyword[def] identifier[get_backend] ( identifier[config] ):
literal[string]
identifier[backend_string] = identifier[get_conf] ( identifier[config] , literal[string] , keyword[None] )
keyword[if] identifier[backend_string] keyword[is] keyword[None] :
keyword[from] .. identifier[backend] ... | def get_backend(config):
""" Returns a backend instance based on the Daemon config file. """
backend_string = get_conf(config, 'Dagobahd.backend', None)
if backend_string is None:
from ..backend.base import BaseBackend
return BaseBackend() # depends on [control=['if'], data=[]]
elif bac... |
def isScreenOn(self):
"""
Checks if the screen is ON.
@return: True if the device screen is ON
"""
self.__checkTransport()
screenOnRE = re.compile('mScreenOnFully=(true|false)')
m = screenOnRE.search(self.shell('dumpsys window policy'))
if m:
... | def function[isScreenOn, parameter[self]]:
constant[
Checks if the screen is ON.
@return: True if the device screen is ON
]
call[name[self].__checkTransport, parameter[]]
variable[screenOnRE] assign[=] call[name[re].compile, parameter[constant[mScreenOnFully=(true|false)... | keyword[def] identifier[isScreenOn] ( identifier[self] ):
literal[string]
identifier[self] . identifier[__checkTransport] ()
identifier[screenOnRE] = identifier[re] . identifier[compile] ( literal[string] )
identifier[m] = identifier[screenOnRE] . identifier[search] ( identifier[... | def isScreenOn(self):
"""
Checks if the screen is ON.
@return: True if the device screen is ON
"""
self.__checkTransport()
screenOnRE = re.compile('mScreenOnFully=(true|false)')
m = screenOnRE.search(self.shell('dumpsys window policy'))
if m:
return m.group(1) == 'tr... |
def write_roc(roc_structure, inputfilename, options, fw_type = None):
"""
writes ROC output
:param roc_structure: a.k.a auc_structure, generated in /common_tools/classification/make_auc_structure()
:param inputfilename: name of the file specified on the command line that contains the ensemble. This will... | def function[write_roc, parameter[roc_structure, inputfilename, options, fw_type]]:
constant[
writes ROC output
:param roc_structure: a.k.a auc_structure, generated in /common_tools/classification/make_auc_structure()
:param inputfilename: name of the file specified on the command line that contains... | keyword[def] identifier[write_roc] ( identifier[roc_structure] , identifier[inputfilename] , identifier[options] , identifier[fw_type] = keyword[None] ):
literal[string]
identifier[rocdir] = identifier[os] . identifier[path] . identifier[join] ( identifier[os] . identifier[getcwd] (), literal[string] ... | def write_roc(roc_structure, inputfilename, options, fw_type=None):
"""
writes ROC output
:param roc_structure: a.k.a auc_structure, generated in /common_tools/classification/make_auc_structure()
:param inputfilename: name of the file specified on the command line that contains the ensemble. This will b... |
def init(ctx, client, directory, name, force, use_external_storage):
"""Initialize a project."""
if not client.use_external_storage:
use_external_storage = False
ctx.obj = client = attr.evolve(
client,
path=directory,
use_external_storage=use_external_storage,
)
msg... | def function[init, parameter[ctx, client, directory, name, force, use_external_storage]]:
constant[Initialize a project.]
if <ast.UnaryOp object at 0x7da1b02e4c70> begin[:]
variable[use_external_storage] assign[=] constant[False]
name[ctx].obj assign[=] call[name[attr].evolve, pa... | keyword[def] identifier[init] ( identifier[ctx] , identifier[client] , identifier[directory] , identifier[name] , identifier[force] , identifier[use_external_storage] ):
literal[string]
keyword[if] keyword[not] identifier[client] . identifier[use_external_storage] :
identifier[use_external_stora... | def init(ctx, client, directory, name, force, use_external_storage):
"""Initialize a project."""
if not client.use_external_storage:
use_external_storage = False # depends on [control=['if'], data=[]]
ctx.obj = client = attr.evolve(client, path=directory, use_external_storage=use_external_storage)
... |
def _get_package_name(prefix=settings.TEMP_DIR, book_id=None):
"""
Return package path. Use uuid to generate package's directory name.
Args:
book_id (str, default None): UUID of the book.
prefix (str, default settings.TEMP_DIR): Where the package will be
stored. Default :attr... | def function[_get_package_name, parameter[prefix, book_id]]:
constant[
Return package path. Use uuid to generate package's directory name.
Args:
book_id (str, default None): UUID of the book.
prefix (str, default settings.TEMP_DIR): Where the package will be
stored. Defau... | keyword[def] identifier[_get_package_name] ( identifier[prefix] = identifier[settings] . identifier[TEMP_DIR] , identifier[book_id] = keyword[None] ):
literal[string]
keyword[if] identifier[book_id] keyword[is] keyword[None] :
identifier[book_id] = identifier[str] ( identifier[uuid] . identifie... | def _get_package_name(prefix=settings.TEMP_DIR, book_id=None):
"""
Return package path. Use uuid to generate package's directory name.
Args:
book_id (str, default None): UUID of the book.
prefix (str, default settings.TEMP_DIR): Where the package will be
stored. Default :attr... |
def Target_setDiscoverTargets(self, discover):
"""
Function path: Target.setDiscoverTargets
Domain: Target
Method name: setDiscoverTargets
Parameters:
Required arguments:
'discover' (type: boolean) -> Whether to discover available targets.
No return value.
Description: Controls whether... | def function[Target_setDiscoverTargets, parameter[self, discover]]:
constant[
Function path: Target.setDiscoverTargets
Domain: Target
Method name: setDiscoverTargets
Parameters:
Required arguments:
'discover' (type: boolean) -> Whether to discover available targets.
No return value.
... | keyword[def] identifier[Target_setDiscoverTargets] ( identifier[self] , identifier[discover] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[discover] ,( identifier[bool] ,)
), literal[string] % identifier[type] (
identifier[discover] )
identifier[subdom_funcs] = identifier[self... | def Target_setDiscoverTargets(self, discover):
"""
Function path: Target.setDiscoverTargets
Domain: Target
Method name: setDiscoverTargets
Parameters:
Required arguments:
'discover' (type: boolean) -> Whether to discover available targets.
No return value.
Description: Controls wheth... |
def run_game_of_life(years, width, height, time_delay, silent="N"):
"""
run a single game of life for 'years' and log start and
end living cells to aikif
"""
lfe = mod_grid.GameOfLife(width, height, ['.', 'x'], 1)
set_random_starting_grid(lfe)
lg.record_source(lfe, 'game_of_life_console.py'... | def function[run_game_of_life, parameter[years, width, height, time_delay, silent]]:
constant[
run a single game of life for 'years' and log start and
end living cells to aikif
]
variable[lfe] assign[=] call[name[mod_grid].GameOfLife, parameter[name[width], name[height], list[[<ast.Constant... | keyword[def] identifier[run_game_of_life] ( identifier[years] , identifier[width] , identifier[height] , identifier[time_delay] , identifier[silent] = literal[string] ):
literal[string]
identifier[lfe] = identifier[mod_grid] . identifier[GameOfLife] ( identifier[width] , identifier[height] ,[ literal[strin... | def run_game_of_life(years, width, height, time_delay, silent='N'):
"""
run a single game of life for 'years' and log start and
end living cells to aikif
"""
lfe = mod_grid.GameOfLife(width, height, ['.', 'x'], 1)
set_random_starting_grid(lfe)
lg.record_source(lfe, 'game_of_life_console.py'... |
def set(self, key, value):
"""Set a value in the `Bison` configuration.
Args:
key (str): The configuration key to set a new value for.
value: The value to set.
"""
# the configuration changes, so we invalidate the cached config
self._full_config = None
... | def function[set, parameter[self, key, value]]:
constant[Set a value in the `Bison` configuration.
Args:
key (str): The configuration key to set a new value for.
value: The value to set.
]
name[self]._full_config assign[=] constant[None]
call[name[self]._... | keyword[def] identifier[set] ( identifier[self] , identifier[key] , identifier[value] ):
literal[string]
identifier[self] . identifier[_full_config] = keyword[None]
identifier[self] . identifier[_override] [ identifier[key] ]= identifier[value] | def set(self, key, value):
"""Set a value in the `Bison` configuration.
Args:
key (str): The configuration key to set a new value for.
value: The value to set.
"""
# the configuration changes, so we invalidate the cached config
self._full_config = None
self._over... |
def cp(hdfs_src, hdfs_dst):
"""Copy a file
:param hdfs_src: Source (str)
:param hdfs_dst: Destination (str)
:raises: IOError: If unsuccessful
"""
cmd = "hadoop fs -cp %s %s" % (hdfs_src, hdfs_dst)
rcode, stdout, stderr = _checked_hadoop_fs_command(cmd) | def function[cp, parameter[hdfs_src, hdfs_dst]]:
constant[Copy a file
:param hdfs_src: Source (str)
:param hdfs_dst: Destination (str)
:raises: IOError: If unsuccessful
]
variable[cmd] assign[=] binary_operation[constant[hadoop fs -cp %s %s] <ast.Mod object at 0x7da2590d6920> tuple[[<as... | keyword[def] identifier[cp] ( identifier[hdfs_src] , identifier[hdfs_dst] ):
literal[string]
identifier[cmd] = literal[string] %( identifier[hdfs_src] , identifier[hdfs_dst] )
identifier[rcode] , identifier[stdout] , identifier[stderr] = identifier[_checked_hadoop_fs_command] ( identifier[cmd] ) | def cp(hdfs_src, hdfs_dst):
"""Copy a file
:param hdfs_src: Source (str)
:param hdfs_dst: Destination (str)
:raises: IOError: If unsuccessful
"""
cmd = 'hadoop fs -cp %s %s' % (hdfs_src, hdfs_dst)
(rcode, stdout, stderr) = _checked_hadoop_fs_command(cmd) |
def update_fw_local_cache(self, net, direc, start):
"""Update the fw dict with Net ID and service IP. """
fw_dict = self.get_fw_dict()
if direc == 'in':
fw_dict.update({'in_network_id': net, 'in_service_ip': start})
else:
fw_dict.update({'out_network_id': net, 'ou... | def function[update_fw_local_cache, parameter[self, net, direc, start]]:
constant[Update the fw dict with Net ID and service IP. ]
variable[fw_dict] assign[=] call[name[self].get_fw_dict, parameter[]]
if compare[name[direc] equal[==] constant[in]] begin[:]
call[name[fw_dict].upda... | keyword[def] identifier[update_fw_local_cache] ( identifier[self] , identifier[net] , identifier[direc] , identifier[start] ):
literal[string]
identifier[fw_dict] = identifier[self] . identifier[get_fw_dict] ()
keyword[if] identifier[direc] == literal[string] :
identifier[fw_... | def update_fw_local_cache(self, net, direc, start):
"""Update the fw dict with Net ID and service IP. """
fw_dict = self.get_fw_dict()
if direc == 'in':
fw_dict.update({'in_network_id': net, 'in_service_ip': start}) # depends on [control=['if'], data=[]]
else:
fw_dict.update({'out_netwo... |
def _get_splunk_search_props(search):
'''
Get splunk search properties from an object
'''
props = search.content
props["app"] = search.access.app
props["sharing"] = search.access.sharing
return props | def function[_get_splunk_search_props, parameter[search]]:
constant[
Get splunk search properties from an object
]
variable[props] assign[=] name[search].content
call[name[props]][constant[app]] assign[=] name[search].access.app
call[name[props]][constant[sharing]] assign[=] name... | keyword[def] identifier[_get_splunk_search_props] ( identifier[search] ):
literal[string]
identifier[props] = identifier[search] . identifier[content]
identifier[props] [ literal[string] ]= identifier[search] . identifier[access] . identifier[app]
identifier[props] [ literal[string] ]= identifi... | def _get_splunk_search_props(search):
"""
Get splunk search properties from an object
"""
props = search.content
props['app'] = search.access.app
props['sharing'] = search.access.sharing
return props |
def parse_args(self, *args, **kwargs):
"""Parse the arguments as usual, then add default processing."""
if _debug: ConfigArgumentParser._debug("parse_args")
# pass along to the parent class
result_args = ArgumentParser.parse_args(self, *args, **kwargs)
# read in the configurati... | def function[parse_args, parameter[self]]:
constant[Parse the arguments as usual, then add default processing.]
if name[_debug] begin[:]
call[name[ConfigArgumentParser]._debug, parameter[constant[parse_args]]]
variable[result_args] assign[=] call[name[ArgumentParser].parse_args, ... | keyword[def] identifier[parse_args] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[_debug] : identifier[ConfigArgumentParser] . identifier[_debug] ( literal[string] )
identifier[result_args] = identifier[ArgumentParser] . ... | def parse_args(self, *args, **kwargs):
"""Parse the arguments as usual, then add default processing."""
if _debug:
ConfigArgumentParser._debug('parse_args') # depends on [control=['if'], data=[]]
# pass along to the parent class
result_args = ArgumentParser.parse_args(self, *args, **kwargs)
... |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'environment_id') and self.environment_id is not None:
_dict['environment_id'] = self.environment_id
if hasattr(self, 'session_token') and self.session_token is not None:
... | def function[_to_dict, parameter[self]]:
constant[Return a json dictionary representing this model.]
variable[_dict] assign[=] dictionary[[], []]
if <ast.BoolOp object at 0x7da18f09d3c0> begin[:]
call[name[_dict]][constant[environment_id]] assign[=] name[self].environment_id
... | keyword[def] identifier[_to_dict] ( identifier[self] ):
literal[string]
identifier[_dict] ={}
keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ) keyword[and] identifier[self] . identifier[environment_id] keyword[is] keyword[not] keyword[None] :
identif... | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'environment_id') and self.environment_id is not None:
_dict['environment_id'] = self.environment_id # depends on [control=['if'], data=[]]
if hasattr(self, 'session_token') and self.session_... |
def get_fqhostname():
'''
Returns the fully qualified hostname
'''
# try getaddrinfo()
fqdn = None
try:
addrinfo = socket.getaddrinfo(
socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM,
socket.SOL_TCP, socket.AI_CANONNAME
)
for info in ... | def function[get_fqhostname, parameter[]]:
constant[
Returns the fully qualified hostname
]
variable[fqdn] assign[=] constant[None]
<ast.Try object at 0x7da1b1f7b100>
if compare[name[fqdn] is constant[None]] begin[:]
variable[fqdn] assign[=] call[name[socket].getfqdn,... | keyword[def] identifier[get_fqhostname] ():
literal[string]
identifier[fqdn] = keyword[None]
keyword[try] :
identifier[addrinfo] = identifier[socket] . identifier[getaddrinfo] (
identifier[socket] . identifier[gethostname] (), literal[int] , identifier[socket] . identifier[AF_U... | def get_fqhostname():
"""
Returns the fully qualified hostname
"""
# try getaddrinfo()
fqdn = None
try:
addrinfo = socket.getaddrinfo(socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME)
for info in addrinfo:
# info struc... |
def derivative(self, x):
"""Return the derivative at ``x``.
The derivative of the right scalar operator multiplication
follows the chain rule:
``OperatorRightScalarMult(op, s).derivative(y) ==
OperatorLeftScalarMult(op.derivative(s * y), s)``
Parameters
... | def function[derivative, parameter[self, x]]:
constant[Return the derivative at ``x``.
The derivative of the right scalar operator multiplication
follows the chain rule:
``OperatorRightScalarMult(op, s).derivative(y) ==
OperatorLeftScalarMult(op.derivative(s * y), s)``
... | keyword[def] identifier[derivative] ( identifier[self] , identifier[x] ):
literal[string]
keyword[return] identifier[self] . identifier[scalar] * identifier[self] . identifier[operator] . identifier[derivative] ( identifier[self] . identifier[scalar] * identifier[x] ) | def derivative(self, x):
"""Return the derivative at ``x``.
The derivative of the right scalar operator multiplication
follows the chain rule:
``OperatorRightScalarMult(op, s).derivative(y) ==
OperatorLeftScalarMult(op.derivative(s * y), s)``
Parameters
---... |
def flush(self):
"""Delete all run-time data generated by this crawler."""
Queue.flush(self)
Event.delete(self)
Crawl.flush(self) | def function[flush, parameter[self]]:
constant[Delete all run-time data generated by this crawler.]
call[name[Queue].flush, parameter[name[self]]]
call[name[Event].delete, parameter[name[self]]]
call[name[Crawl].flush, parameter[name[self]]] | keyword[def] identifier[flush] ( identifier[self] ):
literal[string]
identifier[Queue] . identifier[flush] ( identifier[self] )
identifier[Event] . identifier[delete] ( identifier[self] )
identifier[Crawl] . identifier[flush] ( identifier[self] ) | def flush(self):
"""Delete all run-time data generated by this crawler."""
Queue.flush(self)
Event.delete(self)
Crawl.flush(self) |
def close(self):
"""Close the tough connection.
You are allowed to close a tough connection by default
and it will not complain if you close it more than once.
You can disallow closing connections by setting
the closeable parameter to something false. In this case,
clo... | def function[close, parameter[self]]:
constant[Close the tough connection.
You are allowed to close a tough connection by default
and it will not complain if you close it more than once.
You can disallow closing connections by setting
the closeable parameter to something false.... | keyword[def] identifier[close] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_closeable] :
identifier[self] . identifier[_close] ()
keyword[elif] identifier[self] . identifier[_transaction] :
identifier[self] . identifier[_reset... | def close(self):
"""Close the tough connection.
You are allowed to close a tough connection by default
and it will not complain if you close it more than once.
You can disallow closing connections by setting
the closeable parameter to something false. In this case,
closing... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.