code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def from_name(cls, name, path=THEMES):
"""
Search for the given theme on the filesystem and attempt to load it.
Directories will be checked in a pre-determined order. If the name is
provided as an absolute file path, it will be loaded directly.
"""
if os.path.isfile(nam... | def function[from_name, parameter[cls, name, path]]:
constant[
Search for the given theme on the filesystem and attempt to load it.
Directories will be checked in a pre-determined order. If the name is
provided as an absolute file path, it will be loaded directly.
]
if c... | keyword[def] identifier[from_name] ( identifier[cls] , identifier[name] , identifier[path] = identifier[THEMES] ):
literal[string]
keyword[if] identifier[os] . identifier[path] . identifier[isfile] ( identifier[name] ):
keyword[return] identifier[cls] . identifier[from_file] ( ident... | def from_name(cls, name, path=THEMES):
"""
Search for the given theme on the filesystem and attempt to load it.
Directories will be checked in a pre-determined order. If the name is
provided as an absolute file path, it will be loaded directly.
"""
if os.path.isfile(name):
... |
async def mutual_friends(self):
"""|coro|
Gets all mutual friends of this user.
.. note::
This only applies to non-bot accounts.
Raises
-------
Forbidden
Not allowed to get mutual friends of this user.
HTTPException
Getting ... | <ast.AsyncFunctionDef object at 0x7da1b1f249a0> | keyword[async] keyword[def] identifier[mutual_friends] ( identifier[self] ):
literal[string]
identifier[state] = identifier[self] . identifier[_state]
identifier[mutuals] = keyword[await] identifier[state] . identifier[http] . identifier[get_mutual_friends] ( identifier[self] . identifi... | async def mutual_friends(self):
"""|coro|
Gets all mutual friends of this user.
.. note::
This only applies to non-bot accounts.
Raises
-------
Forbidden
Not allowed to get mutual friends of this user.
HTTPException
Getting mutu... |
def convert_time(obj):
"""Returns a TIME column as a time object:
>>> time_or_None('15:06:17')
datetime.time(15, 6, 17)
Illegal values are returned as None:
>>> time_or_None('-25:06:17') is None
True
>>> time_or_None('random crap') is None
True
Note that MySQL always ... | def function[convert_time, parameter[obj]]:
constant[Returns a TIME column as a time object:
>>> time_or_None('15:06:17')
datetime.time(15, 6, 17)
Illegal values are returned as None:
>>> time_or_None('-25:06:17') is None
True
>>> time_or_None('random crap') is None
Tr... | keyword[def] identifier[convert_time] ( identifier[obj] ):
literal[string]
keyword[if] keyword[not] identifier[PY2] keyword[and] identifier[isinstance] ( identifier[obj] ,( identifier[bytes] , identifier[bytearray] )):
identifier[obj] = identifier[obj] . identifier[decode] ( literal[string] )
... | def convert_time(obj):
"""Returns a TIME column as a time object:
>>> time_or_None('15:06:17')
datetime.time(15, 6, 17)
Illegal values are returned as None:
>>> time_or_None('-25:06:17') is None
True
>>> time_or_None('random crap') is None
True
Note that MySQL always ... |
def _merge(options, name, bases, default=None):
"""Merges a named option collection."""
result = None
for base in bases:
if base is None:
continue
value = getattr(base, name, None)
if value is None:
continue
result = utils.cons(result, value)
va... | def function[_merge, parameter[options, name, bases, default]]:
constant[Merges a named option collection.]
variable[result] assign[=] constant[None]
for taget[name[base]] in starred[name[bases]] begin[:]
if compare[name[base] is constant[None]] begin[:]
continue
... | keyword[def] identifier[_merge] ( identifier[options] , identifier[name] , identifier[bases] , identifier[default] = keyword[None] ):
literal[string]
identifier[result] = keyword[None]
keyword[for] identifier[base] keyword[in] identifier[bases] :
keyword[if] identifier[base] keyword[is]... | def _merge(options, name, bases, default=None):
"""Merges a named option collection."""
result = None
for base in bases:
if base is None:
continue # depends on [control=['if'], data=[]]
value = getattr(base, name, None)
if value is None:
continue # depends o... |
def _add_to_typedef(self, typedef_curr, line, lnum):
"""Add new fields to the current typedef."""
mtch = re.match(r'^(\S+):\s*(\S.*)$', line)
if mtch:
field_name = mtch.group(1)
field_value = mtch.group(2).split('!')[0].rstrip()
if field_name == "id":
... | def function[_add_to_typedef, parameter[self, typedef_curr, line, lnum]]:
constant[Add new fields to the current typedef.]
variable[mtch] assign[=] call[name[re].match, parameter[constant[^(\S+):\s*(\S.*)$], name[line]]]
if name[mtch] begin[:]
variable[field_name] assign[=] call[... | keyword[def] identifier[_add_to_typedef] ( identifier[self] , identifier[typedef_curr] , identifier[line] , identifier[lnum] ):
literal[string]
identifier[mtch] = identifier[re] . identifier[match] ( literal[string] , identifier[line] )
keyword[if] identifier[mtch] :
identifi... | def _add_to_typedef(self, typedef_curr, line, lnum):
"""Add new fields to the current typedef."""
mtch = re.match('^(\\S+):\\s*(\\S.*)$', line)
if mtch:
field_name = mtch.group(1)
field_value = mtch.group(2).split('!')[0].rstrip()
if field_name == 'id':
self._chk_none(typ... |
def multi_ops(data_stream, *funcs):
""" fork a generator with multiple operations/functions
data_stream - an iterable data structure (ie: list/generator/tuple)
funcs - every function that will be applied to the data_stream """
assert all(callable(func) for func in funcs), 'multi_ops ... | def function[multi_ops, parameter[data_stream]]:
constant[ fork a generator with multiple operations/functions
data_stream - an iterable data structure (ie: list/generator/tuple)
funcs - every function that will be applied to the data_stream ]
assert[call[name[all], parameter[<ast... | keyword[def] identifier[multi_ops] ( identifier[data_stream] ,* identifier[funcs] ):
literal[string]
keyword[assert] identifier[all] ( identifier[callable] ( identifier[func] ) keyword[for] identifier[func] keyword[in] identifier[funcs] ), literal[string]
keyword[assert] identifier[len] ( ident... | def multi_ops(data_stream, *funcs):
""" fork a generator with multiple operations/functions
data_stream - an iterable data structure (ie: list/generator/tuple)
funcs - every function that will be applied to the data_stream """
assert all((callable(func) for func in funcs)), 'multi_ops... |
def register(cls, key, filename):
"""Register a image file using key"""
if key in cls._stock:
logger.info('Warning, replacing resource ' + str(key))
cls._stock[key] = {'type': 'custom', 'filename': filename}
logger.info('%s registered as %s' % (filename, key)) | def function[register, parameter[cls, key, filename]]:
constant[Register a image file using key]
if compare[name[key] in name[cls]._stock] begin[:]
call[name[logger].info, parameter[binary_operation[constant[Warning, replacing resource ] + call[name[str], parameter[name[key]]]]]]
... | keyword[def] identifier[register] ( identifier[cls] , identifier[key] , identifier[filename] ):
literal[string]
keyword[if] identifier[key] keyword[in] identifier[cls] . identifier[_stock] :
identifier[logger] . identifier[info] ( literal[string] + identifier[str] ( identifier[key]... | def register(cls, key, filename):
"""Register a image file using key"""
if key in cls._stock:
logger.info('Warning, replacing resource ' + str(key)) # depends on [control=['if'], data=['key']]
cls._stock[key] = {'type': 'custom', 'filename': filename}
logger.info('%s registered as %s' % (filena... |
def validate(bo, error_level: str = "WARNING") -> Tuple[bool, List[Tuple[str, str]]]:
"""Semantically validate BEL AST
Add errors and warnings to bel_obj.validation_messages
Error Levels are similar to log levels - selecting WARNING includes both
WARNING and ERROR, selecting ERROR just includes ERROR
... | def function[validate, parameter[bo, error_level]]:
constant[Semantically validate BEL AST
Add errors and warnings to bel_obj.validation_messages
Error Levels are similar to log levels - selecting WARNING includes both
WARNING and ERROR, selecting ERROR just includes ERROR
Args:
bo: m... | keyword[def] identifier[validate] ( identifier[bo] , identifier[error_level] : identifier[str] = literal[string] )-> identifier[Tuple] [ identifier[bool] , identifier[List] [ identifier[Tuple] [ identifier[str] , identifier[str] ]]]:
literal[string]
keyword[if] identifier[bo] . identifier[ast] :
... | def validate(bo, error_level: str='WARNING') -> Tuple[bool, List[Tuple[str, str]]]:
"""Semantically validate BEL AST
Add errors and warnings to bel_obj.validation_messages
Error Levels are similar to log levels - selecting WARNING includes both
WARNING and ERROR, selecting ERROR just includes ERROR
... |
def get_config(name, region=None, key=None, keyid=None, profile=None):
'''
Get the configuration for a cache cluster.
CLI example::
salt myminion boto_elasticache.get_config myelasticache
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
r... | def function[get_config, parameter[name, region, key, keyid, profile]]:
constant[
Get the configuration for a cache cluster.
CLI example::
salt myminion boto_elasticache.get_config myelasticache
]
variable[conn] assign[=] call[name[_get_conn], parameter[]]
if <ast.UnaryOp o... | keyword[def] identifier[get_config] ( identifier[name] , identifier[region] = keyword[None] , identifier[key] = keyword[None] , identifier[keyid] = keyword[None] , identifier[profile] = keyword[None] ):
literal[string]
identifier[conn] = identifier[_get_conn] ( identifier[region] = identifier[region] , ide... | def get_config(name, region=None, key=None, keyid=None, profile=None):
"""
Get the configuration for a cache cluster.
CLI example::
salt myminion boto_elasticache.get_config myelasticache
"""
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
re... |
def _register_diff_order_book_channels(self):
"""
Registers the binding for the diff_order_book channels.
:return:
"""
channels = {'diff_order_book': self.btcusd_dob_callback,
'diff_order_book_btceur': self.btceur_dob_callback,
'diff_order_... | def function[_register_diff_order_book_channels, parameter[self]]:
constant[
Registers the binding for the diff_order_book channels.
:return:
]
variable[channels] assign[=] dictionary[[<ast.Constant object at 0x7da204962380>, <ast.Constant object at 0x7da204963340>, <ast.Constant... | keyword[def] identifier[_register_diff_order_book_channels] ( identifier[self] ):
literal[string]
identifier[channels] ={ literal[string] : identifier[self] . identifier[btcusd_dob_callback] ,
literal[string] : identifier[self] . identifier[btceur_dob_callback] ,
literal[string] :... | def _register_diff_order_book_channels(self):
"""
Registers the binding for the diff_order_book channels.
:return:
"""
channels = {'diff_order_book': self.btcusd_dob_callback, 'diff_order_book_btceur': self.btceur_dob_callback, 'diff_order_book_eurusd': self.eurusd_dob_callback, 'diff_or... |
def _read_check(self, filepath):
"""Returns the path of a file on the *local* system that can be read
from. If the filepath is on a remote server, the file is first copied
locally."""
if self.is_ssh(filepath):
self._check_ftp()
#First we need to generate a file pa... | def function[_read_check, parameter[self, filepath]]:
constant[Returns the path of a file on the *local* system that can be read
from. If the filepath is on a remote server, the file is first copied
locally.]
if call[name[self].is_ssh, parameter[name[filepath]]] begin[:]
... | keyword[def] identifier[_read_check] ( identifier[self] , identifier[filepath] ):
literal[string]
keyword[if] identifier[self] . identifier[is_ssh] ( identifier[filepath] ):
identifier[self] . identifier[_check_ftp] ()
identifier[source] = identi... | def _read_check(self, filepath):
"""Returns the path of a file on the *local* system that can be read
from. If the filepath is on a remote server, the file is first copied
locally."""
if self.is_ssh(filepath):
self._check_ftp()
#First we need to generate a file path on the local ... |
def create_packet(reqid, message):
"""Creates Outgoing Packet from a given reqid and message
:param reqid: REQID object
:param message: protocol buffer object
"""
assert message.IsInitialized()
packet = ''
# calculate the totla size of the packet incl. header
typename = message.DESCRIP... | def function[create_packet, parameter[reqid, message]]:
constant[Creates Outgoing Packet from a given reqid and message
:param reqid: REQID object
:param message: protocol buffer object
]
assert[call[name[message].IsInitialized, parameter[]]]
variable[packet] assign[=] constant[]
... | keyword[def] identifier[create_packet] ( identifier[reqid] , identifier[message] ):
literal[string]
keyword[assert] identifier[message] . identifier[IsInitialized] ()
identifier[packet] = literal[string]
identifier[typename] = identifier[message] . identifier[DESCRIPTOR] . identifier[full... | def create_packet(reqid, message):
"""Creates Outgoing Packet from a given reqid and message
:param reqid: REQID object
:param message: protocol buffer object
"""
assert message.IsInitialized()
packet = ''
# calculate the totla size of the packet incl. header
typename = message.DESCRIPT... |
def get_dataset(self, owner, id, **kwargs):
"""
Retrieve a dataset
Return details on the dataset.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
... | def function[get_dataset, parameter[self, owner, id]]:
constant[
Retrieve a dataset
Return details on the dataset.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receivi... | keyword[def] identifier[get_dataset] ( identifier[self] , identifier[owner] , identifier[id] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] ... | def get_dataset(self, owner, id, **kwargs):
"""
Retrieve a dataset
Return details on the dataset.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
... |
def get_water_level(cls):
""" This method uses the ADC on the control module to measure
the current water tank level and returns the water volume
remaining in the tank.
For this method, it is assumed that a simple voltage divider
is used to interface the se... | def function[get_water_level, parameter[cls]]:
constant[ This method uses the ADC on the control module to measure
the current water tank level and returns the water volume
remaining in the tank.
For this method, it is assumed that a simple voltage divider
is use... | keyword[def] identifier[get_water_level] ( identifier[cls] ):
literal[string]
identifier[vref] = literal[int]
identifier[tank_height] = literal[int]
identifier[rref] = literal[int]
identifier[val] = literal[int]
keyword[for... | def get_water_level(cls):
""" This method uses the ADC on the control module to measure
the current water tank level and returns the water volume
remaining in the tank.
For this method, it is assumed that a simple voltage divider
is used to interface the sensor to th... |
def parse_format_index(self, text):
"""Parse format index."""
base = 10
prefix = text[1:3] if text[0] == "-" else text[:2]
if prefix[0:1] == "0":
char = prefix[-1]
if char == "b":
base = 2
elif char == "o":
base = 8
... | def function[parse_format_index, parameter[self, text]]:
constant[Parse format index.]
variable[base] assign[=] constant[10]
variable[prefix] assign[=] <ast.IfExp object at 0x7da1b0300370>
if compare[call[name[prefix]][<ast.Slice object at 0x7da1b0300ee0>] equal[==] constant[0]] begin[:]... | keyword[def] identifier[parse_format_index] ( identifier[self] , identifier[text] ):
literal[string]
identifier[base] = literal[int]
identifier[prefix] = identifier[text] [ literal[int] : literal[int] ] keyword[if] identifier[text] [ literal[int] ]== literal[string] keyword[else] iden... | def parse_format_index(self, text):
"""Parse format index."""
base = 10
prefix = text[1:3] if text[0] == '-' else text[:2]
if prefix[0:1] == '0':
char = prefix[-1]
if char == 'b':
base = 2 # depends on [control=['if'], data=[]]
elif char == 'o':
base = 8 ... |
def rename(self, image_name, path):
'''rename performs a move, but ensures the path is maintained in storage
Parameters
==========
image_name: the image name (uri) to rename to.
path: the name to rename (basename is taken)
'''
container = self.get(image_name, quiet=True)
i... | def function[rename, parameter[self, image_name, path]]:
constant[rename performs a move, but ensures the path is maintained in storage
Parameters
==========
image_name: the image name (uri) to rename to.
path: the name to rename (basename is taken)
]
variable[container... | keyword[def] identifier[rename] ( identifier[self] , identifier[image_name] , identifier[path] ):
literal[string]
identifier[container] = identifier[self] . identifier[get] ( identifier[image_name] , identifier[quiet] = keyword[True] )
keyword[if] identifier[container] keyword[is] keyword[not] ke... | def rename(self, image_name, path):
"""rename performs a move, but ensures the path is maintained in storage
Parameters
==========
image_name: the image name (uri) to rename to.
path: the name to rename (basename is taken)
"""
container = self.get(image_name, quiet=True)
if... |
def parse_doc_dict(text=None, split_character="::"):
"""
Returns a dictionary of the parsed doc for
example the following would return {'a':'A','b':'B'} ::
a:A
b:B
:param split_character:
:param text: str of the text to parse, by default uses calling function doc
:param split_ch... | def function[parse_doc_dict, parameter[text, split_character]]:
constant[
Returns a dictionary of the parsed doc for
example the following would return {'a':'A','b':'B'} ::
a:A
b:B
:param split_character:
:param text: str of the text to parse, by default uses calling function do... | keyword[def] identifier[parse_doc_dict] ( identifier[text] = keyword[None] , identifier[split_character] = literal[string] ):
literal[string]
identifier[text] = identifier[text] keyword[or] identifier[function_doc] ( literal[int] )
identifier[text] = identifier[text] . identifier[split] ( identifier... | def parse_doc_dict(text=None, split_character='::'):
"""
Returns a dictionary of the parsed doc for
example the following would return {'a':'A','b':'B'} ::
a:A
b:B
:param split_character:
:param text: str of the text to parse, by default uses calling function doc
:param split_ch... |
def get_cacheable(cache_key, cache_ttl, calculate, recalculate=False):
"""
Gets the result of a method call, using the given key and TTL as a cache
"""
if not recalculate:
cached = cache.get(cache_key)
if cached is not None:
return json.loads(cached)
calculated = calcula... | def function[get_cacheable, parameter[cache_key, cache_ttl, calculate, recalculate]]:
constant[
Gets the result of a method call, using the given key and TTL as a cache
]
if <ast.UnaryOp object at 0x7da2045662c0> begin[:]
variable[cached] assign[=] call[name[cache].get, parameter... | keyword[def] identifier[get_cacheable] ( identifier[cache_key] , identifier[cache_ttl] , identifier[calculate] , identifier[recalculate] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[recalculate] :
identifier[cached] = identifier[cache] . identifier[get] ( identifier[ca... | def get_cacheable(cache_key, cache_ttl, calculate, recalculate=False):
"""
Gets the result of a method call, using the given key and TTL as a cache
"""
if not recalculate:
cached = cache.get(cache_key)
if cached is not None:
return json.loads(cached) # depends on [control=['... |
def parse(self, data, path=None):
"""
Args:
data (str): Raw specification text.
path (Optional[str]): Path to specification on filesystem. Only
used to tag tokens with the file they originated from.
"""
assert not self.exhausted, 'Must call get_par... | def function[parse, parameter[self, data, path]]:
constant[
Args:
data (str): Raw specification text.
path (Optional[str]): Path to specification on filesystem. Only
used to tag tokens with the file they originated from.
]
assert[<ast.UnaryOp object at... | keyword[def] identifier[parse] ( identifier[self] , identifier[data] , identifier[path] = keyword[None] ):
literal[string]
keyword[assert] keyword[not] identifier[self] . identifier[exhausted] , literal[string]
identifier[self] . identifier[path] = identifier[path]
identifier[... | def parse(self, data, path=None):
"""
Args:
data (str): Raw specification text.
path (Optional[str]): Path to specification on filesystem. Only
used to tag tokens with the file they originated from.
"""
assert not self.exhausted, 'Must call get_parser() to... |
def set_variable(section, value, create):
"""
Set value of a variable in an environment file for the given section.
If the variable is already defined, its value is replaced, otherwise, it is added to the end of the file.
The value is given as "ENV_VAR_NAME=env_var_value", e.g.:
s3conf set test ENV... | def function[set_variable, parameter[section, value, create]]:
constant[
Set value of a variable in an environment file for the given section.
If the variable is already defined, its value is replaced, otherwise, it is added to the end of the file.
The value is given as "ENV_VAR_NAME=env_var_value",... | keyword[def] identifier[set_variable] ( identifier[section] , identifier[value] , identifier[create] ):
literal[string]
keyword[if] keyword[not] identifier[value] :
identifier[value] = identifier[section]
identifier[section] = keyword[None]
keyword[try] :
identifier[logg... | def set_variable(section, value, create):
"""
Set value of a variable in an environment file for the given section.
If the variable is already defined, its value is replaced, otherwise, it is added to the end of the file.
The value is given as "ENV_VAR_NAME=env_var_value", e.g.:
s3conf set test ENV... |
def from_shape(self, shape, rho, gm, nmax=7, lmax=None, lmax_grid=None,
lmax_calc=None, omega=None):
"""
Initialize a class of gravitational potential spherical harmonic
coefficients by calculuting the gravitational potential associatiated
with relief along an interfac... | def function[from_shape, parameter[self, shape, rho, gm, nmax, lmax, lmax_grid, lmax_calc, omega]]:
constant[
Initialize a class of gravitational potential spherical harmonic
coefficients by calculuting the gravitational potential associatiated
with relief along an interface.
Us... | keyword[def] identifier[from_shape] ( identifier[self] , identifier[shape] , identifier[rho] , identifier[gm] , identifier[nmax] = literal[int] , identifier[lmax] = keyword[None] , identifier[lmax_grid] = keyword[None] ,
identifier[lmax_calc] = keyword[None] , identifier[omega] = keyword[None] ):
literal[st... | def from_shape(self, shape, rho, gm, nmax=7, lmax=None, lmax_grid=None, lmax_calc=None, omega=None):
"""
Initialize a class of gravitational potential spherical harmonic
coefficients by calculuting the gravitational potential associatiated
with relief along an interface.
Usage
... |
def paint(self, painter, option, index):
"""Paint checkbox and text
_________________________________________
| | label | duration |
|toggle |_____________________| |
| | families | |
|_______|___________________... | def function[paint, parameter[self, painter, option, index]]:
constant[Paint checkbox and text
_________________________________________
| | label | duration |
|toggle |_____________________| |
| | families | |
|... | keyword[def] identifier[paint] ( identifier[self] , identifier[painter] , identifier[option] , identifier[index] ):
literal[string]
identifier[spacing] = literal[int]
identifier[metrics] = identifier[painter] . identifier[fontMetrics] ()
identifier[body_rect] = identif... | def paint(self, painter, option, index):
"""Paint checkbox and text
_________________________________________
| | label | duration |
|toggle |_____________________| |
| | families | |
|_______|_____________________|_... |
def _normal_model(self, beta):
""" Creates the structure of the model (model matrices, etc) for
a Normal family ARIMAX model.
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for the latent variables
Returns
----------
... | def function[_normal_model, parameter[self, beta]]:
constant[ Creates the structure of the model (model matrices, etc) for
a Normal family ARIMAX model.
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for the latent variables
R... | keyword[def] identifier[_normal_model] ( identifier[self] , identifier[beta] ):
literal[string]
identifier[Y] = identifier[self] . identifier[y] [ identifier[self] . identifier[max_lag] :]
identifier[z] = identifier[np] . identifier[array] ([ identifier[self] . identifier[latent... | def _normal_model(self, beta):
""" Creates the structure of the model (model matrices, etc) for
a Normal family ARIMAX model.
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for the latent variables
Returns
----------
... |
def get_scraperclasses():
"""Find all comic scraper classes in the plugins directory.
The result is cached.
@return: list of Scraper classes
@rtype: list of Scraper
"""
global _scraperclasses
if _scraperclasses is None:
out.debug(u"Loading comic modules...")
modules = loader.... | def function[get_scraperclasses, parameter[]]:
constant[Find all comic scraper classes in the plugins directory.
The result is cached.
@return: list of Scraper classes
@rtype: list of Scraper
]
<ast.Global object at 0x7da207f98ac0>
if compare[name[_scraperclasses] is constant[None]] ... | keyword[def] identifier[get_scraperclasses] ():
literal[string]
keyword[global] identifier[_scraperclasses]
keyword[if] identifier[_scraperclasses] keyword[is] keyword[None] :
identifier[out] . identifier[debug] ( literal[string] )
identifier[modules] = identifier[loader] . iden... | def get_scraperclasses():
"""Find all comic scraper classes in the plugins directory.
The result is cached.
@return: list of Scraper classes
@rtype: list of Scraper
"""
global _scraperclasses
if _scraperclasses is None:
out.debug(u'Loading comic modules...')
modules = loader.... |
def _get_offset(self):
"""
Subclasses may override this method.
"""
sx, sxy, syx, sy, ox, oy = self.transformation
return (ox, oy) | def function[_get_offset, parameter[self]]:
constant[
Subclasses may override this method.
]
<ast.Tuple object at 0x7da20c76c8b0> assign[=] name[self].transformation
return[tuple[[<ast.Name object at 0x7da20c76de40>, <ast.Name object at 0x7da20c76e2f0>]]] | keyword[def] identifier[_get_offset] ( identifier[self] ):
literal[string]
identifier[sx] , identifier[sxy] , identifier[syx] , identifier[sy] , identifier[ox] , identifier[oy] = identifier[self] . identifier[transformation]
keyword[return] ( identifier[ox] , identifier[oy] ) | def _get_offset(self):
"""
Subclasses may override this method.
"""
(sx, sxy, syx, sy, ox, oy) = self.transformation
return (ox, oy) |
def eeg_select_channels(raw, channel_names):
"""
Select one or several channels by name and returns them in a dataframe.
Parameters
----------
raw : mne.io.Raw
Raw EEG data.
channel_names : str or list
Channel's name(s).
Returns
----------
channels : pd.DataFrame
... | def function[eeg_select_channels, parameter[raw, channel_names]]:
constant[
Select one or several channels by name and returns them in a dataframe.
Parameters
----------
raw : mne.io.Raw
Raw EEG data.
channel_names : str or list
Channel's name(s).
Returns
----------... | keyword[def] identifier[eeg_select_channels] ( identifier[raw] , identifier[channel_names] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[channel_names] , identifier[list] ) keyword[is] keyword[False] :
identifier[channel_names] =[ identifier[channel_names] ]
identifier... | def eeg_select_channels(raw, channel_names):
"""
Select one or several channels by name and returns them in a dataframe.
Parameters
----------
raw : mne.io.Raw
Raw EEG data.
channel_names : str or list
Channel's name(s).
Returns
----------
channels : pd.DataFrame
... |
def dtype(self, byte_order='='):
'''
Return the numpy dtype of the in-memory representation of the
data. (If there are no list properties, and the PLY format is
binary, then this also accurately describes the on-disk
representation of the element.)
'''
return _n... | def function[dtype, parameter[self, byte_order]]:
constant[
Return the numpy dtype of the in-memory representation of the
data. (If there are no list properties, and the PLY format is
binary, then this also accurately describes the on-disk
representation of the element.)
... | keyword[def] identifier[dtype] ( identifier[self] , identifier[byte_order] = literal[string] ):
literal[string]
keyword[return] identifier[_np] . identifier[dtype] ([( identifier[prop] . identifier[name] , identifier[prop] . identifier[dtype] ( identifier[byte_order] ))
keyword[for] iden... | def dtype(self, byte_order='='):
"""
Return the numpy dtype of the in-memory representation of the
data. (If there are no list properties, and the PLY format is
binary, then this also accurately describes the on-disk
representation of the element.)
"""
return _np.dtype(... |
def copy_data_ext(self, model, field, dest=None, idx=None, astype=None):
"""
Retrieve the field of another model and store it as a field.
:param model: name of the source model being a model name or a group name
:param field: name of the field to retrieve
:param dest: name of th... | def function[copy_data_ext, parameter[self, model, field, dest, idx, astype]]:
constant[
Retrieve the field of another model and store it as a field.
:param model: name of the source model being a model name or a group name
:param field: name of the field to retrieve
:param dest... | keyword[def] identifier[copy_data_ext] ( identifier[self] , identifier[model] , identifier[field] , identifier[dest] = keyword[None] , identifier[idx] = keyword[None] , identifier[astype] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[dest] :
identif... | def copy_data_ext(self, model, field, dest=None, idx=None, astype=None):
"""
Retrieve the field of another model and store it as a field.
:param model: name of the source model being a model name or a group name
:param field: name of the field to retrieve
:param dest: name of the de... |
def open(cls, path):
"""Load an image file into a PIX object.
Leptonica can load TIFF, PNM (PBM, PGM, PPM), PNG, and JPEG. If
loading fails then the object will wrap a C null pointer.
"""
filename = fspath(path)
with _LeptonicaErrorTrap():
return cls(lept.pi... | def function[open, parameter[cls, path]]:
constant[Load an image file into a PIX object.
Leptonica can load TIFF, PNM (PBM, PGM, PPM), PNG, and JPEG. If
loading fails then the object will wrap a C null pointer.
]
variable[filename] assign[=] call[name[fspath], parameter[name[pa... | keyword[def] identifier[open] ( identifier[cls] , identifier[path] ):
literal[string]
identifier[filename] = identifier[fspath] ( identifier[path] )
keyword[with] identifier[_LeptonicaErrorTrap] ():
keyword[return] identifier[cls] ( identifier[lept] . identifier[pixRead] ( i... | def open(cls, path):
"""Load an image file into a PIX object.
Leptonica can load TIFF, PNM (PBM, PGM, PPM), PNG, and JPEG. If
loading fails then the object will wrap a C null pointer.
"""
filename = fspath(path)
with _LeptonicaErrorTrap():
return cls(lept.pixRead(os.fsencod... |
def get_video(self, node):
"""
Create a video object from a video embed
"""
video = Video()
video.embed_code = self.get_embed_code(node)
video.embed_type = self.get_embed_type(node)
video.width = self.get_width(node)
video.height = self.get_height(node)
... | def function[get_video, parameter[self, node]]:
constant[
Create a video object from a video embed
]
variable[video] assign[=] call[name[Video], parameter[]]
name[video].embed_code assign[=] call[name[self].get_embed_code, parameter[name[node]]]
name[video].embed_type ass... | keyword[def] identifier[get_video] ( identifier[self] , identifier[node] ):
literal[string]
identifier[video] = identifier[Video] ()
identifier[video] . identifier[embed_code] = identifier[self] . identifier[get_embed_code] ( identifier[node] )
identifier[video] . identifier[embed... | def get_video(self, node):
"""
Create a video object from a video embed
"""
video = Video()
video.embed_code = self.get_embed_code(node)
video.embed_type = self.get_embed_type(node)
video.width = self.get_width(node)
video.height = self.get_height(node)
video.src = self.get_s... |
def calc_contriarea_v1(self):
"""Determine the relative size of the contributing area of the whole
subbasin.
Required control parameters:
|NmbZones|
|ZoneType|
|RespArea|
|FC|
|Beta|
Required derived parameter:
|RelSoilArea|
Required state sequence:
|SM|
... | def function[calc_contriarea_v1, parameter[self]]:
constant[Determine the relative size of the contributing area of the whole
subbasin.
Required control parameters:
|NmbZones|
|ZoneType|
|RespArea|
|FC|
|Beta|
Required derived parameter:
|RelSoilArea|
Require... | keyword[def] identifier[calc_contriarea_v1] ( identifier[self] ):
literal[string]
identifier[con] = identifier[self] . identifier[parameters] . identifier[control] . identifier[fastaccess]
identifier[der] = identifier[self] . identifier[parameters] . identifier[derived] . identifier[fastaccess]
... | def calc_contriarea_v1(self):
"""Determine the relative size of the contributing area of the whole
subbasin.
Required control parameters:
|NmbZones|
|ZoneType|
|RespArea|
|FC|
|Beta|
Required derived parameter:
|RelSoilArea|
Required state sequence:
|SM|
... |
def service_data(self):
"""
Returns all introspected service data.
If the data has been previously accessed, a memoized version of the
data is returned.
:returns: A dict of introspected service data
:rtype: dict
"""
# Lean on the cache first.
if ... | def function[service_data, parameter[self]]:
constant[
Returns all introspected service data.
If the data has been previously accessed, a memoized version of the
data is returned.
:returns: A dict of introspected service data
:rtype: dict
]
if compare[na... | keyword[def] identifier[service_data] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_loaded_service_data] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[self] . identifier[_loaded_service_data]
... | def service_data(self):
"""
Returns all introspected service data.
If the data has been previously accessed, a memoized version of the
data is returned.
:returns: A dict of introspected service data
:rtype: dict
"""
# Lean on the cache first.
if self._loaded... |
def generate_ssh(self, server, args, configure):
"""
εΌζ₯εζΆζ§θ‘SSHηζ generate ssh
:param server:
:param args:
:param configure:
:return:
"""
self.reset_server_env(server, configure)
# chmod project root owner
sudo('chown {user}:{user} -R {path... | def function[generate_ssh, parameter[self, server, args, configure]]:
constant[
εΌζ₯εζΆζ§θ‘SSHηζ generate ssh
:param server:
:param args:
:param configure:
:return:
]
call[name[self].reset_server_env, parameter[name[server], name[configure]]]
call[name[... | keyword[def] identifier[generate_ssh] ( identifier[self] , identifier[server] , identifier[args] , identifier[configure] ):
literal[string]
identifier[self] . identifier[reset_server_env] ( identifier[server] , identifier[configure] )
identifier[sudo] ( literal[string] . identifi... | def generate_ssh(self, server, args, configure):
"""
εΌζ₯εζΆζ§θ‘SSHηζ generate ssh
:param server:
:param args:
:param configure:
:return:
"""
self.reset_server_env(server, configure)
# chmod project root owner
sudo('chown {user}:{user} -R {path}'.format(user=co... |
def _deserialize(s, proto): # type: (bytes, _Proto) -> _Proto
'''
Parse bytes into a in-memory proto
@params
s is bytes containing serialized proto
proto is a in-memory proto object
@return
The proto instance filled in by s
'''
if not isinstance(s, bytes):
raise ValueError... | def function[_deserialize, parameter[s, proto]]:
constant[
Parse bytes into a in-memory proto
@params
s is bytes containing serialized proto
proto is a in-memory proto object
@return
The proto instance filled in by s
]
if <ast.UnaryOp object at 0x7da18fe90460> begin[:]
... | keyword[def] identifier[_deserialize] ( identifier[s] , identifier[proto] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[s] , identifier[bytes] ):
keyword[raise] identifier[ValueError] ( literal[string] . identifier[format] ( identifier[type] ( identifier[s] )))... | def _deserialize(s, proto): # type: (bytes, _Proto) -> _Proto
'\n Parse bytes into a in-memory proto\n\n @params\n s is bytes containing serialized proto\n proto is a in-memory proto object\n\n @return\n The proto instance filled in by s\n '
if not isinstance(s, bytes):
raise Value... |
def recipe_velocity(adata, min_counts=3, min_counts_u=3, n_top_genes=None, n_pcs=30, n_neighbors=30, log=True, copy=False):
"""Runs pp.filter_and_normalize() and pp.moments()
"""
from .moments import moments
filter_and_normalize(adata, min_counts=min_counts, min_counts_u=min_counts_u, n_top_genes=n_top_... | def function[recipe_velocity, parameter[adata, min_counts, min_counts_u, n_top_genes, n_pcs, n_neighbors, log, copy]]:
constant[Runs pp.filter_and_normalize() and pp.moments()
]
from relative_module[moments] import module[moments]
call[name[filter_and_normalize], parameter[name[adata]]]
... | keyword[def] identifier[recipe_velocity] ( identifier[adata] , identifier[min_counts] = literal[int] , identifier[min_counts_u] = literal[int] , identifier[n_top_genes] = keyword[None] , identifier[n_pcs] = literal[int] , identifier[n_neighbors] = literal[int] , identifier[log] = keyword[True] , identifier[copy] = ke... | def recipe_velocity(adata, min_counts=3, min_counts_u=3, n_top_genes=None, n_pcs=30, n_neighbors=30, log=True, copy=False):
"""Runs pp.filter_and_normalize() and pp.moments()
"""
from .moments import moments
filter_and_normalize(adata, min_counts=min_counts, min_counts_u=min_counts_u, n_top_genes=n_top_... |
def _stream_docker_logs(self):
"""Stream stdout and stderr from the task container to this
process's stdout and stderr, respectively.
"""
thread = threading.Thread(target=self._stderr_stream_worker)
thread.start()
for line in self.docker_client.logs(self.container, stdout... | def function[_stream_docker_logs, parameter[self]]:
constant[Stream stdout and stderr from the task container to this
process's stdout and stderr, respectively.
]
variable[thread] assign[=] call[name[threading].Thread, parameter[]]
call[name[thread].start, parameter[]]
fo... | keyword[def] identifier[_stream_docker_logs] ( identifier[self] ):
literal[string]
identifier[thread] = identifier[threading] . identifier[Thread] ( identifier[target] = identifier[self] . identifier[_stderr_stream_worker] )
identifier[thread] . identifier[start] ()
keyword[for] ... | def _stream_docker_logs(self):
"""Stream stdout and stderr from the task container to this
process's stdout and stderr, respectively.
"""
thread = threading.Thread(target=self._stderr_stream_worker)
thread.start()
for line in self.docker_client.logs(self.container, stdout=True, stderr=Fa... |
def risearch(self):
"instance of :class:`eulfedora.api.ResourceIndex`, with the same root url and credentials"
if self._risearch is None:
self._risearch = ResourceIndex(self.fedora_root, self.username, self.password)
return self._risearch | def function[risearch, parameter[self]]:
constant[instance of :class:`eulfedora.api.ResourceIndex`, with the same root url and credentials]
if compare[name[self]._risearch is constant[None]] begin[:]
name[self]._risearch assign[=] call[name[ResourceIndex], parameter[name[self].fedora_roo... | keyword[def] identifier[risearch] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_risearch] keyword[is] keyword[None] :
identifier[self] . identifier[_risearch] = identifier[ResourceIndex] ( identifier[self] . identifier[fedora_root] , identifier[sel... | def risearch(self):
"""instance of :class:`eulfedora.api.ResourceIndex`, with the same root url and credentials"""
if self._risearch is None:
self._risearch = ResourceIndex(self.fedora_root, self.username, self.password) # depends on [control=['if'], data=[]]
return self._risearch |
def precision_series(y_true, y_score, k=None):
"""
Returns series of length k whose i-th entry is the precision in the top i
TODO: extrapolate here
"""
y_true, y_score = to_float(y_true, y_score)
top = _argsort(y_score, k)
n = np.nan_to_num(y_true[top]).cumsum() # fill missing labels with ... | def function[precision_series, parameter[y_true, y_score, k]]:
constant[
Returns series of length k whose i-th entry is the precision in the top i
TODO: extrapolate here
]
<ast.Tuple object at 0x7da1b24c2170> assign[=] call[name[to_float], parameter[name[y_true], name[y_score]]]
vari... | keyword[def] identifier[precision_series] ( identifier[y_true] , identifier[y_score] , identifier[k] = keyword[None] ):
literal[string]
identifier[y_true] , identifier[y_score] = identifier[to_float] ( identifier[y_true] , identifier[y_score] )
identifier[top] = identifier[_argsort] ( identifier[y_sco... | def precision_series(y_true, y_score, k=None):
"""
Returns series of length k whose i-th entry is the precision in the top i
TODO: extrapolate here
"""
(y_true, y_score) = to_float(y_true, y_score)
top = _argsort(y_score, k)
n = np.nan_to_num(y_true[top]).cumsum() # fill missing labels with... |
def datetimeobj_YmdHMS(value):
"""Convert timestamp string to a datetime object.
Timestamps strings like '20130618120000' are able to be converted by this
function.
Args:
value: A timestamp string in the format '%Y%m%d%H%M%S'.
Returns:
A datetime object.
Raises:
Value... | def function[datetimeobj_YmdHMS, parameter[value]]:
constant[Convert timestamp string to a datetime object.
Timestamps strings like '20130618120000' are able to be converted by this
function.
Args:
value: A timestamp string in the format '%Y%m%d%H%M%S'.
Returns:
A datetime obj... | keyword[def] identifier[datetimeobj_YmdHMS] ( identifier[value] ):
literal[string]
identifier[i] = identifier[int] ( identifier[value] )
identifier[S] = identifier[i]
identifier[M] = identifier[S] // literal[int]
identifier[H] = identifier[M] // literal[int]
identifier[d] = identifie... | def datetimeobj_YmdHMS(value):
"""Convert timestamp string to a datetime object.
Timestamps strings like '20130618120000' are able to be converted by this
function.
Args:
value: A timestamp string in the format '%Y%m%d%H%M%S'.
Returns:
A datetime object.
Raises:
Value... |
def update(self, values, copy_instance=False):
"""
Updates the configuration with the contents of the given configuration object or dictionary.
In case of a dictionary, only valid attributes for this class are considered. Existing attributes are replaced
with the new values. The object ... | def function[update, parameter[self, values, copy_instance]]:
constant[
Updates the configuration with the contents of the given configuration object or dictionary.
In case of a dictionary, only valid attributes for this class are considered. Existing attributes are replaced
with the ne... | keyword[def] identifier[update] ( identifier[self] , identifier[values] , identifier[copy_instance] = keyword[False] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[values] , identifier[self] . identifier[__class__] ):
identifier[self] . identifier[update_from_obj] ... | def update(self, values, copy_instance=False):
"""
Updates the configuration with the contents of the given configuration object or dictionary.
In case of a dictionary, only valid attributes for this class are considered. Existing attributes are replaced
with the new values. The object is n... |
def _crc8(self, buffer):
""" Polynomial 0x31 (x8 + x5 +x4 +1) """
polynomial = 0x31;
crc = 0xFF;
index = 0
for index in range(0, len(buffer)):
crc ^= buffer[index]
for i in range(8, 0, -1):
if crc & 0x80:
crc = (crc ... | def function[_crc8, parameter[self, buffer]]:
constant[ Polynomial 0x31 (x8 + x5 +x4 +1) ]
variable[polynomial] assign[=] constant[49]
variable[crc] assign[=] constant[255]
variable[index] assign[=] constant[0]
for taget[name[index]] in starred[call[name[range], parameter[constan... | keyword[def] identifier[_crc8] ( identifier[self] , identifier[buffer] ):
literal[string]
identifier[polynomial] = literal[int] ;
identifier[crc] = literal[int] ;
identifier[index] = literal[int]
keyword[for] identifier[index] keyword[in] identifier[range] ( literal... | def _crc8(self, buffer):
""" Polynomial 0x31 (x8 + x5 +x4 +1) """
polynomial = 49
crc = 255
index = 0
for index in range(0, len(buffer)):
crc ^= buffer[index]
for i in range(8, 0, -1):
if crc & 128:
crc = crc << 1 ^ polynomial # depends on [control=['if']... |
def get_xstatic_dirs(XSTATIC_MODULES, HORIZON_CONFIG):
"""Discover static file configuration of the xstatic modules.
For each entry in the XSTATIC_MODULES list we determine the entry
point files (which may come from the xstatic MAIN var) and then
determine where in the Django static tree the xstatic pa... | def function[get_xstatic_dirs, parameter[XSTATIC_MODULES, HORIZON_CONFIG]]:
constant[Discover static file configuration of the xstatic modules.
For each entry in the XSTATIC_MODULES list we determine the entry
point files (which may come from the xstatic MAIN var) and then
determine where in the Dj... | keyword[def] identifier[get_xstatic_dirs] ( identifier[XSTATIC_MODULES] , identifier[HORIZON_CONFIG] ):
literal[string]
identifier[STATICFILES_DIRS] =[]
identifier[HORIZON_CONFIG] . identifier[setdefault] ( literal[string] ,[])
keyword[for] identifier[module_name] , identifier[files] keyword[in... | def get_xstatic_dirs(XSTATIC_MODULES, HORIZON_CONFIG):
"""Discover static file configuration of the xstatic modules.
For each entry in the XSTATIC_MODULES list we determine the entry
point files (which may come from the xstatic MAIN var) and then
determine where in the Django static tree the xstatic pa... |
def CSS_setRuleSelector(self, styleSheetId, range, selector):
"""
Function path: CSS.setRuleSelector
Domain: CSS
Method name: setRuleSelector
Parameters:
Required arguments:
'styleSheetId' (type: StyleSheetId) -> No description
'range' (type: SourceRange) -> No description
'selector' ... | def function[CSS_setRuleSelector, parameter[self, styleSheetId, range, selector]]:
constant[
Function path: CSS.setRuleSelector
Domain: CSS
Method name: setRuleSelector
Parameters:
Required arguments:
'styleSheetId' (type: StyleSheetId) -> No description
'range' (type: SourceRange) -... | keyword[def] identifier[CSS_setRuleSelector] ( identifier[self] , identifier[styleSheetId] , identifier[range] , identifier[selector] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[selector] ,( identifier[str] ,)
), literal[string] % identifier[type] (
identifier[selector] )
id... | def CSS_setRuleSelector(self, styleSheetId, range, selector):
"""
Function path: CSS.setRuleSelector
Domain: CSS
Method name: setRuleSelector
Parameters:
Required arguments:
'styleSheetId' (type: StyleSheetId) -> No description
'range' (type: SourceRange) -> No description
'selector... |
def _sub(cmd, *sections):
"""Build Subcmd instance."""
cmd_func = cmd if isfunction(cmd) else cmd.cmd
return Subcmd(baredoc(cmd), *sections, func=cmd_func) | def function[_sub, parameter[cmd]]:
constant[Build Subcmd instance.]
variable[cmd_func] assign[=] <ast.IfExp object at 0x7da18f58f2e0>
return[call[name[Subcmd], parameter[call[name[baredoc], parameter[name[cmd]]], <ast.Starred object at 0x7da18f58ca90>]]] | keyword[def] identifier[_sub] ( identifier[cmd] ,* identifier[sections] ):
literal[string]
identifier[cmd_func] = identifier[cmd] keyword[if] identifier[isfunction] ( identifier[cmd] ) keyword[else] identifier[cmd] . identifier[cmd]
keyword[return] identifier[Subcmd] ( identifier[baredoc] ( ident... | def _sub(cmd, *sections):
"""Build Subcmd instance."""
cmd_func = cmd if isfunction(cmd) else cmd.cmd
return Subcmd(baredoc(cmd), *sections, func=cmd_func) |
def config(self):
"""Read the configuration variables and returns them as a dictionary
:rtype: dictionary
:Example:
>>> alpha.config()
{
'BPD 13': 1.6499,
'BPD 12': 1.6499,
'BPD 11': 1.6499,
'BPD 10': 1.6499,
'BPD 15'... | def function[config, parameter[self]]:
constant[Read the configuration variables and returns them as a dictionary
:rtype: dictionary
:Example:
>>> alpha.config()
{
'BPD 13': 1.6499,
'BPD 12': 1.6499,
'BPD 11': 1.6499,
'BPD 10': 1... | keyword[def] identifier[config] ( identifier[self] ):
literal[string]
identifier[config] =[]
identifier[data] ={}
identifier[self] . identifier[cnxn] . identifier[xfer] ([ literal[int] ])
identifier[sleep] ( literal[int] )
keyword[for] identi... | def config(self):
"""Read the configuration variables and returns them as a dictionary
:rtype: dictionary
:Example:
>>> alpha.config()
{
'BPD 13': 1.6499,
'BPD 12': 1.6499,
'BPD 11': 1.6499,
'BPD 10': 1.6499,
'BPD 15': 1.... |
def subs_consts(self, expr):
"""Substitute constants in expression unless it is already a number."""
if isinstance(expr, numbers.Number):
return expr
else:
return expr.subs(self.constants) | def function[subs_consts, parameter[self, expr]]:
constant[Substitute constants in expression unless it is already a number.]
if call[name[isinstance], parameter[name[expr], name[numbers].Number]] begin[:]
return[name[expr]] | keyword[def] identifier[subs_consts] ( identifier[self] , identifier[expr] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[expr] , identifier[numbers] . identifier[Number] ):
keyword[return] identifier[expr]
keyword[else] :
keyword[return] i... | def subs_consts(self, expr):
"""Substitute constants in expression unless it is already a number."""
if isinstance(expr, numbers.Number):
return expr # depends on [control=['if'], data=[]]
else:
return expr.subs(self.constants) |
def leave(self, _id):
""" Leave a room """
if SockJSRoomHandler._room.has_key(self._gcls() + _id):
SockJSRoomHandler._room[self._gcls() + _id].remove(self)
if len(SockJSRoomHandler._room[self._gcls() + _id]) == 0:
del SockJSRoomHandler._room[self._gcls() + _id] | def function[leave, parameter[self, _id]]:
constant[ Leave a room ]
if call[name[SockJSRoomHandler]._room.has_key, parameter[binary_operation[call[name[self]._gcls, parameter[]] + name[_id]]]] begin[:]
call[call[name[SockJSRoomHandler]._room][binary_operation[call[name[self]._gcls, param... | keyword[def] identifier[leave] ( identifier[self] , identifier[_id] ):
literal[string]
keyword[if] identifier[SockJSRoomHandler] . identifier[_room] . identifier[has_key] ( identifier[self] . identifier[_gcls] ()+ identifier[_id] ):
identifier[SockJSRoomHandler] . identifier[_room] [ ... | def leave(self, _id):
""" Leave a room """
if SockJSRoomHandler._room.has_key(self._gcls() + _id):
SockJSRoomHandler._room[self._gcls() + _id].remove(self)
if len(SockJSRoomHandler._room[self._gcls() + _id]) == 0:
del SockJSRoomHandler._room[self._gcls() + _id] # depends on [control... |
def parse_results_mol2(mol2_outpath):
"""Parse a DOCK6 mol2 output file, return a Pandas DataFrame of the results.
Args:
mol2_outpath (str): Path to mol2 output file
Returns:
DataFrame: Pandas DataFrame of the results
"""
docked_ligands = pd.DataFrame()
lines = [line.strip() ... | def function[parse_results_mol2, parameter[mol2_outpath]]:
constant[Parse a DOCK6 mol2 output file, return a Pandas DataFrame of the results.
Args:
mol2_outpath (str): Path to mol2 output file
Returns:
DataFrame: Pandas DataFrame of the results
]
variable[docked_ligands] a... | keyword[def] identifier[parse_results_mol2] ( identifier[mol2_outpath] ):
literal[string]
identifier[docked_ligands] = identifier[pd] . identifier[DataFrame] ()
identifier[lines] =[ identifier[line] . identifier[strip] () keyword[for] identifier[line] keyword[in] identifier[open] ( identifier[mol2... | def parse_results_mol2(mol2_outpath):
"""Parse a DOCK6 mol2 output file, return a Pandas DataFrame of the results.
Args:
mol2_outpath (str): Path to mol2 output file
Returns:
DataFrame: Pandas DataFrame of the results
"""
docked_ligands = pd.DataFrame()
lines = [line.strip() f... |
def connect(cls, *args, **kwargs):
"""
connect(username=None, password=None, endpoint=None, admin=False)
Configures the Panoptes client for use.
Note that there is no need to call this unless you need to pass one or
more of the below arguments. By default, the client will conn... | def function[connect, parameter[cls]]:
constant[
connect(username=None, password=None, endpoint=None, admin=False)
Configures the Panoptes client for use.
Note that there is no need to call this unless you need to pass one or
more of the below arguments. By default, the client... | keyword[def] identifier[connect] ( identifier[cls] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[cls] . identifier[_local] . identifier[panoptes_client] = identifier[cls] (* identifier[args] ,** identifier[kwargs] )
identifier[cls] . identifier[_local] . identifi... | def connect(cls, *args, **kwargs):
"""
connect(username=None, password=None, endpoint=None, admin=False)
Configures the Panoptes client for use.
Note that there is no need to call this unless you need to pass one or
more of the below arguments. By default, the client will connect ... |
def execute_file(self, filename):
"""
Execute a file and provide feedback to the user.
:param filename: The pathname of the file to execute (a string).
:returns: Whatever the executed file returns on stdout (a string).
"""
logger.info("Executing file: %s", format_path(fi... | def function[execute_file, parameter[self, filename]]:
constant[
Execute a file and provide feedback to the user.
:param filename: The pathname of the file to execute (a string).
:returns: Whatever the executed file returns on stdout (a string).
]
call[name[logger].info,... | keyword[def] identifier[execute_file] ( identifier[self] , identifier[filename] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] , identifier[format_path] ( identifier[filename] ))
identifier[contents] = identifier[self] . identifier[context] . identifier[execute]... | def execute_file(self, filename):
"""
Execute a file and provide feedback to the user.
:param filename: The pathname of the file to execute (a string).
:returns: Whatever the executed file returns on stdout (a string).
"""
logger.info('Executing file: %s', format_path(filename))... |
def _remote_connection(server, opts, argparser_):
"""Initiate a remote connection, via PyWBEM. Arguments for
the request are part of the command line arguments and include
user name, password, namespace, etc.
"""
global CONN # pylint: disable=global-statement
if opts.timeout is not N... | def function[_remote_connection, parameter[server, opts, argparser_]]:
constant[Initiate a remote connection, via PyWBEM. Arguments for
the request are part of the command line arguments and include
user name, password, namespace, etc.
]
<ast.Global object at 0x7da204564550>
if com... | keyword[def] identifier[_remote_connection] ( identifier[server] , identifier[opts] , identifier[argparser_] ):
literal[string]
keyword[global] identifier[CONN]
keyword[if] identifier[opts] . identifier[timeout] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[opts] . ... | def _remote_connection(server, opts, argparser_):
"""Initiate a remote connection, via PyWBEM. Arguments for
the request are part of the command line arguments and include
user name, password, namespace, etc.
"""
global CONN # pylint: disable=global-statement
if opts.timeout is not None:
... |
def acquireConnection(self):
""" Get a connection from the pool.
Parameters:
----------------------------------------------------------------
retval: A ConnectionWrapper instance. NOTE: Caller
is responsible for calling the ConnectionWrapper
instance's rel... | def function[acquireConnection, parameter[self]]:
constant[ Get a connection from the pool.
Parameters:
----------------------------------------------------------------
retval: A ConnectionWrapper instance. NOTE: Caller
is responsible for calling the ConnectionWrapper
... | keyword[def] identifier[acquireConnection] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_logger] . identifier[debug] ( literal[string] )
identifier[dbConn] = identifier[self] . identifier[_pool] . identifier[connection] ( identifier[shareable] = keyword[False] )
identifier... | def acquireConnection(self):
""" Get a connection from the pool.
Parameters:
----------------------------------------------------------------
retval: A ConnectionWrapper instance. NOTE: Caller
is responsible for calling the ConnectionWrapper
instance's rel... |
def get_float_time():
'''returns time as double precision floats - Time64 in pytables - mapping to and from python datetime's
'''
t1 = time.time()
t2 = datetime.datetime.fromtimestamp(t1)
return time.mktime(t2.timetuple()) + 1e-6 * t2.microsecond | def function[get_float_time, parameter[]]:
constant[returns time as double precision floats - Time64 in pytables - mapping to and from python datetime's
]
variable[t1] assign[=] call[name[time].time, parameter[]]
variable[t2] assign[=] call[name[datetime].datetime.fromtimestamp, parameter[n... | keyword[def] identifier[get_float_time] ():
literal[string]
identifier[t1] = identifier[time] . identifier[time] ()
identifier[t2] = identifier[datetime] . identifier[datetime] . identifier[fromtimestamp] ( identifier[t1] )
keyword[return] identifier[time] . identifier[mktime] ( identifier[t... | def get_float_time():
"""returns time as double precision floats - Time64 in pytables - mapping to and from python datetime's
"""
t1 = time.time()
t2 = datetime.datetime.fromtimestamp(t1)
return time.mktime(t2.timetuple()) + 1e-06 * t2.microsecond |
def tracking_branch(self):
"""
:return: The remote_reference we are tracking, or None if we are
not a tracking branch"""
from .remote import RemoteReference
reader = self.config_reader()
if reader.has_option(self.k_config_remote) and reader.has_option(self.k_config_re... | def function[tracking_branch, parameter[self]]:
constant[
:return: The remote_reference we are tracking, or None if we are
not a tracking branch]
from relative_module[remote] import module[RemoteReference]
variable[reader] assign[=] call[name[self].config_reader, parameter[]]
... | keyword[def] identifier[tracking_branch] ( identifier[self] ):
literal[string]
keyword[from] . identifier[remote] keyword[import] identifier[RemoteReference]
identifier[reader] = identifier[self] . identifier[config_reader] ()
keyword[if] identifier[reader] . identifier[has_op... | def tracking_branch(self):
"""
:return: The remote_reference we are tracking, or None if we are
not a tracking branch"""
from .remote import RemoteReference
reader = self.config_reader()
if reader.has_option(self.k_config_remote) and reader.has_option(self.k_config_remote_ref):
... |
def register_onRsp(self, req):
"""
ζ·»ε εθ°ε€ηε½ζ°ηθ£
ι₯°ε¨
:param req: ε
·δ½ηtopicοΌε¦
:return:
"""
def wrapper(_callback):
callbackList = self._req_callbacks.setdefault(req, [])
callbackList.append(_callback)
return _callback
return wrapper | def function[register_onRsp, parameter[self, req]]:
constant[
ζ·»ε εθ°ε€ηε½ζ°ηθ£
ι₯°ε¨
:param req: ε
·δ½ηtopicοΌε¦
:return:
]
def function[wrapper, parameter[_callback]]:
variable[callbackList] assign[=] call[name[self]._req_callbacks.setdefault, parameter[name[req], list[... | keyword[def] identifier[register_onRsp] ( identifier[self] , identifier[req] ):
literal[string]
keyword[def] identifier[wrapper] ( identifier[_callback] ):
identifier[callbackList] = identifier[self] . identifier[_req_callbacks] . identifier[setdefault] ( identifier[req] ,[])
... | def register_onRsp(self, req):
"""
ζ·»ε εθ°ε€ηε½ζ°ηθ£
ι₯°ε¨
:param req: ε
·δ½ηtopicοΌε¦
:return:
"""
def wrapper(_callback):
callbackList = self._req_callbacks.setdefault(req, [])
callbackList.append(_callback)
return _callback
return wrapper |
def fade_to_rgb_uncorrected(self, fade_milliseconds, red, green, blue, led_number=0):
"""
Command blink(1) to fade to RGB color, no color correction applied.
"""
action = ord('c')
fade_time = int(fade_milliseconds / 10)
th = (fade_time & 0xff00) >> 8
tl = fade_tim... | def function[fade_to_rgb_uncorrected, parameter[self, fade_milliseconds, red, green, blue, led_number]]:
constant[
Command blink(1) to fade to RGB color, no color correction applied.
]
variable[action] assign[=] call[name[ord], parameter[constant[c]]]
variable[fade_time] assign[=... | keyword[def] identifier[fade_to_rgb_uncorrected] ( identifier[self] , identifier[fade_milliseconds] , identifier[red] , identifier[green] , identifier[blue] , identifier[led_number] = literal[int] ):
literal[string]
identifier[action] = identifier[ord] ( literal[string] )
identifier[fade_t... | def fade_to_rgb_uncorrected(self, fade_milliseconds, red, green, blue, led_number=0):
"""
Command blink(1) to fade to RGB color, no color correction applied.
"""
action = ord('c')
fade_time = int(fade_milliseconds / 10)
th = (fade_time & 65280) >> 8
tl = fade_time & 255
buf = [RE... |
def getL2Representations(self):
"""
Returns the active representation in L2.
"""
return [set(L2.getSelf()._pooler.getActiveCells()) for L2 in self.L2Regions] | def function[getL2Representations, parameter[self]]:
constant[
Returns the active representation in L2.
]
return[<ast.ListComp object at 0x7da1b085fca0>] | keyword[def] identifier[getL2Representations] ( identifier[self] ):
literal[string]
keyword[return] [ identifier[set] ( identifier[L2] . identifier[getSelf] (). identifier[_pooler] . identifier[getActiveCells] ()) keyword[for] identifier[L2] keyword[in] identifier[self] . identifier[L2Regions] ] | def getL2Representations(self):
"""
Returns the active representation in L2.
"""
return [set(L2.getSelf()._pooler.getActiveCells()) for L2 in self.L2Regions] |
def index_buffer(self, buffer, index_element_size=4):
"""
Set the index buffer for this VAO
Args:
buffer: ``moderngl.Buffer``, ``numpy.array`` or ``bytes``
Keyword Args:
index_element_size (int): Byte size of each element. 1, 2 or 4
"""
if not ty... | def function[index_buffer, parameter[self, buffer, index_element_size]]:
constant[
Set the index buffer for this VAO
Args:
buffer: ``moderngl.Buffer``, ``numpy.array`` or ``bytes``
Keyword Args:
index_element_size (int): Byte size of each element. 1, 2 or 4
... | keyword[def] identifier[index_buffer] ( identifier[self] , identifier[buffer] , identifier[index_element_size] = literal[int] ):
literal[string]
keyword[if] keyword[not] identifier[type] ( identifier[buffer] ) keyword[in] [ identifier[moderngl] . identifier[Buffer] , identifier[numpy] . identifie... | def index_buffer(self, buffer, index_element_size=4):
"""
Set the index buffer for this VAO
Args:
buffer: ``moderngl.Buffer``, ``numpy.array`` or ``bytes``
Keyword Args:
index_element_size (int): Byte size of each element. 1, 2 or 4
"""
if not type(buffe... |
def title(self, value):
"""
Setter for **self.__title** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"title", v... | def function[title, parameter[self, value]]:
constant[
Setter for **self.__title** attribute.
:param value: Attribute value.
:type value: unicode
]
if compare[name[value] is_not constant[None]] begin[:]
assert[compare[call[name[type], parameter[name[value]]] is n... | keyword[def] identifier[title] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[not] keyword[None] :
keyword[assert] identifier[type] ( identifier[value] ) keyword[is] identifier[unicode] , literal[string] . identifier[f... | def title(self, value):
"""
Setter for **self.__title** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format('title', value) # depends on [control=[... |
def reservations(self):
"""get nodes of every reservations"""
command = [SINFO, '--reservation']
output = subprocess.check_output(command, env=SINFO_ENV)
output = output.decode()
it = iter(output.splitlines())
next(it)
for line in it:
rsv = Reservation... | def function[reservations, parameter[self]]:
constant[get nodes of every reservations]
variable[command] assign[=] list[[<ast.Name object at 0x7da2041d8d00>, <ast.Constant object at 0x7da2041daa10>]]
variable[output] assign[=] call[name[subprocess].check_output, parameter[name[command]]]
... | keyword[def] identifier[reservations] ( identifier[self] ):
literal[string]
identifier[command] =[ identifier[SINFO] , literal[string] ]
identifier[output] = identifier[subprocess] . identifier[check_output] ( identifier[command] , identifier[env] = identifier[SINFO_ENV] )
identif... | def reservations(self):
"""get nodes of every reservations"""
command = [SINFO, '--reservation']
output = subprocess.check_output(command, env=SINFO_ENV)
output = output.decode()
it = iter(output.splitlines())
next(it)
for line in it:
rsv = Reservation.from_sinfo(line)
yield ... |
def seekset_ng(func):
"""Read file from start then set back to original."""
@functools.wraps(func)
def seekcur(file, *args, seekset=os.SEEK_SET, **kw):
# seek_cur = file.tell()
file.seek(seekset, os.SEEK_SET)
return_ = func(file, *args, seekset=seekset, **kw)
# file.seek(seek... | def function[seekset_ng, parameter[func]]:
constant[Read file from start then set back to original.]
def function[seekcur, parameter[file]]:
call[name[file].seek, parameter[name[seekset], name[os].SEEK_SET]]
variable[return_] assign[=] call[name[func], parameter[name[file... | keyword[def] identifier[seekset_ng] ( identifier[func] ):
literal[string]
@ identifier[functools] . identifier[wraps] ( identifier[func] )
keyword[def] identifier[seekcur] ( identifier[file] ,* identifier[args] , identifier[seekset] = identifier[os] . identifier[SEEK_SET] ,** identifier[kw] ):
... | def seekset_ng(func):
"""Read file from start then set back to original."""
@functools.wraps(func)
def seekcur(file, *args, seekset=os.SEEK_SET, **kw):
# seek_cur = file.tell()
file.seek(seekset, os.SEEK_SET)
return_ = func(file, *args, seekset=seekset, **kw)
# file.seek(see... |
def get_foreign_key_declaration_sql(self, foreign_key):
"""
Obtain DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
of a field declaration to be used in statements like CREATE TABLE.
:param foreign_key: The foreign key
:type foreign_key: ForeignKeyConstrai... | def function[get_foreign_key_declaration_sql, parameter[self, foreign_key]]:
constant[
Obtain DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
of a field declaration to be used in statements like CREATE TABLE.
:param foreign_key: The foreign key
:type fore... | keyword[def] identifier[get_foreign_key_declaration_sql] ( identifier[self] , identifier[foreign_key] ):
literal[string]
identifier[sql] = identifier[self] . identifier[get_foreign_key_base_declaration_sql] ( identifier[foreign_key] )
identifier[sql] += identifier[self] . identifier[get_ad... | def get_foreign_key_declaration_sql(self, foreign_key):
"""
Obtain DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
of a field declaration to be used in statements like CREATE TABLE.
:param foreign_key: The foreign key
:type foreign_key: ForeignKeyConstraint
... |
def exp(cls, x: 'TensorFluent') -> 'TensorFluent':
'''Returns a TensorFluent for the exp function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the exp function.
'''
return cls._unary_op(x, tf.exp, tf.float32) | def function[exp, parameter[cls, x]]:
constant[Returns a TensorFluent for the exp function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the exp function.
]
return[call[name[cls]._unary_op, parameter[name[x], name[tf].exp, name[tf].float32]]] | keyword[def] identifier[exp] ( identifier[cls] , identifier[x] : literal[string] )-> literal[string] :
literal[string]
keyword[return] identifier[cls] . identifier[_unary_op] ( identifier[x] , identifier[tf] . identifier[exp] , identifier[tf] . identifier[float32] ) | def exp(cls, x: 'TensorFluent') -> 'TensorFluent':
"""Returns a TensorFluent for the exp function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the exp function.
"""
return cls._unary_op(x, tf.exp, tf.float32) |
def addIVMInputs(imageObjectList,ivmlist):
""" Add IVM filenames provided by user to outputNames dictionary for each input imageObject.
"""
if ivmlist is None:
return
for img,ivmname in zip(imageObjectList,ivmlist):
img.updateIVMName(ivmname) | def function[addIVMInputs, parameter[imageObjectList, ivmlist]]:
constant[ Add IVM filenames provided by user to outputNames dictionary for each input imageObject.
]
if compare[name[ivmlist] is constant[None]] begin[:]
return[None]
for taget[tuple[[<ast.Name object at 0x7da1b1a7df30>... | keyword[def] identifier[addIVMInputs] ( identifier[imageObjectList] , identifier[ivmlist] ):
literal[string]
keyword[if] identifier[ivmlist] keyword[is] keyword[None] :
keyword[return]
keyword[for] identifier[img] , identifier[ivmname] keyword[in] identifier[zip] ( identifier[imageObj... | def addIVMInputs(imageObjectList, ivmlist):
""" Add IVM filenames provided by user to outputNames dictionary for each input imageObject.
"""
if ivmlist is None:
return # depends on [control=['if'], data=[]]
for (img, ivmname) in zip(imageObjectList, ivmlist):
img.updateIVMName(ivmname) ... |
async def emit(self, record: LogRecord): # type: ignore
"""
Actually log the specified logging record to the stream.
"""
if self.writer is None:
self.writer = await self._init_writer()
try:
msg = self.format(record) + self.terminator
self.wr... | <ast.AsyncFunctionDef object at 0x7da204621120> | keyword[async] keyword[def] identifier[emit] ( identifier[self] , identifier[record] : identifier[LogRecord] ):
literal[string]
keyword[if] identifier[self] . identifier[writer] keyword[is] keyword[None] :
identifier[self] . identifier[writer] = keyword[await] identifier[self] . i... | async def emit(self, record: LogRecord): # type: ignore
'\n Actually log the specified logging record to the stream.\n '
if self.writer is None:
self.writer = await self._init_writer() # depends on [control=['if'], data=[]]
try:
msg = self.format(record) + self.terminator
... |
def plot_plate_limits_field(axis, rcmb, ridges, trenches):
"""plot arrows designating ridges and trenches in 2D field plots"""
for trench in trenches:
xxd = (rcmb + 1.02) * np.cos(trench) # arrow begin
yyd = (rcmb + 1.02) * np.sin(trench) # arrow begin
xxt = (rcmb + 1.35) * np.cos(tren... | def function[plot_plate_limits_field, parameter[axis, rcmb, ridges, trenches]]:
constant[plot arrows designating ridges and trenches in 2D field plots]
for taget[name[trench]] in starred[name[trenches]] begin[:]
variable[xxd] assign[=] binary_operation[binary_operation[name[rcmb] + const... | keyword[def] identifier[plot_plate_limits_field] ( identifier[axis] , identifier[rcmb] , identifier[ridges] , identifier[trenches] ):
literal[string]
keyword[for] identifier[trench] keyword[in] identifier[trenches] :
identifier[xxd] =( identifier[rcmb] + literal[int] )* identifier[np] . identif... | def plot_plate_limits_field(axis, rcmb, ridges, trenches):
"""plot arrows designating ridges and trenches in 2D field plots"""
for trench in trenches:
xxd = (rcmb + 1.02) * np.cos(trench) # arrow begin
yyd = (rcmb + 1.02) * np.sin(trench) # arrow begin
xxt = (rcmb + 1.35) * np.cos(tren... |
def mark_failed_exc(self, e_val=None, e_ty=None):
'''Marks the tracer as failed with the given exception :code:`e_val` of
type :code:`e_ty` (defaults to the current exception).
May only be called in the started state and only if the tracer is not
already marked as failed. Note that this... | def function[mark_failed_exc, parameter[self, e_val, e_ty]]:
constant[Marks the tracer as failed with the given exception :code:`e_val` of
type :code:`e_ty` (defaults to the current exception).
May only be called in the started state and only if the tracer is not
already marked as faile... | keyword[def] identifier[mark_failed_exc] ( identifier[self] , identifier[e_val] = keyword[None] , identifier[e_ty] = keyword[None] ):
literal[string]
identifier[_error_from_exc] ( identifier[self] . identifier[nsdk] , identifier[self] . identifier[handle] , identifier[e_val] , identifier[e_ty] ) | def mark_failed_exc(self, e_val=None, e_ty=None):
"""Marks the tracer as failed with the given exception :code:`e_val` of
type :code:`e_ty` (defaults to the current exception).
May only be called in the started state and only if the tracer is not
already marked as failed. Note that this doe... |
def schema(self, schema):
"""Specifies the input schema.
Some data sources (e.g. JSON) can infer the input schema automatically from data.
By specifying the schema here, the underlying data source can skip the schema
inference step, and thus speed up data loading.
:param schema... | def function[schema, parameter[self, schema]]:
constant[Specifies the input schema.
Some data sources (e.g. JSON) can infer the input schema automatically from data.
By specifying the schema here, the underlying data source can skip the schema
inference step, and thus speed up data load... | keyword[def] identifier[schema] ( identifier[self] , identifier[schema] ):
literal[string]
keyword[from] identifier[pyspark] . identifier[sql] keyword[import] identifier[SparkSession]
identifier[spark] = identifier[SparkSession] . identifier[builder] . identifier[getOrCreate] ()
... | def schema(self, schema):
"""Specifies the input schema.
Some data sources (e.g. JSON) can infer the input schema automatically from data.
By specifying the schema here, the underlying data source can skip the schema
inference step, and thus speed up data loading.
:param schema: a ... |
def calc_tkor_v1(self):
"""Adjust the given air temperature values.
Required control parameters:
|NHRU|
|KT|
Required input sequence:
|TemL|
Calculated flux sequence:
|TKor|
Basic equation:
:math:`TKor = KT + TemL`
Example:
>>> from hydpy.models.lland ... | def function[calc_tkor_v1, parameter[self]]:
constant[Adjust the given air temperature values.
Required control parameters:
|NHRU|
|KT|
Required input sequence:
|TemL|
Calculated flux sequence:
|TKor|
Basic equation:
:math:`TKor = KT + TemL`
Example:
... | keyword[def] identifier[calc_tkor_v1] ( identifier[self] ):
literal[string]
identifier[con] = identifier[self] . identifier[parameters] . identifier[control] . identifier[fastaccess]
identifier[inp] = identifier[self] . identifier[sequences] . identifier[inputs] . identifier[fastaccess]
identif... | def calc_tkor_v1(self):
"""Adjust the given air temperature values.
Required control parameters:
|NHRU|
|KT|
Required input sequence:
|TemL|
Calculated flux sequence:
|TKor|
Basic equation:
:math:`TKor = KT + TemL`
Example:
>>> from hydpy.models.lland ... |
def hook(self, event_type='push'):
"""
Registers a function as a hook. Multiple hooks can be registered for a given type, but the
order in which they are invoke is unspecified.
:param event_type: The event type this hook will be invoked for.
"""
def decorator(func):
... | def function[hook, parameter[self, event_type]]:
constant[
Registers a function as a hook. Multiple hooks can be registered for a given type, but the
order in which they are invoke is unspecified.
:param event_type: The event type this hook will be invoked for.
]
def fun... | keyword[def] identifier[hook] ( identifier[self] , identifier[event_type] = literal[string] ):
literal[string]
keyword[def] identifier[decorator] ( identifier[func] ):
identifier[self] . identifier[_hooks] [ identifier[event_type] ]. identifier[append] ( identifier[func] )
... | def hook(self, event_type='push'):
"""
Registers a function as a hook. Multiple hooks can be registered for a given type, but the
order in which they are invoke is unspecified.
:param event_type: The event type this hook will be invoked for.
"""
def decorator(func):
sel... |
def check_accesspoints(sess):
"""
check the status of all connected access points
"""
ap_names = walk_data(sess, name_ap_oid, helper)[0]
ap_operationals = walk_data(sess, operational_ap_oid, helper)[0]
ap_availabilitys = walk_data(sess, availability_ap_oid, helper)[0]
... | def function[check_accesspoints, parameter[sess]]:
constant[
check the status of all connected access points
]
variable[ap_names] assign[=] call[call[name[walk_data], parameter[name[sess], name[name_ap_oid], name[helper]]]][constant[0]]
variable[ap_operationals] assign[=] call[call[name[... | keyword[def] identifier[check_accesspoints] ( identifier[sess] ):
literal[string]
identifier[ap_names] = identifier[walk_data] ( identifier[sess] , identifier[name_ap_oid] , identifier[helper] )[ literal[int] ]
identifier[ap_operationals] = identifier[walk_data] ( identifier[sess] , identifier[operati... | def check_accesspoints(sess):
"""
check the status of all connected access points
"""
ap_names = walk_data(sess, name_ap_oid, helper)[0]
ap_operationals = walk_data(sess, operational_ap_oid, helper)[0]
ap_availabilitys = walk_data(sess, availability_ap_oid, helper)[0]
ap_alarms = walk_data(s... |
def get_required_permissions(self, request):
""" Returns the required permissions to access the considered object. """
perms = []
if not self.permission_required:
return perms
if isinstance(self.permission_required, string_types):
perms = [self.permission_requir... | def function[get_required_permissions, parameter[self, request]]:
constant[ Returns the required permissions to access the considered object. ]
variable[perms] assign[=] list[[]]
if <ast.UnaryOp object at 0x7da20c7ca560> begin[:]
return[name[perms]]
if call[name[isinstance], para... | keyword[def] identifier[get_required_permissions] ( identifier[self] , identifier[request] ):
literal[string]
identifier[perms] =[]
keyword[if] keyword[not] identifier[self] . identifier[permission_required] :
keyword[return] identifier[perms]
keyword[if] ident... | def get_required_permissions(self, request):
""" Returns the required permissions to access the considered object. """
perms = []
if not self.permission_required:
return perms # depends on [control=['if'], data=[]]
if isinstance(self.permission_required, string_types):
perms = [self.per... |
def resample(args):
"""
%prog resample yellow-catfish-resample.txt medicago-resample.txt
Plot ALLMAPS performance across resampled real data.
"""
p = OptionParser(resample.__doc__)
opts, args, iopts = p.set_image_options(args, figsize="8x4", dpi=300)
if len(args) != 2:
sys.exit(not... | def function[resample, parameter[args]]:
constant[
%prog resample yellow-catfish-resample.txt medicago-resample.txt
Plot ALLMAPS performance across resampled real data.
]
variable[p] assign[=] call[name[OptionParser], parameter[name[resample].__doc__]]
<ast.Tuple object at 0x7da20e9... | keyword[def] identifier[resample] ( identifier[args] ):
literal[string]
identifier[p] = identifier[OptionParser] ( identifier[resample] . identifier[__doc__] )
identifier[opts] , identifier[args] , identifier[iopts] = identifier[p] . identifier[set_image_options] ( identifier[args] , identifier[figsiz... | def resample(args):
"""
%prog resample yellow-catfish-resample.txt medicago-resample.txt
Plot ALLMAPS performance across resampled real data.
"""
p = OptionParser(resample.__doc__)
(opts, args, iopts) = p.set_image_options(args, figsize='8x4', dpi=300)
if len(args) != 2:
sys.exit(no... |
def annotate_text(self, document, features, encoding_type=None, retry=None, timeout=None, metadata=None):
"""
A convenience method that provides all the features that analyzeSentiment,
analyzeEntities, and analyzeSyntax provide in one call.
:param document: Input document.
I... | def function[annotate_text, parameter[self, document, features, encoding_type, retry, timeout, metadata]]:
constant[
A convenience method that provides all the features that analyzeSentiment,
analyzeEntities, and analyzeSyntax provide in one call.
:param document: Input document.
... | keyword[def] identifier[annotate_text] ( identifier[self] , identifier[document] , identifier[features] , identifier[encoding_type] = keyword[None] , identifier[retry] = keyword[None] , identifier[timeout] = keyword[None] , identifier[metadata] = keyword[None] ):
literal[string]
identifier[client] ... | def annotate_text(self, document, features, encoding_type=None, retry=None, timeout=None, metadata=None):
"""
A convenience method that provides all the features that analyzeSentiment,
analyzeEntities, and analyzeSyntax provide in one call.
:param document: Input document.
If a ... |
def conv_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs):
"""A block of standard 2d convolutions."""
return conv_block_internal(conv, inputs, filters,
dilation_rates_and_kernel_sizes, **kwargs) | def function[conv_block, parameter[inputs, filters, dilation_rates_and_kernel_sizes]]:
constant[A block of standard 2d convolutions.]
return[call[name[conv_block_internal], parameter[name[conv], name[inputs], name[filters], name[dilation_rates_and_kernel_sizes]]]] | keyword[def] identifier[conv_block] ( identifier[inputs] , identifier[filters] , identifier[dilation_rates_and_kernel_sizes] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[conv_block_internal] ( identifier[conv] , identifier[inputs] , identifier[filters] ,
identifier[dilation_rates_an... | def conv_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs):
"""A block of standard 2d convolutions."""
return conv_block_internal(conv, inputs, filters, dilation_rates_and_kernel_sizes, **kwargs) |
def makePacket(ID, instr, reg=None, params=None):
"""
This makes a generic packet.
TODO: look a struct ... does that add value using it?
0xFF, 0xFF, 0xFD, 0x00, ID, LEN_L, LEN_H, INST, PARAM 1, PARAM 2, ..., PARAM N, CRC_L, CRC_H]
in:
ID - servo id
instr - instruction
reg - register
params - instruction ... | def function[makePacket, parameter[ID, instr, reg, params]]:
constant[
This makes a generic packet.
TODO: look a struct ... does that add value using it?
0xFF, 0xFF, 0xFD, 0x00, ID, LEN_L, LEN_H, INST, PARAM 1, PARAM 2, ..., PARAM N, CRC_L, CRC_H]
in:
ID - servo id
instr - instruction
reg - register... | keyword[def] identifier[makePacket] ( identifier[ID] , identifier[instr] , identifier[reg] = keyword[None] , identifier[params] = keyword[None] ):
literal[string]
identifier[pkt] =[]
identifier[pkt] +=[ literal[int] , literal[int] , literal[int] ]
identifier[pkt] +=[ literal[int] ]
identifier[pkt] +=[ iden... | def makePacket(ID, instr, reg=None, params=None):
"""
This makes a generic packet.
TODO: look a struct ... does that add value using it?
0xFF, 0xFF, 0xFD, 0x00, ID, LEN_L, LEN_H, INST, PARAM 1, PARAM 2, ..., PARAM N, CRC_L, CRC_H]
in:
ID - servo id
instr - instruction
reg - register
params - instructi... |
def fallbacks(enable=True):
"""
Temporarily switch all language fallbacks on or off.
Example:
with fallbacks(False):
lang_has_slug = bool(self.slug)
May be used to enable fallbacks just when they're needed saving on some
processing or check if there is a value for the current ... | def function[fallbacks, parameter[enable]]:
constant[
Temporarily switch all language fallbacks on or off.
Example:
with fallbacks(False):
lang_has_slug = bool(self.slug)
May be used to enable fallbacks just when they're needed saving on some
processing or check if there i... | keyword[def] identifier[fallbacks] ( identifier[enable] = keyword[True] ):
literal[string]
identifier[current_enable_fallbacks] = identifier[settings] . identifier[ENABLE_FALLBACKS]
identifier[settings] . identifier[ENABLE_FALLBACKS] = identifier[enable]
keyword[try] :
keyword[yield]
... | def fallbacks(enable=True):
"""
Temporarily switch all language fallbacks on or off.
Example:
with fallbacks(False):
lang_has_slug = bool(self.slug)
May be used to enable fallbacks just when they're needed saving on some
processing or check if there is a value for the current ... |
def query_api(self, q, s, g, **kwargs): # noqa: E501
"""Perform a charting query against Wavefront servers that returns the appropriate points in the specified time window and granularity # noqa: E501
Long time spans and small granularities can take a long time to calculate # noqa: E501
This... | def function[query_api, parameter[self, q, s, g]]:
constant[Perform a charting query against Wavefront servers that returns the appropriate points in the specified time window and granularity # noqa: E501
Long time spans and small granularities can take a long time to calculate # noqa: E501
T... | keyword[def] identifier[query_api] ( identifier[self] , identifier[q] , identifier[s] , identifier[g] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword... | def query_api(self, q, s, g, **kwargs): # noqa: E501
'Perform a charting query against Wavefront servers that returns the appropriate points in the specified time window and granularity # noqa: E501\n\n Long time spans and small granularities can take a long time to calculate # noqa: E501\n This me... |
def gen_outputs(self, riskinput, monitor, epspath=None, hazard=None):
"""
Group the assets per taxonomy and compute the outputs by using the
underlying riskmodels. Yield one output per realization.
:param riskinput: a RiskInput instance
:param monitor: a monitor object used to m... | def function[gen_outputs, parameter[self, riskinput, monitor, epspath, hazard]]:
constant[
Group the assets per taxonomy and compute the outputs by using the
underlying riskmodels. Yield one output per realization.
:param riskinput: a RiskInput instance
:param monitor: a monitor... | keyword[def] identifier[gen_outputs] ( identifier[self] , identifier[riskinput] , identifier[monitor] , identifier[epspath] = keyword[None] , identifier[hazard] = keyword[None] ):
literal[string]
identifier[self] . identifier[monitor] = identifier[monitor]
identifier[hazard_getter] = iden... | def gen_outputs(self, riskinput, monitor, epspath=None, hazard=None):
"""
Group the assets per taxonomy and compute the outputs by using the
underlying riskmodels. Yield one output per realization.
:param riskinput: a RiskInput instance
:param monitor: a monitor object used to measu... |
def get_key(self, key, target='in'):
"""Get the name of a key in current style.
e.g.: in javadoc style, the returned key for 'param' is '@param'
:param key: the key wanted (param, type, return, rtype,..)
:param target: the target docstring is 'in' for the input or
'out' for th... | def function[get_key, parameter[self, key, target]]:
constant[Get the name of a key in current style.
e.g.: in javadoc style, the returned key for 'param' is '@param'
:param key: the key wanted (param, type, return, rtype,..)
:param target: the target docstring is 'in' for the input or
... | keyword[def] identifier[get_key] ( identifier[self] , identifier[key] , identifier[target] = literal[string] ):
literal[string]
identifier[target] = literal[string] keyword[if] identifier[target] == literal[string] keyword[else] literal[string]
keyword[return] identifier[self] . iden... | def get_key(self, key, target='in'):
"""Get the name of a key in current style.
e.g.: in javadoc style, the returned key for 'param' is '@param'
:param key: the key wanted (param, type, return, rtype,..)
:param target: the target docstring is 'in' for the input or
'out' for the ou... |
def parse_game_event(self, event):
"""
So CSVCMsg_GameEventList is a list of all events that can happen.
A game event has an eventid which maps to a type of event that happened
"""
if event.eventid in self.event_lookup:
#Bash this into a nicer data format to work wit... | def function[parse_game_event, parameter[self, event]]:
constant[
So CSVCMsg_GameEventList is a list of all events that can happen.
A game event has an eventid which maps to a type of event that happened
]
if compare[name[event].eventid in name[self].event_lookup] begin[:]
... | keyword[def] identifier[parse_game_event] ( identifier[self] , identifier[event] ):
literal[string]
keyword[if] identifier[event] . identifier[eventid] keyword[in] identifier[self] . identifier[event_lookup] :
identifier[event_type] = identifier[self] . identifier[event_lo... | def parse_game_event(self, event):
"""
So CSVCMsg_GameEventList is a list of all events that can happen.
A game event has an eventid which maps to a type of event that happened
"""
if event.eventid in self.event_lookup:
#Bash this into a nicer data format to work with
eve... |
def create_asset(self, asset_form):
"""Creates a new ``Asset``.
arg: asset_form (osid.repository.AssetForm): the form for
this ``Asset``
return: (osid.repository.Asset) - the new ``Asset``
raise: IllegalState - ``asset_form`` already used in a create
... | def function[create_asset, parameter[self, asset_form]]:
constant[Creates a new ``Asset``.
arg: asset_form (osid.repository.AssetForm): the form for
this ``Asset``
return: (osid.repository.Asset) - the new ``Asset``
raise: IllegalState - ``asset_form`` already used i... | keyword[def] identifier[create_asset] ( identifier[self] , identifier[asset_form] ):
literal[string]
identifier[collection] = identifier[JSONClientValidated] ( literal[string] ,
identifier[collection] = literal[string] ,
identifier[runtime] = identifier[self] . i... | def create_asset(self, asset_form):
"""Creates a new ``Asset``.
arg: asset_form (osid.repository.AssetForm): the form for
this ``Asset``
return: (osid.repository.Asset) - the new ``Asset``
raise: IllegalState - ``asset_form`` already used in a create
tran... |
def check_subtype_integrity(m, super_kind, rel_id):
'''
Check the model for integrity violations across a subtype association.
'''
if isinstance(rel_id, int):
rel_id = 'R%d' % rel_id
res = 0
for inst in m.select_many(super_kind):
if not xtuml.navigate_subtype(inst, rel_id):
... | def function[check_subtype_integrity, parameter[m, super_kind, rel_id]]:
constant[
Check the model for integrity violations across a subtype association.
]
if call[name[isinstance], parameter[name[rel_id], name[int]]] begin[:]
variable[rel_id] assign[=] binary_operation[constant[... | keyword[def] identifier[check_subtype_integrity] ( identifier[m] , identifier[super_kind] , identifier[rel_id] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[rel_id] , identifier[int] ):
identifier[rel_id] = literal[string] % identifier[rel_id]
identifier[res] = literal... | def check_subtype_integrity(m, super_kind, rel_id):
"""
Check the model for integrity violations across a subtype association.
"""
if isinstance(rel_id, int):
rel_id = 'R%d' % rel_id # depends on [control=['if'], data=[]]
res = 0
for inst in m.select_many(super_kind):
if not xtu... |
def infer_x(self, y):
"""Infer probable x from input y
@param y the desired output for infered x.
@return a list of probable x
"""
OptimizedInverseModel.infer_x(self, y)
if self.fmodel.size() == 0:
return self._random_x()
x_guesses = [self._guess_x... | def function[infer_x, parameter[self, y]]:
constant[Infer probable x from input y
@param y the desired output for infered x.
@return a list of probable x
]
call[name[OptimizedInverseModel].infer_x, parameter[name[self], name[y]]]
if compare[call[name[self].fmodel.size,... | keyword[def] identifier[infer_x] ( identifier[self] , identifier[y] ):
literal[string]
identifier[OptimizedInverseModel] . identifier[infer_x] ( identifier[self] , identifier[y] )
keyword[if] identifier[self] . identifier[fmodel] . identifier[size] ()== literal[int] :
keyword... | def infer_x(self, y):
"""Infer probable x from input y
@param y the desired output for infered x.
@return a list of probable x
"""
OptimizedInverseModel.infer_x(self, y)
if self.fmodel.size() == 0:
return self._random_x() # depends on [control=['if'], data=[]]
x_guess... |
def meta_set(self, key, metafield, value):
""" Set the meta field for a key to a new value. """
self._meta.setdefault(key, {})[metafield] = value | def function[meta_set, parameter[self, key, metafield, value]]:
constant[ Set the meta field for a key to a new value. ]
call[call[name[self]._meta.setdefault, parameter[name[key], dictionary[[], []]]]][name[metafield]] assign[=] name[value] | keyword[def] identifier[meta_set] ( identifier[self] , identifier[key] , identifier[metafield] , identifier[value] ):
literal[string]
identifier[self] . identifier[_meta] . identifier[setdefault] ( identifier[key] ,{})[ identifier[metafield] ]= identifier[value] | def meta_set(self, key, metafield, value):
""" Set the meta field for a key to a new value. """
self._meta.setdefault(key, {})[metafield] = value |
def update_catalog_extent(self, current_extent):
# type: (int) -> None
'''
A method to update the extent associated with this Boot Catalog.
Parameters:
current_extent - New extent to associate with this Boot Catalog
Returns:
Nothing.
'''
if not ... | def function[update_catalog_extent, parameter[self, current_extent]]:
constant[
A method to update the extent associated with this Boot Catalog.
Parameters:
current_extent - New extent to associate with this Boot Catalog
Returns:
Nothing.
]
if <ast.Unar... | keyword[def] identifier[update_catalog_extent] ( identifier[self] , identifier[current_extent] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_initialized] :
keyword[raise] identifier[pycdlibexception] . identifier[PyCdlibInternalError] ( literal[string] ... | def update_catalog_extent(self, current_extent):
# type: (int) -> None
'\n A method to update the extent associated with this Boot Catalog.\n\n Parameters:\n current_extent - New extent to associate with this Boot Catalog\n Returns:\n Nothing.\n '
if not self._ini... |
def make_vertical_bar(percentage, width=1):
"""
Draws a vertical bar made of unicode characters.
:param value: A value between 0 and 100
:param width: How many characters wide the bar should be.
:returns: Bar as a String
"""
bar = ' _βββββ
βββ'
percentage //= 10
percentage = int(perc... | def function[make_vertical_bar, parameter[percentage, width]]:
constant[
Draws a vertical bar made of unicode characters.
:param value: A value between 0 and 100
:param width: How many characters wide the bar should be.
:returns: Bar as a String
]
variable[bar] assign[=] constant[ _... | keyword[def] identifier[make_vertical_bar] ( identifier[percentage] , identifier[width] = literal[int] ):
literal[string]
identifier[bar] = literal[string]
identifier[percentage] //= literal[int]
identifier[percentage] = identifier[int] ( identifier[percentage] )
keyword[if] identifier[pe... | def make_vertical_bar(percentage, width=1):
"""
Draws a vertical bar made of unicode characters.
:param value: A value between 0 and 100
:param width: How many characters wide the bar should be.
:returns: Bar as a String
"""
bar = ' _βββββ
βββ'
percentage //= 10
percentage = int(perc... |
def upgrade():
"""Upgrade database."""
op.create_table(
'oauthclient_remoteaccount',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('client_id', sa.String(length=255), nullable=False),
sa.Column(
'e... | def function[upgrade, parameter[]]:
constant[Upgrade database.]
call[name[op].create_table, parameter[constant[oauthclient_remoteaccount], call[name[sa].Column, parameter[constant[id], call[name[sa].Integer, parameter[]]]], call[name[sa].Column, parameter[constant[user_id], call[name[sa].Integer, parame... | keyword[def] identifier[upgrade] ():
literal[string]
identifier[op] . identifier[create_table] (
literal[string] ,
identifier[sa] . identifier[Column] ( literal[string] , identifier[sa] . identifier[Integer] (), identifier[nullable] = keyword[False] ),
identifier[sa] . identifier[Column] ( l... | def upgrade():
"""Upgrade database."""
op.create_table('oauthclient_remoteaccount', sa.Column('id', sa.Integer(), nullable=False), sa.Column('user_id', sa.Integer(), nullable=False), sa.Column('client_id', sa.String(length=255), nullable=False), sa.Column('extra_data', sqlalchemy_utils.JSONType(), nullable=Fals... |
def scons_subst_once(strSubst, env, key):
"""Perform single (non-recursive) substitution of a single
construction variable keyword.
This is used when setting a variable when copying or overriding values
in an Environment. We want to capture (expand) the old value before
we override it, so people c... | def function[scons_subst_once, parameter[strSubst, env, key]]:
constant[Perform single (non-recursive) substitution of a single
construction variable keyword.
This is used when setting a variable when copying or overriding values
in an Environment. We want to capture (expand) the old value before
... | keyword[def] identifier[scons_subst_once] ( identifier[strSubst] , identifier[env] , identifier[key] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[strSubst] , identifier[str] ) keyword[and] identifier[strSubst] . identifier[find] ( literal[string] )< literal[int] :
keyword[r... | def scons_subst_once(strSubst, env, key):
"""Perform single (non-recursive) substitution of a single
construction variable keyword.
This is used when setting a variable when copying or overriding values
in an Environment. We want to capture (expand) the old value before
we override it, so people c... |
def _get_cached_response(self):
"""Returns a file object of the cached response."""
if not self._is_cached():
response = self._download_response()
self.cache.set_xml(self._get_cache_key(), response)
return self.cache.get_xml(self._get_cache_key()) | def function[_get_cached_response, parameter[self]]:
constant[Returns a file object of the cached response.]
if <ast.UnaryOp object at 0x7da1b0b486d0> begin[:]
variable[response] assign[=] call[name[self]._download_response, parameter[]]
call[name[self].cache.set_xml, par... | keyword[def] identifier[_get_cached_response] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_is_cached] ():
identifier[response] = identifier[self] . identifier[_download_response] ()
identifier[self] . identifier[cache] . ... | def _get_cached_response(self):
"""Returns a file object of the cached response."""
if not self._is_cached():
response = self._download_response()
self.cache.set_xml(self._get_cache_key(), response) # depends on [control=['if'], data=[]]
return self.cache.get_xml(self._get_cache_key()) |
def data_and_files(self, data=True, files=True, stream=None):
"""Retrieve body data.
Returns a two-elements tuple of a
:class:`~.MultiValueDict` containing data from
the request body, and data from uploaded files.
If the body data is not ready, return a :class:`~asyncio.Future`... | def function[data_and_files, parameter[self, data, files, stream]]:
constant[Retrieve body data.
Returns a two-elements tuple of a
:class:`~.MultiValueDict` containing data from
the request body, and data from uploaded files.
If the body data is not ready, return a :class:`~asy... | keyword[def] identifier[data_and_files] ( identifier[self] , identifier[data] = keyword[True] , identifier[files] = keyword[True] , identifier[stream] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[method] keyword[in] identifier[ENCODE_URL_METHODS] :
id... | def data_and_files(self, data=True, files=True, stream=None):
"""Retrieve body data.
Returns a two-elements tuple of a
:class:`~.MultiValueDict` containing data from
the request body, and data from uploaded files.
If the body data is not ready, return a :class:`~asyncio.Future`
... |
def eval(self, x, y, z):
"""Evaluate the function in (x, y, z)."""
xc, yc, zc = self.rc
sx, sy, sz = self.s
## Method1: direct evaluation
#return exp(-(((x-xc)**2)/(2*sx**2) + ((y-yc)**2)/(2*sy**2) +\
# ((z-zc)**2)/(2*sz**2)))
## Method2: evaluation using... | def function[eval, parameter[self, x, y, z]]:
constant[Evaluate the function in (x, y, z).]
<ast.Tuple object at 0x7da18f58dff0> assign[=] name[self].rc
<ast.Tuple object at 0x7da18f58cf40> assign[=] name[self].s
def function[arg, parameter[s]]:
return[binary_operation[constant[(... | keyword[def] identifier[eval] ( identifier[self] , identifier[x] , identifier[y] , identifier[z] ):
literal[string]
identifier[xc] , identifier[yc] , identifier[zc] = identifier[self] . identifier[rc]
identifier[sx] , identifier[sy] , identifier[sz] = identifier[self] . identifier[s]
... | def eval(self, x, y, z):
"""Evaluate the function in (x, y, z)."""
(xc, yc, zc) = self.rc
(sx, sy, sz) = self.s
## Method1: direct evaluation
#return exp(-(((x-xc)**2)/(2*sx**2) + ((y-yc)**2)/(2*sy**2) +\
# ((z-zc)**2)/(2*sz**2)))
## Method2: evaluation using numexpr
def arg(s):
... |
def convert_model_to_onnx(frozen_graph_path, end_node_names, onnx_output_path):
"""Reimplementation of the TensorFlow-onnx official tutorial convert the proto buff to onnx file:
Parameters
-----------
frozen_graph_path : string
the path where your frozen graph file save.
end_node_names : st... | def function[convert_model_to_onnx, parameter[frozen_graph_path, end_node_names, onnx_output_path]]:
constant[Reimplementation of the TensorFlow-onnx official tutorial convert the proto buff to onnx file:
Parameters
-----------
frozen_graph_path : string
the path where your frozen graph fil... | keyword[def] identifier[convert_model_to_onnx] ( identifier[frozen_graph_path] , identifier[end_node_names] , identifier[onnx_output_path] ):
literal[string]
keyword[with] identifier[tf] . identifier[gfile] . identifier[GFile] ( identifier[frozen_graph_path] , literal[string] ) keyword[as] identifier[f] ... | def convert_model_to_onnx(frozen_graph_path, end_node_names, onnx_output_path):
"""Reimplementation of the TensorFlow-onnx official tutorial convert the proto buff to onnx file:
Parameters
-----------
frozen_graph_path : string
the path where your frozen graph file save.
end_node_names : st... |
def flush(self, error=False, prompt=False):
"""Flush buffer, write text to console"""
# Fix for Issue 2452
if PY3:
try:
text = "".join(self.__buffer)
except TypeError:
text = b"".join(self.__buffer)
try:
... | def function[flush, parameter[self, error, prompt]]:
constant[Flush buffer, write text to console]
if name[PY3] begin[:]
<ast.Try object at 0x7da18eb54be0>
name[self].__buffer assign[=] list[[]]
call[name[self].insert_text, parameter[name[text]]]
call[name[QCoreApplicatio... | keyword[def] identifier[flush] ( identifier[self] , identifier[error] = keyword[False] , identifier[prompt] = keyword[False] ):
literal[string]
keyword[if] identifier[PY3] :
keyword[try] :
identifier[text] = literal[string] . identifier[join] ( identifie... | def flush(self, error=False, prompt=False):
"""Flush buffer, write text to console""" # Fix for Issue 2452
if PY3:
try:
text = ''.join(self.__buffer) # depends on [control=['try'], data=[]]
except TypeError:
text = b''.join(self.__buffer)
try:
... |
def relocate_image(self, new_ImageBase):
"""Apply the relocation information to the image using the provided new image base.
This method will apply the relocation information to the image. Given the new base,
all the relocations will be processed and both the raw data and the section's ... | def function[relocate_image, parameter[self, new_ImageBase]]:
constant[Apply the relocation information to the image using the provided new image base.
This method will apply the relocation information to the image. Given the new base,
all the relocations will be processed and both the ... | keyword[def] identifier[relocate_image] ( identifier[self] , identifier[new_ImageBase] ):
literal[string]
identifier[relocation_difference] = identifier[new_ImageBase] - identifier[self] . identifier[OPTIONAL_HEADER] . identifier[ImageBase]
keyword[for] identifier[reloc] keyword[in] ... | def relocate_image(self, new_ImageBase):
"""Apply the relocation information to the image using the provided new image base.
This method will apply the relocation information to the image. Given the new base,
all the relocations will be processed and both the raw data and the section's data... |
def enable_napp(cls, mgr):
"""Install one NApp using NAppManager object."""
try:
if not mgr.is_enabled():
LOG.info(' Enabling...')
mgr.enable()
LOG.info(' Enabled.')
except (FileNotFoundError, PermissionError) as exception:
... | def function[enable_napp, parameter[cls, mgr]]:
constant[Install one NApp using NAppManager object.]
<ast.Try object at 0x7da18dc98910> | keyword[def] identifier[enable_napp] ( identifier[cls] , identifier[mgr] ):
literal[string]
keyword[try] :
keyword[if] keyword[not] identifier[mgr] . identifier[is_enabled] ():
identifier[LOG] . identifier[info] ( literal[string] )
identifier[mgr] . ... | def enable_napp(cls, mgr):
"""Install one NApp using NAppManager object."""
try:
if not mgr.is_enabled():
LOG.info(' Enabling...')
mgr.enable() # depends on [control=['if'], data=[]]
LOG.info(' Enabled.') # depends on [control=['try'], data=[]]
except (FileNot... |
def is_unsigned(*p):
""" Returns false unless all types in p are unsigned
"""
from symbols.type_ import Type
try:
for i in p:
if not i.type_.is_basic or not Type.is_unsigned(i.type_):
return False
return True
except:
pass
return False | def function[is_unsigned, parameter[]]:
constant[ Returns false unless all types in p are unsigned
]
from relative_module[symbols.type_] import module[Type]
<ast.Try object at 0x7da204567610>
return[constant[False]] | keyword[def] identifier[is_unsigned] (* identifier[p] ):
literal[string]
keyword[from] identifier[symbols] . identifier[type_] keyword[import] identifier[Type]
keyword[try] :
keyword[for] identifier[i] keyword[in] identifier[p] :
keyword[if] keyword[not] identifier[i] .... | def is_unsigned(*p):
""" Returns false unless all types in p are unsigned
"""
from symbols.type_ import Type
try:
for i in p:
if not i.type_.is_basic or not Type.is_unsigned(i.type_):
return False # depends on [control=['if'], data=[]] # depends on [control=['for'],... |
def initial_state(self, batch_size, dtype=tf.float32, trainable=False,
trainable_initializers=None, trainable_regularizers=None,
name=None):
"""Builds the default start state tensor of zeros."""
return self._core.initial_state(
batch_size, dtype=dtype, trainable=t... | def function[initial_state, parameter[self, batch_size, dtype, trainable, trainable_initializers, trainable_regularizers, name]]:
constant[Builds the default start state tensor of zeros.]
return[call[name[self]._core.initial_state, parameter[name[batch_size]]]] | keyword[def] identifier[initial_state] ( identifier[self] , identifier[batch_size] , identifier[dtype] = identifier[tf] . identifier[float32] , identifier[trainable] = keyword[False] ,
identifier[trainable_initializers] = keyword[None] , identifier[trainable_regularizers] = keyword[None] ,
identifier[name] = keywor... | def initial_state(self, batch_size, dtype=tf.float32, trainable=False, trainable_initializers=None, trainable_regularizers=None, name=None):
"""Builds the default start state tensor of zeros."""
return self._core.initial_state(batch_size, dtype=dtype, trainable=trainable, trainable_initializers=trainable_initia... |
def prepare(self, cache):
"""Prepare to run next shot."""
if cache is not None:
np.copyto(self.qubits, cache)
else:
self.qubits.fill(0.0)
self.qubits[0] = 1.0
self.cregs = [0] * self.n_qubits | def function[prepare, parameter[self, cache]]:
constant[Prepare to run next shot.]
if compare[name[cache] is_not constant[None]] begin[:]
call[name[np].copyto, parameter[name[self].qubits, name[cache]]]
name[self].cregs assign[=] binary_operation[list[[<ast.Constant object at 0x7... | keyword[def] identifier[prepare] ( identifier[self] , identifier[cache] ):
literal[string]
keyword[if] identifier[cache] keyword[is] keyword[not] keyword[None] :
identifier[np] . identifier[copyto] ( identifier[self] . identifier[qubits] , identifier[cache] )
keyword[else]... | def prepare(self, cache):
"""Prepare to run next shot."""
if cache is not None:
np.copyto(self.qubits, cache) # depends on [control=['if'], data=['cache']]
else:
self.qubits.fill(0.0)
self.qubits[0] = 1.0
self.cregs = [0] * self.n_qubits |
def application(environ, start_response):
"""WSGI interface.
"""
def send_response(status, body):
if not isinstance(body, bytes):
body = body.encode('utf-8')
start_response(status, [('Content-Type', 'text/plain'),
('Content-Length', '%d' % len(bo... | def function[application, parameter[environ, start_response]]:
constant[WSGI interface.
]
def function[send_response, parameter[status, body]]:
if <ast.UnaryOp object at 0x7da18c4cf9a0> begin[:]
variable[body] assign[=] call[name[body].encode, parameter[consta... | keyword[def] identifier[application] ( identifier[environ] , identifier[start_response] ):
literal[string]
keyword[def] identifier[send_response] ( identifier[status] , identifier[body] ):
keyword[if] keyword[not] identifier[isinstance] ( identifier[body] , identifier[bytes] ):
id... | def application(environ, start_response):
"""WSGI interface.
"""
def send_response(status, body):
if not isinstance(body, bytes):
body = body.encode('utf-8') # depends on [control=['if'], data=[]]
start_response(status, [('Content-Type', 'text/plain'), ('Content-Length', '%d' %... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.