code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def send_video_note(self, chat_id, data, duration=None, length=None, reply_to_message_id=None, reply_markup=None,
disable_notification=None, timeout=None):
"""
Use this method to send video files, Telegram clients support mp4 videos.
:param chat_id: Integer : Unique ident... | def function[send_video_note, parameter[self, chat_id, data, duration, length, reply_to_message_id, reply_markup, disable_notification, timeout]]:
constant[
Use this method to send video files, Telegram clients support mp4 videos.
:param chat_id: Integer : Unique identifier for the message recip... | keyword[def] identifier[send_video_note] ( identifier[self] , identifier[chat_id] , identifier[data] , identifier[duration] = keyword[None] , identifier[length] = keyword[None] , identifier[reply_to_message_id] = keyword[None] , identifier[reply_markup] = keyword[None] ,
identifier[disable_notification] = keyword[No... | def send_video_note(self, chat_id, data, duration=None, length=None, reply_to_message_id=None, reply_markup=None, disable_notification=None, timeout=None):
"""
Use this method to send video files, Telegram clients support mp4 videos.
:param chat_id: Integer : Unique identifier for the message recipi... |
def dsa_sign(private_key, data, hash_algorithm):
"""
Generates a DSA signature
:param private_key:
The PrivateKey to generate the signature with
:param data:
A byte string of the data the signature is for
:param hash_algorithm:
A unicode string of "md5", "sha1", "sha256", ... | def function[dsa_sign, parameter[private_key, data, hash_algorithm]]:
constant[
Generates a DSA signature
:param private_key:
The PrivateKey to generate the signature with
:param data:
A byte string of the data the signature is for
:param hash_algorithm:
A unicode stri... | keyword[def] identifier[dsa_sign] ( identifier[private_key] , identifier[data] , identifier[hash_algorithm] ):
literal[string]
keyword[if] identifier[private_key] . identifier[algorithm] != literal[string] :
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[return] identi... | def dsa_sign(private_key, data, hash_algorithm):
"""
Generates a DSA signature
:param private_key:
The PrivateKey to generate the signature with
:param data:
A byte string of the data the signature is for
:param hash_algorithm:
A unicode string of "md5", "sha1", "sha256", ... |
async def reset_all(self):
"""
Reset states in DB
"""
async with self.connection() as conn:
await r.table(self._table).delete().run(conn) | <ast.AsyncFunctionDef object at 0x7da1b184a170> | keyword[async] keyword[def] identifier[reset_all] ( identifier[self] ):
literal[string]
keyword[async] keyword[with] identifier[self] . identifier[connection] () keyword[as] identifier[conn] :
keyword[await] identifier[r] . identifier[table] ( identifier[self] . identifier[_table]... | async def reset_all(self):
"""
Reset states in DB
"""
async with self.connection() as conn:
await r.table(self._table).delete().run(conn) |
def list_service_profiles(self, retrieve_all=True, **_params):
"""Fetches a list of all Neutron service flavor profiles."""
return self.list('service_profiles', self.service_profiles_path,
retrieve_all, **_params) | def function[list_service_profiles, parameter[self, retrieve_all]]:
constant[Fetches a list of all Neutron service flavor profiles.]
return[call[name[self].list, parameter[constant[service_profiles], name[self].service_profiles_path, name[retrieve_all]]]] | keyword[def] identifier[list_service_profiles] ( identifier[self] , identifier[retrieve_all] = keyword[True] ,** identifier[_params] ):
literal[string]
keyword[return] identifier[self] . identifier[list] ( literal[string] , identifier[self] . identifier[service_profiles_path] ,
identifier... | def list_service_profiles(self, retrieve_all=True, **_params):
"""Fetches a list of all Neutron service flavor profiles."""
return self.list('service_profiles', self.service_profiles_path, retrieve_all, **_params) |
def has_gpg_key(fingerprint):
"""Checks to see if we have this gpg fingerprint"""
if len(fingerprint) > 8:
fingerprint = fingerprint[-8:]
fingerprint = fingerprint.upper()
cmd = flatten([gnupg_bin(), gnupg_home(), "--list-public-keys"])
lines = stderr_output(cmd).split('\n')
return len(... | def function[has_gpg_key, parameter[fingerprint]]:
constant[Checks to see if we have this gpg fingerprint]
if compare[call[name[len], parameter[name[fingerprint]]] greater[>] constant[8]] begin[:]
variable[fingerprint] assign[=] call[name[fingerprint]][<ast.Slice object at 0x7da1b190dde0... | keyword[def] identifier[has_gpg_key] ( identifier[fingerprint] ):
literal[string]
keyword[if] identifier[len] ( identifier[fingerprint] )> literal[int] :
identifier[fingerprint] = identifier[fingerprint] [- literal[int] :]
identifier[fingerprint] = identifier[fingerprint] . identifier[upper... | def has_gpg_key(fingerprint):
"""Checks to see if we have this gpg fingerprint"""
if len(fingerprint) > 8:
fingerprint = fingerprint[-8:] # depends on [control=['if'], data=[]]
fingerprint = fingerprint.upper()
cmd = flatten([gnupg_bin(), gnupg_home(), '--list-public-keys'])
lines = stderr_... |
def cwtmorlet(points, width):
"""complex morlet wavelet function compatible with scipy.signal.cwt
Parameters: points: int
Number of points in `vector`.
width: scalar
Width parameter of wavelet.
Equals (sample rate / fundamental frequenc... | def function[cwtmorlet, parameter[points, width]]:
constant[complex morlet wavelet function compatible with scipy.signal.cwt
Parameters: points: int
Number of points in `vector`.
width: scalar
Width parameter of wavelet.
Equals (sam... | keyword[def] identifier[cwtmorlet] ( identifier[points] , identifier[width] ):
literal[string]
identifier[omega] = literal[int]
identifier[s] = identifier[points] /( literal[int] * identifier[omega] * identifier[width] )
keyword[return] identifier[wavelets] . identifier[morlet] ( identifier[poi... | def cwtmorlet(points, width):
"""complex morlet wavelet function compatible with scipy.signal.cwt
Parameters: points: int
Number of points in `vector`.
width: scalar
Width parameter of wavelet.
Equals (sample rate / fundamental frequenc... |
def _cleanPictures(self):
"""
Delete unused images
"""
# Project have been deleted
if not os.path.exists(self.path):
return
try:
pictures = set(os.listdir(self.pictures_directory))
for drawing in self._drawings.values():
... | def function[_cleanPictures, parameter[self]]:
constant[
Delete unused images
]
if <ast.UnaryOp object at 0x7da1b17d6a40> begin[:]
return[None]
<ast.Try object at 0x7da1b17d43d0> | keyword[def] identifier[_cleanPictures] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[self] . identifier[path] ):
keyword[return]
keyword[try] :
identifier[pictures] ... | def _cleanPictures(self):
"""
Delete unused images
"""
# Project have been deleted
if not os.path.exists(self.path):
return # depends on [control=['if'], data=[]]
try:
pictures = set(os.listdir(self.pictures_directory))
for drawing in self._drawings.values():
... |
def hlog(x, b=500, r=_display_max, d=_l_mmax):
"""
Base 10 hyperlog transform.
Parameters
----------
x : num | num iterable
values to be transformed.
b : num
Parameter controling the location of the shift
from linear to log transformation.
r : num (default = 10**4)
... | def function[hlog, parameter[x, b, r, d]]:
constant[
Base 10 hyperlog transform.
Parameters
----------
x : num | num iterable
values to be transformed.
b : num
Parameter controling the location of the shift
from linear to log transformation.
r : num (default = 10... | keyword[def] identifier[hlog] ( identifier[x] , identifier[b] = literal[int] , identifier[r] = identifier[_display_max] , identifier[d] = identifier[_l_mmax] ):
literal[string]
identifier[hlog_fun] = identifier[_make_hlog_numeric] ( identifier[b] , identifier[r] , identifier[d] )
keyword[if] keyword[... | def hlog(x, b=500, r=_display_max, d=_l_mmax):
"""
Base 10 hyperlog transform.
Parameters
----------
x : num | num iterable
values to be transformed.
b : num
Parameter controling the location of the shift
from linear to log transformation.
r : num (default = 10**4)
... |
def display(self):
"""
Displays the Layer instance to the screen.
"""
if self.displayWidth == 0: return
print("=============================")
print("Layer '%s': (Kind: %s, Size: %d, Active: %d, Frozen: %d)" % (
self.name, self.kind, self.size, self.active, se... | def function[display, parameter[self]]:
constant[
Displays the Layer instance to the screen.
]
if compare[name[self].displayWidth equal[==] constant[0]] begin[:]
return[None]
call[name[print], parameter[constant[=============================]]]
call[name[print], p... | keyword[def] identifier[display] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[displayWidth] == literal[int] : keyword[return]
identifier[print] ( literal[string] )
identifier[print] ( literal[string] %(
identifier[self] . identifier[na... | def display(self):
"""
Displays the Layer instance to the screen.
"""
if self.displayWidth == 0:
return # depends on [control=['if'], data=[]]
print('=============================')
print("Layer '%s': (Kind: %s, Size: %d, Active: %d, Frozen: %d)" % (self.name, self.kind, self.si... |
def init(fname=None, format=None):
"""This is a "factory" procedure that creates a new canvas.T object.
Both parameters, <fname> and
<format>, are optional. Parameter <fname> specifies either the output
file name or a file object. Parameter <format>, if specified, defines the
file's format. Its valu... | def function[init, parameter[fname, format]]:
constant[This is a "factory" procedure that creates a new canvas.T object.
Both parameters, <fname> and
<format>, are optional. Parameter <fname> specifies either the output
file name or a file object. Parameter <format>, if specified, defines the
fi... | keyword[def] identifier[init] ( identifier[fname] = keyword[None] , identifier[format] = keyword[None] ):
literal[string]
identifier[fname] = identifier[fname] keyword[or] identifier[theme] . identifier[output_file]
identifier[format] = identifier[format] keyword[or] identifier[theme] . identifi... | def init(fname=None, format=None):
"""This is a "factory" procedure that creates a new canvas.T object.
Both parameters, <fname> and
<format>, are optional. Parameter <fname> specifies either the output
file name or a file object. Parameter <format>, if specified, defines the
file's format. Its valu... |
def main():
"""
NAME
eqarea.py
DESCRIPTION
makes equal area projections from declination/inclination data
INPUT FORMAT
takes dec/inc as first two columns in space delimited file
SYNTAX
eqarea.py [options]
OPTIONS
-f FILE, specify file on command line
... | def function[main, parameter[]]:
constant[
NAME
eqarea.py
DESCRIPTION
makes equal area projections from declination/inclination data
INPUT FORMAT
takes dec/inc as first two columns in space delimited file
SYNTAX
eqarea.py [options]
OPTIONS
-f FILE, spe... | keyword[def] identifier[main] ():
literal[string]
identifier[title] = literal[string]
identifier[files] , identifier[fmt] ={}, literal[string]
identifier[sym] ={ literal[string] :[ literal[string] , literal[string] ], literal[string] :[ literal[string] , literal[string] ]}
identifier[plot]... | def main():
"""
NAME
eqarea.py
DESCRIPTION
makes equal area projections from declination/inclination data
INPUT FORMAT
takes dec/inc as first two columns in space delimited file
SYNTAX
eqarea.py [options]
OPTIONS
-f FILE, specify file on command line
... |
def matrix_iter(matrix, version, scale=1, border=None):
"""\
Returns an iterator / generator over the provided matrix which includes
the border and the scaling factor.
If either the `scale` or `border` value is invalid, a :py:exc:`ValueError`
is raised.
:param matrix: An iterable of bytearrays... | def function[matrix_iter, parameter[matrix, version, scale, border]]:
constant[ Returns an iterator / generator over the provided matrix which includes
the border and the scaling factor.
If either the `scale` or `border` value is invalid, a :py:exc:`ValueError`
is raised.
:param matrix: An ... | keyword[def] identifier[matrix_iter] ( identifier[matrix] , identifier[version] , identifier[scale] = literal[int] , identifier[border] = keyword[None] ):
literal[string]
identifier[check_valid_border] ( identifier[border] )
identifier[scale] = identifier[int] ( identifier[scale] )
identifier[che... | def matrix_iter(matrix, version, scale=1, border=None):
""" Returns an iterator / generator over the provided matrix which includes
the border and the scaling factor.
If either the `scale` or `border` value is invalid, a :py:exc:`ValueError`
is raised.
:param matrix: An iterable of bytearrays.
... |
def check_if_vislcg_is_in_path( self, vislcg_cmd1 ):
''' Checks whether given vislcg_cmd1 is in system's PATH. Returns True, there is
a file named vislcg_cmd1 in the path, otherwise returns False;
The idea borrows from: http://stackoverflow.com/a/377028
'''
for path ... | def function[check_if_vislcg_is_in_path, parameter[self, vislcg_cmd1]]:
constant[ Checks whether given vislcg_cmd1 is in system's PATH. Returns True, there is
a file named vislcg_cmd1 in the path, otherwise returns False;
The idea borrows from: http://stackoverflow.com/a/377028
... | keyword[def] identifier[check_if_vislcg_is_in_path] ( identifier[self] , identifier[vislcg_cmd1] ):
literal[string]
keyword[for] identifier[path] keyword[in] identifier[os] . identifier[environ] [ literal[string] ]. identifier[split] ( identifier[os] . identifier[pathsep] ):
identif... | def check_if_vislcg_is_in_path(self, vislcg_cmd1):
""" Checks whether given vislcg_cmd1 is in system's PATH. Returns True, there is
a file named vislcg_cmd1 in the path, otherwise returns False;
The idea borrows from: http://stackoverflow.com/a/377028
"""
for path in os.envi... |
def get_obj(self, objpath, metahash, dst_path):
"""Get object from cache, write it to dst_path.
Args:
objpath: filename relative to buildroot
(example: mini-boot/blahblah/somefile.bin)
metahash: metahash. See targets/base.py
dst_path: Absolute path where... | def function[get_obj, parameter[self, objpath, metahash, dst_path]]:
constant[Get object from cache, write it to dst_path.
Args:
objpath: filename relative to buildroot
(example: mini-boot/blahblah/somefile.bin)
metahash: metahash. See targets/base.py
ds... | keyword[def] identifier[get_obj] ( identifier[self] , identifier[objpath] , identifier[metahash] , identifier[dst_path] ):
literal[string]
identifier[incachepath] = identifier[self] . identifier[path_in_cache] ( identifier[objpath] , identifier[metahash] )
keyword[if] keyword[not] identi... | def get_obj(self, objpath, metahash, dst_path):
"""Get object from cache, write it to dst_path.
Args:
objpath: filename relative to buildroot
(example: mini-boot/blahblah/somefile.bin)
metahash: metahash. See targets/base.py
dst_path: Absolute path where the... |
def autolink_role(typ, rawtext, etext, lineno, inliner,
options={}, content=[]):
"""Smart linking role.
Expands to ':obj:`text`' if `text` is an object that can be imported;
otherwise expands to '*text*'.
"""
env = inliner.document.settings.env
r = env.get_domain('py').role('o... | def function[autolink_role, parameter[typ, rawtext, etext, lineno, inliner, options, content]]:
constant[Smart linking role.
Expands to ':obj:`text`' if `text` is an object that can be imported;
otherwise expands to '*text*'.
]
variable[env] assign[=] name[inliner].document.settings.env
... | keyword[def] identifier[autolink_role] ( identifier[typ] , identifier[rawtext] , identifier[etext] , identifier[lineno] , identifier[inliner] ,
identifier[options] ={}, identifier[content] =[]):
literal[string]
identifier[env] = identifier[inliner] . identifier[document] . identifier[settings] . identifie... | def autolink_role(typ, rawtext, etext, lineno, inliner, options={}, content=[]):
"""Smart linking role.
Expands to ':obj:`text`' if `text` is an object that can be imported;
otherwise expands to '*text*'.
"""
env = inliner.document.settings.env
r = env.get_domain('py').role('obj')('obj', rawtex... |
def aggregate(d, y_size, x_size):
"""Average every 4 elements (2x2) in a 2D array"""
if d.ndim != 2:
# we can't guarantee what blocks we are getting and how
# it should be reshaped to do the averaging.
raise ValueError("Can't aggregrate (reduce) data arrays with "
... | def function[aggregate, parameter[d, y_size, x_size]]:
constant[Average every 4 elements (2x2) in a 2D array]
if compare[name[d].ndim not_equal[!=] constant[2]] begin[:]
<ast.Raise object at 0x7da1b22ad450>
if <ast.UnaryOp object at 0x7da1b22ad360> begin[:]
<ast.Raise object at 0... | keyword[def] identifier[aggregate] ( identifier[d] , identifier[y_size] , identifier[x_size] ):
literal[string]
keyword[if] identifier[d] . identifier[ndim] != literal[int] :
keyword[raise] identifier[ValueError] ( literal[string]
literal[string] )
... | def aggregate(d, y_size, x_size):
"""Average every 4 elements (2x2) in a 2D array"""
if d.ndim != 2:
# we can't guarantee what blocks we are getting and how
# it should be reshaped to do the averaging.
raise ValueError("Can't aggregrate (reduce) data arrays with more than 2 dimensions.")... |
async def on_raw_433(self, message):
""" Nickname in use. """
if not self.registered:
self._registration_attempts += 1
# Attempt to set new nickname.
if self._attempt_nicknames:
await self.set_nickname(self._attempt_nicknames.pop(0))
else:
... | <ast.AsyncFunctionDef object at 0x7da18f00e140> | keyword[async] keyword[def] identifier[on_raw_433] ( identifier[self] , identifier[message] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[registered] :
identifier[self] . identifier[_registration_attempts] += literal[int]
keywor... | async def on_raw_433(self, message):
""" Nickname in use. """
if not self.registered:
self._registration_attempts += 1
# Attempt to set new nickname.
if self._attempt_nicknames:
await self.set_nickname(self._attempt_nicknames.pop(0)) # depends on [control=['if'], data=[]]
... |
def BB(n):
"""constructs the BB context"""
if (n<=1):return Context('0\n1')
else:
BB1=BB(n-1)
AA1=AA(n-1)
r1 = C1((n-1)*2**(n-2),2**(n-1)) - AA1 - BB1
r2 = BB1 - C1(2**(n-1),2**(n-1)) - BB1;
return r1 + r2 | def function[BB, parameter[n]]:
constant[constructs the BB context]
if compare[name[n] less_or_equal[<=] constant[1]] begin[:]
return[call[name[Context], parameter[constant[0
1]]]] | keyword[def] identifier[BB] ( identifier[n] ):
literal[string]
keyword[if] ( identifier[n] <= literal[int] ): keyword[return] identifier[Context] ( literal[string] )
keyword[else] :
identifier[BB1] = identifier[BB] ( identifier[n] - literal[int] )
identifier[AA1] = identifier[AA] ( ... | def BB(n):
"""constructs the BB context"""
if n <= 1:
return Context('0\n1') # depends on [control=['if'], data=[]]
else:
BB1 = BB(n - 1)
AA1 = AA(n - 1)
r1 = C1((n - 1) * 2 ** (n - 2), 2 ** (n - 1)) - AA1 - BB1
r2 = BB1 - C1(2 ** (n - 1), 2 ** (n - 1)) - BB1
... |
def _do_download(version, download_base, to_dir, download_delay):
"""Download Setuptools."""
py_desig = 'py{sys.version_info[0]}.{sys.version_info[1]}'.format(sys=sys)
tp = 'setuptools-{version}-{py_desig}.egg'
egg = os.path.join(to_dir, tp.format(**locals()))
if not os.path.exists(egg):
arc... | def function[_do_download, parameter[version, download_base, to_dir, download_delay]]:
constant[Download Setuptools.]
variable[py_desig] assign[=] call[constant[py{sys.version_info[0]}.{sys.version_info[1]}].format, parameter[]]
variable[tp] assign[=] constant[setuptools-{version}-{py_desig}.egg... | keyword[def] identifier[_do_download] ( identifier[version] , identifier[download_base] , identifier[to_dir] , identifier[download_delay] ):
literal[string]
identifier[py_desig] = literal[string] . identifier[format] ( identifier[sys] = identifier[sys] )
identifier[tp] = literal[string]
identifi... | def _do_download(version, download_base, to_dir, download_delay):
"""Download Setuptools."""
py_desig = 'py{sys.version_info[0]}.{sys.version_info[1]}'.format(sys=sys)
tp = 'setuptools-{version}-{py_desig}.egg'
egg = os.path.join(to_dir, tp.format(**locals()))
if not os.path.exists(egg):
arc... |
def reorder(self, single_column=False):
"""Force a reorder of the displayed items"""
if single_column:
columns = self.sortOrder[:1]
else:
columns = self.sortOrder
for ascending,column in columns[::-1]:
# Python 2.2+ guarantees stable sort, so sort by e... | def function[reorder, parameter[self, single_column]]:
constant[Force a reorder of the displayed items]
if name[single_column] begin[:]
variable[columns] assign[=] call[name[self].sortOrder][<ast.Slice object at 0x7da1b0473280>]
for taget[tuple[[<ast.Name object at 0x7da1b04704f0... | keyword[def] identifier[reorder] ( identifier[self] , identifier[single_column] = keyword[False] ):
literal[string]
keyword[if] identifier[single_column] :
identifier[columns] = identifier[self] . identifier[sortOrder] [: literal[int] ]
keyword[else] :
identifier... | def reorder(self, single_column=False):
"""Force a reorder of the displayed items"""
if single_column:
columns = self.sortOrder[:1] # depends on [control=['if'], data=[]]
else:
columns = self.sortOrder
for (ascending, column) in columns[::-1]: # Python 2.2+ guarantees stable sort, so s... |
def _connect(cls, url, token, timeout, results, i, job_is_done_event=None):
""" Connects to the specified cls with url and token. Stores the connection
information to results[i] in a threadsafe way.
Arguments:
cls: the class which is responsible for establishing connection, basically it... | def function[_connect, parameter[cls, url, token, timeout, results, i, job_is_done_event]]:
constant[ Connects to the specified cls with url and token. Stores the connection
information to results[i] in a threadsafe way.
Arguments:
cls: the class which is responsible for establishin... | keyword[def] identifier[_connect] ( identifier[cls] , identifier[url] , identifier[token] , identifier[timeout] , identifier[results] , identifier[i] , identifier[job_is_done_event] = keyword[None] ):
literal[string]
identifier[starttime] = identifier[time] . identifier[time] ()
keyword[try] :
... | def _connect(cls, url, token, timeout, results, i, job_is_done_event=None):
""" Connects to the specified cls with url and token. Stores the connection
information to results[i] in a threadsafe way.
Arguments:
cls: the class which is responsible for establishing connection, basically it... |
def get_member_device(self, device):
"""Returns the given virtual media device object.
:param device: virtual media device to be queried
:returns virtual media device object.
"""
for vmedia_device in self.get_members():
if device in vmedia_device.media_types:
... | def function[get_member_device, parameter[self, device]]:
constant[Returns the given virtual media device object.
:param device: virtual media device to be queried
:returns virtual media device object.
]
for taget[name[vmedia_device]] in starred[call[name[self].get_members, par... | keyword[def] identifier[get_member_device] ( identifier[self] , identifier[device] ):
literal[string]
keyword[for] identifier[vmedia_device] keyword[in] identifier[self] . identifier[get_members] ():
keyword[if] identifier[device] keyword[in] identifier[vmedia_device] . identifie... | def get_member_device(self, device):
"""Returns the given virtual media device object.
:param device: virtual media device to be queried
:returns virtual media device object.
"""
for vmedia_device in self.get_members():
if device in vmedia_device.media_types:
return... |
def checkfiles(args):
"""Checks existence of files based on your criteria"""
from .query import Database
db = Database()
r = db.objects()
# go through all files, check if they are available on the filesystem
good = []
bad = []
for f in r:
if os.path.exists(f.make_path(args.directory, args.extensi... | def function[checkfiles, parameter[args]]:
constant[Checks existence of files based on your criteria]
from relative_module[query] import module[Database]
variable[db] assign[=] call[name[Database], parameter[]]
variable[r] assign[=] call[name[db].objects, parameter[]]
variable[good] ... | keyword[def] identifier[checkfiles] ( identifier[args] ):
literal[string]
keyword[from] . identifier[query] keyword[import] identifier[Database]
identifier[db] = identifier[Database] ()
identifier[r] = identifier[db] . identifier[objects] ()
identifier[good] =[]
identifier[bad] =[]
keyw... | def checkfiles(args):
"""Checks existence of files based on your criteria"""
from .query import Database
db = Database()
r = db.objects()
# go through all files, check if they are available on the filesystem
good = []
bad = []
for f in r:
if os.path.exists(f.make_path(args.direct... |
def _create_indexed_dictionary(self, group=0):
"""
Creates a dict of lists of Wells. Which way the labware is segmented
determines whether this is a dict of rows or dict of columns. If group
is 1, then it will collect wells that have the same alphabetic prefix
and therefore are c... | def function[_create_indexed_dictionary, parameter[self, group]]:
constant[
Creates a dict of lists of Wells. Which way the labware is segmented
determines whether this is a dict of rows or dict of columns. If group
is 1, then it will collect wells that have the same alphabetic prefix
... | keyword[def] identifier[_create_indexed_dictionary] ( identifier[self] , identifier[group] = literal[int] ):
literal[string]
identifier[dict_list] = identifier[defaultdict] ( identifier[list] )
keyword[for] identifier[index] , identifier[well_obj] keyword[in] identifier[zip] ( identifie... | def _create_indexed_dictionary(self, group=0):
"""
Creates a dict of lists of Wells. Which way the labware is segmented
determines whether this is a dict of rows or dict of columns. If group
is 1, then it will collect wells that have the same alphabetic prefix
and therefore are consi... |
def combinations(l):
"""Pure-Python implementation of itertools.combinations(l, 2)."""
result = []
for x in xrange(len(l) - 1):
ls = l[x + 1:]
for y in ls:
result.append((l[x], y))
return result | def function[combinations, parameter[l]]:
constant[Pure-Python implementation of itertools.combinations(l, 2).]
variable[result] assign[=] list[[]]
for taget[name[x]] in starred[call[name[xrange], parameter[binary_operation[call[name[len], parameter[name[l]]] - constant[1]]]]] begin[:]
... | keyword[def] identifier[combinations] ( identifier[l] ):
literal[string]
identifier[result] =[]
keyword[for] identifier[x] keyword[in] identifier[xrange] ( identifier[len] ( identifier[l] )- literal[int] ):
identifier[ls] = identifier[l] [ identifier[x] + literal[int] :]
keyword[f... | def combinations(l):
"""Pure-Python implementation of itertools.combinations(l, 2)."""
result = []
for x in xrange(len(l) - 1):
ls = l[x + 1:]
for y in ls:
result.append((l[x], y)) # depends on [control=['for'], data=['y']] # depends on [control=['for'], data=['x']]
return ... |
def recursive_file_count(files, item=None, checksum=False):
"""Given a filepath or list of filepaths, return the total number of files."""
if not isinstance(files, (list, set)):
files = [files]
total_files = 0
if checksum is True:
md5s = [f.get('md5') for f in item.files]
else:
... | def function[recursive_file_count, parameter[files, item, checksum]]:
constant[Given a filepath or list of filepaths, return the total number of files.]
if <ast.UnaryOp object at 0x7da18dc9a1a0> begin[:]
variable[files] assign[=] list[[<ast.Name object at 0x7da18dc9a4a0>]]
variab... | keyword[def] identifier[recursive_file_count] ( identifier[files] , identifier[item] = keyword[None] , identifier[checksum] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[files] ,( identifier[list] , identifier[set] )):
identifier[files] =[ ident... | def recursive_file_count(files, item=None, checksum=False):
"""Given a filepath or list of filepaths, return the total number of files."""
if not isinstance(files, (list, set)):
files = [files] # depends on [control=['if'], data=[]]
total_files = 0
if checksum is True:
md5s = [f.get('md... |
def states(self):
"""Returns a set containing the enabled states."""
state_list = []
for state in States:
if state.value & self._states != 0:
state_list.append(state)
if (self._flashing_states & States.FILTER) != 0:
state_list.append(States.FILTER... | def function[states, parameter[self]]:
constant[Returns a set containing the enabled states.]
variable[state_list] assign[=] list[[]]
for taget[name[state]] in starred[name[States]] begin[:]
if compare[binary_operation[name[state].value <ast.BitAnd object at 0x7da2590d6b60> name[... | keyword[def] identifier[states] ( identifier[self] ):
literal[string]
identifier[state_list] =[]
keyword[for] identifier[state] keyword[in] identifier[States] :
keyword[if] identifier[state] . identifier[value] & identifier[self] . identifier[_states] != literal[int] :
... | def states(self):
"""Returns a set containing the enabled states."""
state_list = []
for state in States:
if state.value & self._states != 0:
state_list.append(state) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['state']]
if self._flashing_states & St... |
def get_image(self, image_id, **kwargs):
"""Get details about an image.
:param int image: The ID of the image.
:param dict \\*\\*kwargs: response-level options (mask, limit, etc.)
"""
if 'mask' not in kwargs:
kwargs['mask'] = IMAGE_MASK
return self.vgbdtg.ge... | def function[get_image, parameter[self, image_id]]:
constant[Get details about an image.
:param int image: The ID of the image.
:param dict \*\*kwargs: response-level options (mask, limit, etc.)
]
if compare[constant[mask] <ast.NotIn object at 0x7da2590d7190> name[kwargs]] begin... | keyword[def] identifier[get_image] ( identifier[self] , identifier[image_id] ,** identifier[kwargs] ):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[kwargs] :
identifier[kwargs] [ literal[string] ]= identifier[IMAGE_MASK]
keyword[return]... | def get_image(self, image_id, **kwargs):
"""Get details about an image.
:param int image: The ID of the image.
:param dict \\*\\*kwargs: response-level options (mask, limit, etc.)
"""
if 'mask' not in kwargs:
kwargs['mask'] = IMAGE_MASK # depends on [control=['if'], data=['kwar... |
def init_conv_weight(layer):
'''initilize conv layer weight.
'''
n_filters = layer.filters
filter_shape = (layer.kernel_size,) * get_n_dim(layer)
weight = np.zeros((n_filters, n_filters) + filter_shape)
center = tuple(map(lambda x: int((x - 1) / 2), filter_shape))
for i in range(n_filters):... | def function[init_conv_weight, parameter[layer]]:
constant[initilize conv layer weight.
]
variable[n_filters] assign[=] name[layer].filters
variable[filter_shape] assign[=] binary_operation[tuple[[<ast.Attribute object at 0x7da2054a4be0>]] * call[name[get_n_dim], parameter[name[layer]]]]
... | keyword[def] identifier[init_conv_weight] ( identifier[layer] ):
literal[string]
identifier[n_filters] = identifier[layer] . identifier[filters]
identifier[filter_shape] =( identifier[layer] . identifier[kernel_size] ,)* identifier[get_n_dim] ( identifier[layer] )
identifier[weight] = identifier... | def init_conv_weight(layer):
"""initilize conv layer weight.
"""
n_filters = layer.filters
filter_shape = (layer.kernel_size,) * get_n_dim(layer)
weight = np.zeros((n_filters, n_filters) + filter_shape)
center = tuple(map(lambda x: int((x - 1) / 2), filter_shape))
for i in range(n_filters):
... |
def _shouldOwn(self, param):
"""
Validates that the input param belongs to this Params instance.
"""
if not (self.uid == param.parent and self.hasParam(param.name)):
raise ValueError("Param %r does not belong to %r." % (param, self)) | def function[_shouldOwn, parameter[self, param]]:
constant[
Validates that the input param belongs to this Params instance.
]
if <ast.UnaryOp object at 0x7da20e955ed0> begin[:]
<ast.Raise object at 0x7da18f812650> | keyword[def] identifier[_shouldOwn] ( identifier[self] , identifier[param] ):
literal[string]
keyword[if] keyword[not] ( identifier[self] . identifier[uid] == identifier[param] . identifier[parent] keyword[and] identifier[self] . identifier[hasParam] ( identifier[param] . identifier[name] )):
... | def _shouldOwn(self, param):
"""
Validates that the input param belongs to this Params instance.
"""
if not (self.uid == param.parent and self.hasParam(param.name)):
raise ValueError('Param %r does not belong to %r.' % (param, self)) # depends on [control=['if'], data=[]] |
def update_account(self, account_id, body, **kwargs): # noqa: E501
"""Update attributes of an existing account. # noqa: E501
An endpoint for updating an account. **Example usage:** `curl -X PUT https://api.us-east-1.mbedcloud.com/v3/accounts/{account-id} -d '{\"phone_number\": \"12345678\"}' -H 'co... | def function[update_account, parameter[self, account_id, body]]:
constant[Update attributes of an existing account. # noqa: E501
An endpoint for updating an account. **Example usage:** `curl -X PUT https://api.us-east-1.mbedcloud.com/v3/accounts/{account-id} -d '{"phone_number": "12345678"}' -H 'con... | keyword[def] identifier[update_account] ( identifier[self] , identifier[account_id] , identifier[body] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keywor... | def update_account(self, account_id, body, **kwargs): # noqa: E501
'Update attributes of an existing account. # noqa: E501\n\n An endpoint for updating an account. **Example usage:** `curl -X PUT https://api.us-east-1.mbedcloud.com/v3/accounts/{account-id} -d \'{"phone_number": "12345678"}\' -H \'content... |
def modulation_type(self, value: int):
"""
0 - "ASK", 1 - "FSK", 2 - "PSK", 3 - "APSK (QAM)"
:param value:
:return:
"""
if self.__modulation_type != value:
self.__modulation_type = value
self._qad = None
self.modulation_type_changed.e... | def function[modulation_type, parameter[self, value]]:
constant[
0 - "ASK", 1 - "FSK", 2 - "PSK", 3 - "APSK (QAM)"
:param value:
:return:
]
if compare[name[self].__modulation_type not_equal[!=] name[value]] begin[:]
name[self].__modulation_type assign[=] ... | keyword[def] identifier[modulation_type] ( identifier[self] , identifier[value] : identifier[int] ):
literal[string]
keyword[if] identifier[self] . identifier[__modulation_type] != identifier[value] :
identifier[self] . identifier[__modulation_type] = identifier[value]
i... | def modulation_type(self, value: int):
"""
0 - "ASK", 1 - "FSK", 2 - "PSK", 3 - "APSK (QAM)"
:param value:
:return:
"""
if self.__modulation_type != value:
self.__modulation_type = value
self._qad = None
self.modulation_type_changed.emit(self.__modulation... |
def get_peb(self):
"""
Returns a copy of the PEB.
To dereference pointers in it call L{Process.read_structure}.
@rtype: L{win32.PEB}
@return: PEB structure.
@raise WindowsError: An exception is raised on error.
"""
self.get_handle( win32.PROCESS_VM_READ ... | def function[get_peb, parameter[self]]:
constant[
Returns a copy of the PEB.
To dereference pointers in it call L{Process.read_structure}.
@rtype: L{win32.PEB}
@return: PEB structure.
@raise WindowsError: An exception is raised on error.
]
call[name[self... | keyword[def] identifier[get_peb] ( identifier[self] ):
literal[string]
identifier[self] . identifier[get_handle] ( identifier[win32] . identifier[PROCESS_VM_READ] |
identifier[win32] . identifier[PROCESS_QUERY_INFORMATION] )
keyword[return] identifier[self] . identifier[read_stru... | def get_peb(self):
"""
Returns a copy of the PEB.
To dereference pointers in it call L{Process.read_structure}.
@rtype: L{win32.PEB}
@return: PEB structure.
@raise WindowsError: An exception is raised on error.
"""
self.get_handle(win32.PROCESS_VM_READ | win32.P... |
def setWidth(self, typeID, width):
"""setWidth(string, double) -> None
Sets the width in m of vehicles of this type.
"""
self._connection._sendDoubleCmd(
tc.CMD_SET_VEHICLETYPE_VARIABLE, tc.VAR_WIDTH, typeID, width) | def function[setWidth, parameter[self, typeID, width]]:
constant[setWidth(string, double) -> None
Sets the width in m of vehicles of this type.
]
call[name[self]._connection._sendDoubleCmd, parameter[name[tc].CMD_SET_VEHICLETYPE_VARIABLE, name[tc].VAR_WIDTH, name[typeID], name[width]]] | keyword[def] identifier[setWidth] ( identifier[self] , identifier[typeID] , identifier[width] ):
literal[string]
identifier[self] . identifier[_connection] . identifier[_sendDoubleCmd] (
identifier[tc] . identifier[CMD_SET_VEHICLETYPE_VARIABLE] , identifier[tc] . identifier[VAR_WIDTH] , id... | def setWidth(self, typeID, width):
"""setWidth(string, double) -> None
Sets the width in m of vehicles of this type.
"""
self._connection._sendDoubleCmd(tc.CMD_SET_VEHICLETYPE_VARIABLE, tc.VAR_WIDTH, typeID, width) |
def is_running(self, submissionid, user_check=True):
""" Tells if a submission is running/in queue """
submission = self.get_submission(submissionid, user_check)
return submission["status"] == "waiting" | def function[is_running, parameter[self, submissionid, user_check]]:
constant[ Tells if a submission is running/in queue ]
variable[submission] assign[=] call[name[self].get_submission, parameter[name[submissionid], name[user_check]]]
return[compare[call[name[submission]][constant[status]] equal[==]... | keyword[def] identifier[is_running] ( identifier[self] , identifier[submissionid] , identifier[user_check] = keyword[True] ):
literal[string]
identifier[submission] = identifier[self] . identifier[get_submission] ( identifier[submissionid] , identifier[user_check] )
keyword[return] identi... | def is_running(self, submissionid, user_check=True):
""" Tells if a submission is running/in queue """
submission = self.get_submission(submissionid, user_check)
return submission['status'] == 'waiting' |
def _Vapor_Density(cls, T):
"""Auxiliary equation for the density of saturated vapor
Parameters
----------
T : float
Temperature, [K]
Returns
-------
rho : float
Saturated vapor density, [kg/m³]
References
----------
... | def function[_Vapor_Density, parameter[cls, T]]:
constant[Auxiliary equation for the density of saturated vapor
Parameters
----------
T : float
Temperature, [K]
Returns
-------
rho : float
Saturated vapor density, [kg/m³]
Referen... | keyword[def] identifier[_Vapor_Density] ( identifier[cls] , identifier[T] ):
literal[string]
identifier[eq] = identifier[cls] . identifier[_rhoG] [ literal[string] ]
identifier[Tita] = literal[int] - identifier[T] / identifier[cls] . identifier[Tc]
keyword[if] identifier[eq] == ... | def _Vapor_Density(cls, T):
"""Auxiliary equation for the density of saturated vapor
Parameters
----------
T : float
Temperature, [K]
Returns
-------
rho : float
Saturated vapor density, [kg/m³]
References
----------
... |
def _set_image(self, image, nodata=None):
"""
Set self._image.
:param image: supported: np.ma.array, np.array, TODO: PIL image
:param nodata: if provided image is array (not masked array), treat pixels with value=nodata as nodata
:return:
"""
# convert to masked ... | def function[_set_image, parameter[self, image, nodata]]:
constant[
Set self._image.
:param image: supported: np.ma.array, np.array, TODO: PIL image
:param nodata: if provided image is array (not masked array), treat pixels with value=nodata as nodata
:return:
]
... | keyword[def] identifier[_set_image] ( identifier[self] , identifier[image] , identifier[nodata] = keyword[None] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[image] , identifier[np] . identifier[ma] . identifier[core] . identifier[MaskedArray] ):
identifi... | def _set_image(self, image, nodata=None):
"""
Set self._image.
:param image: supported: np.ma.array, np.array, TODO: PIL image
:param nodata: if provided image is array (not masked array), treat pixels with value=nodata as nodata
:return:
"""
# convert to masked array:
... |
def _pfp__add_child(self, name, child, stream=None):
"""Add a child to the Union field
:name: The name of the child
:child: A :class:`.Field` instance
:returns: The resulting field
"""
res = super(Union, self)._pfp__add_child(name, child)
self._pfp__buff.seek(0, ... | def function[_pfp__add_child, parameter[self, name, child, stream]]:
constant[Add a child to the Union field
:name: The name of the child
:child: A :class:`.Field` instance
:returns: The resulting field
]
variable[res] assign[=] call[call[name[super], parameter[name[Unio... | keyword[def] identifier[_pfp__add_child] ( identifier[self] , identifier[name] , identifier[child] , identifier[stream] = keyword[None] ):
literal[string]
identifier[res] = identifier[super] ( identifier[Union] , identifier[self] ). identifier[_pfp__add_child] ( identifier[name] , identifier[child]... | def _pfp__add_child(self, name, child, stream=None):
"""Add a child to the Union field
:name: The name of the child
:child: A :class:`.Field` instance
:returns: The resulting field
"""
res = super(Union, self)._pfp__add_child(name, child)
self._pfp__buff.seek(0, 0)
child... |
def _prepare_summary_table(rows):
"""Create a new table that is a summary of the input rows.
All with the same (job-name or job-id, status) go together.
Args:
rows: the input rows, a list of dictionaries.
Returns:
A new row set of summary information.
"""
if not rows:
return []
# We either ... | def function[_prepare_summary_table, parameter[rows]]:
constant[Create a new table that is a summary of the input rows.
All with the same (job-name or job-id, status) go together.
Args:
rows: the input rows, a list of dictionaries.
Returns:
A new row set of summary information.
]
if <a... | keyword[def] identifier[_prepare_summary_table] ( identifier[rows] ):
literal[string]
keyword[if] keyword[not] identifier[rows] :
keyword[return] []
identifier[key_field] = literal[string]
keyword[if] identifier[key_field] keyword[not] keyword[in] identifier[rows] [ literal[int] ]:
... | def _prepare_summary_table(rows):
"""Create a new table that is a summary of the input rows.
All with the same (job-name or job-id, status) go together.
Args:
rows: the input rows, a list of dictionaries.
Returns:
A new row set of summary information.
"""
if not rows:
return [] # depe... |
def safe_size_check(checked_path, error_detail, max_bytes=500000000):
"""Determines if a particular path is larger than expected. Useful before any recursive remove."""
actual_size = 0
for dirpath, dirnames, filenames in os.walk(checked_path):
for f in filenames:
fp = os.path.join(dirpat... | def function[safe_size_check, parameter[checked_path, error_detail, max_bytes]]:
constant[Determines if a particular path is larger than expected. Useful before any recursive remove.]
variable[actual_size] assign[=] constant[0]
for taget[tuple[[<ast.Name object at 0x7da1b0a4f430>, <ast.Name obje... | keyword[def] identifier[safe_size_check] ( identifier[checked_path] , identifier[error_detail] , identifier[max_bytes] = literal[int] ):
literal[string]
identifier[actual_size] = literal[int]
keyword[for] identifier[dirpath] , identifier[dirnames] , identifier[filenames] keyword[in] identifier[os]... | def safe_size_check(checked_path, error_detail, max_bytes=500000000):
"""Determines if a particular path is larger than expected. Useful before any recursive remove."""
actual_size = 0
for (dirpath, dirnames, filenames) in os.walk(checked_path):
for f in filenames:
fp = os.path.join(dirp... |
def get_mors_with_properties(service_instance, object_type, property_list=None,
container_ref=None, traversal_spec=None,
local_properties=False):
'''
Returns a list containing properties and managed object references for the managed object.
service_... | def function[get_mors_with_properties, parameter[service_instance, object_type, property_list, container_ref, traversal_spec, local_properties]]:
constant[
Returns a list containing properties and managed object references for the managed object.
service_instance
The Service Instance from which... | keyword[def] identifier[get_mors_with_properties] ( identifier[service_instance] , identifier[object_type] , identifier[property_list] = keyword[None] ,
identifier[container_ref] = keyword[None] , identifier[traversal_spec] = keyword[None] ,
identifier[local_properties] = keyword[False] ):
literal[string]
... | def get_mors_with_properties(service_instance, object_type, property_list=None, container_ref=None, traversal_spec=None, local_properties=False):
"""
Returns a list containing properties and managed object references for the managed object.
service_instance
The Service Instance from which to obtain... |
def join(*vectors):
r"""
Takes an arbitrary number of aligned vectors of the same length and combines
them into a single vector (vertically).
E.g. taking two 100-sample feature vectors of once 5 and once 7 features, a 100x12
feature vector is created and returned.
The feature vectors ... | def function[join, parameter[]]:
constant[
Takes an arbitrary number of aligned vectors of the same length and combines
them into a single vector (vertically).
E.g. taking two 100-sample feature vectors of once 5 and once 7 features, a 100x12
feature vector is created and returned.
... | keyword[def] identifier[join] (* identifier[vectors] ):
literal[string]
keyword[if] identifier[len] ( identifier[vectors] )< literal[int] :
keyword[return] identifier[vectors] [ literal[int] ]
identifier[vectors] = identifier[list] ( identifier[vectors] )
keyword[for] i... | def join(*vectors):
"""
Takes an arbitrary number of aligned vectors of the same length and combines
them into a single vector (vertically).
E.g. taking two 100-sample feature vectors of once 5 and once 7 features, a 100x12
feature vector is created and returned.
The feature vectors a... |
def create_releasenotes(project_dir=os.curdir, bugtracker_url=''):
"""
Creates the release notes file, if not in a package.
Args:
project_dir(str): Path to the git repo of the project.
bugtracker_url(str): Url to the bug tracker for the issues.
Returns:
None
Raises:
... | def function[create_releasenotes, parameter[project_dir, bugtracker_url]]:
constant[
Creates the release notes file, if not in a package.
Args:
project_dir(str): Path to the git repo of the project.
bugtracker_url(str): Url to the bug tracker for the issues.
Returns:
None
... | keyword[def] identifier[create_releasenotes] ( identifier[project_dir] = identifier[os] . identifier[curdir] , identifier[bugtracker_url] = literal[string] ):
literal[string]
identifier[pkg_info_file] = identifier[os] . identifier[path] . identifier[join] ( identifier[project_dir] , literal[string] )
... | def create_releasenotes(project_dir=os.curdir, bugtracker_url=''):
"""
Creates the release notes file, if not in a package.
Args:
project_dir(str): Path to the git repo of the project.
bugtracker_url(str): Url to the bug tracker for the issues.
Returns:
None
Raises:
... |
def tryDynMod(name):
'''
Dynamically import a python module or exception.
'''
try:
return importlib.import_module(name)
except ModuleNotFoundError:
raise s_exc.NoSuchDyn(name=name) | def function[tryDynMod, parameter[name]]:
constant[
Dynamically import a python module or exception.
]
<ast.Try object at 0x7da1b23ef0d0> | keyword[def] identifier[tryDynMod] ( identifier[name] ):
literal[string]
keyword[try] :
keyword[return] identifier[importlib] . identifier[import_module] ( identifier[name] )
keyword[except] identifier[ModuleNotFoundError] :
keyword[raise] identifier[s_exc] . identifier[NoSuchDyn]... | def tryDynMod(name):
"""
Dynamically import a python module or exception.
"""
try:
return importlib.import_module(name) # depends on [control=['try'], data=[]]
except ModuleNotFoundError:
raise s_exc.NoSuchDyn(name=name) # depends on [control=['except'], data=[]] |
def analyze_entities(self, document, encoding_type=None, retry=None, timeout=None, metadata=None):
"""
Finds named entities in the text along with entity types,
salience, mentions for each entity, and other properties.
:param document: Input document.
If a dict is provided, ... | def function[analyze_entities, parameter[self, document, encoding_type, retry, timeout, metadata]]:
constant[
Finds named entities in the text along with entity types,
salience, mentions for each entity, and other properties.
:param document: Input document.
If a dict is pro... | keyword[def] identifier[analyze_entities] ( identifier[self] , identifier[document] , identifier[encoding_type] = keyword[None] , identifier[retry] = keyword[None] , identifier[timeout] = keyword[None] , identifier[metadata] = keyword[None] ):
literal[string]
identifier[client] = identifier[self] .... | def analyze_entities(self, document, encoding_type=None, retry=None, timeout=None, metadata=None):
"""
Finds named entities in the text along with entity types,
salience, mentions for each entity, and other properties.
:param document: Input document.
If a dict is provided, it m... |
def create(self, typ, data, return_response=False):
"""
Create new type
Valid arguments:
skip : number of records to skip
limit : number of records to limit request to
"""
res = self._request(typ, method='POST', data=data)
if res.status_code != 201... | def function[create, parameter[self, typ, data, return_response]]:
constant[
Create new type
Valid arguments:
skip : number of records to skip
limit : number of records to limit request to
]
variable[res] assign[=] call[name[self]._request, parameter[name[... | keyword[def] identifier[create] ( identifier[self] , identifier[typ] , identifier[data] , identifier[return_response] = keyword[False] ):
literal[string]
identifier[res] = identifier[self] . identifier[_request] ( identifier[typ] , identifier[method] = literal[string] , identifier[data] = identifie... | def create(self, typ, data, return_response=False):
"""
Create new type
Valid arguments:
skip : number of records to skip
limit : number of records to limit request to
"""
res = self._request(typ, method='POST', data=data)
if res.status_code != 201:
tr... |
def get_target(cls, path, index, chain=None):
"""
Calculate the target difficulty at a particular difficulty interval (index).
Return (bits, target) on success
"""
if chain is None:
chain = [] # Do not use mutables as default values!
max_target = 0x00000000F... | def function[get_target, parameter[cls, path, index, chain]]:
constant[
Calculate the target difficulty at a particular difficulty interval (index).
Return (bits, target) on success
]
if compare[name[chain] is constant[None]] begin[:]
variable[chain] assign[=] lis... | keyword[def] identifier[get_target] ( identifier[cls] , identifier[path] , identifier[index] , identifier[chain] = keyword[None] ):
literal[string]
keyword[if] identifier[chain] keyword[is] keyword[None] :
identifier[chain] =[]
identifier[max_target] = literal[int]
... | def get_target(cls, path, index, chain=None):
"""
Calculate the target difficulty at a particular difficulty interval (index).
Return (bits, target) on success
"""
if chain is None:
chain = [] # Do not use mutables as default values! # depends on [control=['if'], data=['chain']... |
def segment(self, tokens):
"""
Segments a sequence of tokens into a sequence of segments.
:Parameters:
tokens : `list` ( :class:`~deltas.Token` )
"""
look_ahead = LookAhead(tokens)
segments = Segment()
while not look_ahead.empty():
if l... | def function[segment, parameter[self, tokens]]:
constant[
Segments a sequence of tokens into a sequence of segments.
:Parameters:
tokens : `list` ( :class:`~deltas.Token` )
]
variable[look_ahead] assign[=] call[name[LookAhead], parameter[name[tokens]]]
variab... | keyword[def] identifier[segment] ( identifier[self] , identifier[tokens] ):
literal[string]
identifier[look_ahead] = identifier[LookAhead] ( identifier[tokens] )
identifier[segments] = identifier[Segment] ()
keyword[while] keyword[not] identifier[look_ahead] . identifier[empty... | def segment(self, tokens):
"""
Segments a sequence of tokens into a sequence of segments.
:Parameters:
tokens : `list` ( :class:`~deltas.Token` )
"""
look_ahead = LookAhead(tokens)
segments = Segment()
while not look_ahead.empty():
if look_ahead.peek().type n... |
def command_max_run_time(self, event=None):
""" CPU burst max running time - self.runtime_cfg.max_run_time """
try:
max_run_time = self.max_run_time_var.get()
except ValueError:
max_run_time = self.runtime_cfg.max_run_time
self.runtime_cfg.max_run_time = max_run_... | def function[command_max_run_time, parameter[self, event]]:
constant[ CPU burst max running time - self.runtime_cfg.max_run_time ]
<ast.Try object at 0x7da1b054bfa0>
name[self].runtime_cfg.max_run_time assign[=] name[max_run_time]
call[name[self].max_run_time_var.set, parameter[name[self].ru... | keyword[def] identifier[command_max_run_time] ( identifier[self] , identifier[event] = keyword[None] ):
literal[string]
keyword[try] :
identifier[max_run_time] = identifier[self] . identifier[max_run_time_var] . identifier[get] ()
keyword[except] identifier[ValueError] :
... | def command_max_run_time(self, event=None):
""" CPU burst max running time - self.runtime_cfg.max_run_time """
try:
max_run_time = self.max_run_time_var.get() # depends on [control=['try'], data=[]]
except ValueError:
max_run_time = self.runtime_cfg.max_run_time # depends on [control=['exc... |
def connect_external_kernel(self, shellwidget):
"""
Connect an external kernel to the Variable Explorer and Help, if
it is a Spyder kernel.
"""
sw = shellwidget
kc = shellwidget.kernel_client
if self.main.help is not None:
self.main.help.set_sh... | def function[connect_external_kernel, parameter[self, shellwidget]]:
constant[
Connect an external kernel to the Variable Explorer and Help, if
it is a Spyder kernel.
]
variable[sw] assign[=] name[shellwidget]
variable[kc] assign[=] name[shellwidget].kernel_client
... | keyword[def] identifier[connect_external_kernel] ( identifier[self] , identifier[shellwidget] ):
literal[string]
identifier[sw] = identifier[shellwidget]
identifier[kc] = identifier[shellwidget] . identifier[kernel_client]
keyword[if] identifier[self] . identifier[main] . i... | def connect_external_kernel(self, shellwidget):
"""
Connect an external kernel to the Variable Explorer and Help, if
it is a Spyder kernel.
"""
sw = shellwidget
kc = shellwidget.kernel_client
if self.main.help is not None:
self.main.help.set_shell(sw) # depends on [contr... |
def is_unwrapped(f):
"""If `f` was imported and then unwrapped, this function might return True.
.. |is_unwrapped| replace:: :py:func:`is_unwrapped`"""
try:
g = look_up(object_name(f))
return g != f and unwrap(g) == f
except (AttributeError, TypeError, ImportError):
return Fals... | def function[is_unwrapped, parameter[f]]:
constant[If `f` was imported and then unwrapped, this function might return True.
.. |is_unwrapped| replace:: :py:func:`is_unwrapped`]
<ast.Try object at 0x7da20c991420> | keyword[def] identifier[is_unwrapped] ( identifier[f] ):
literal[string]
keyword[try] :
identifier[g] = identifier[look_up] ( identifier[object_name] ( identifier[f] ))
keyword[return] identifier[g] != identifier[f] keyword[and] identifier[unwrap] ( identifier[g] )== identifier[f]
... | def is_unwrapped(f):
"""If `f` was imported and then unwrapped, this function might return True.
.. |is_unwrapped| replace:: :py:func:`is_unwrapped`"""
try:
g = look_up(object_name(f))
return g != f and unwrap(g) == f # depends on [control=['try'], data=[]]
except (AttributeError, Type... |
def rolling(self, *args, **kwargs):
"""
Return a rolling grouper, providing rolling functionality per group.
"""
from pandas.core.window import RollingGroupby
return RollingGroupby(self, *args, **kwargs) | def function[rolling, parameter[self]]:
constant[
Return a rolling grouper, providing rolling functionality per group.
]
from relative_module[pandas.core.window] import module[RollingGroupby]
return[call[name[RollingGroupby], parameter[name[self], <ast.Starred object at 0x7da1b26af970>]]... | keyword[def] identifier[rolling] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[from] identifier[pandas] . identifier[core] . identifier[window] keyword[import] identifier[RollingGroupby]
keyword[return] identifier[RollingGroupby] ( identifier... | def rolling(self, *args, **kwargs):
"""
Return a rolling grouper, providing rolling functionality per group.
"""
from pandas.core.window import RollingGroupby
return RollingGroupby(self, *args, **kwargs) |
def flag(self, diagnostic, thresh=None):
'''
Returns indices of diagnostic that satisfy (return True from) the
threshold predicate. Will use class-level default threshold if
None provided.
Args:
diagnostic (str): name of the diagnostic
thresh (func): thre... | def function[flag, parameter[self, diagnostic, thresh]]:
constant[
Returns indices of diagnostic that satisfy (return True from) the
threshold predicate. Will use class-level default threshold if
None provided.
Args:
diagnostic (str): name of the diagnostic
... | keyword[def] identifier[flag] ( identifier[self] , identifier[diagnostic] , identifier[thresh] = keyword[None] ):
literal[string]
keyword[if] identifier[thresh] keyword[is] keyword[None] :
identifier[thresh] = identifier[self] . identifier[defaults] [ identifier[diagnostic] ]
... | def flag(self, diagnostic, thresh=None):
"""
Returns indices of diagnostic that satisfy (return True from) the
threshold predicate. Will use class-level default threshold if
None provided.
Args:
diagnostic (str): name of the diagnostic
thresh (func): threshol... |
def to_cldf(self, dest, mdname='cldf-metadata.json'):
"""
Write the data from the db to a CLDF dataset according to the metadata in `self.dataset`.
:param dest:
:param mdname:
:return: path of the metadata file
"""
dest = Path(dest)
if not dest.exists():
... | def function[to_cldf, parameter[self, dest, mdname]]:
constant[
Write the data from the db to a CLDF dataset according to the metadata in `self.dataset`.
:param dest:
:param mdname:
:return: path of the metadata file
]
variable[dest] assign[=] call[name[Path], pa... | keyword[def] identifier[to_cldf] ( identifier[self] , identifier[dest] , identifier[mdname] = literal[string] ):
literal[string]
identifier[dest] = identifier[Path] ( identifier[dest] )
keyword[if] keyword[not] identifier[dest] . identifier[exists] ():
identifier[dest] . ide... | def to_cldf(self, dest, mdname='cldf-metadata.json'):
"""
Write the data from the db to a CLDF dataset according to the metadata in `self.dataset`.
:param dest:
:param mdname:
:return: path of the metadata file
"""
dest = Path(dest)
if not dest.exists():
dest... |
def execute_replay() -> None:
"""
Execute all commands.
For every command that is found in replay/toDo, execute each of them
and move the file to the replay/archive directory.
"""
files = glob.glob('./replay/toDo/*')
sorted_files = sorted(files, key=os.path.getctime)
if not sorted_file... | def function[execute_replay, parameter[]]:
constant[
Execute all commands.
For every command that is found in replay/toDo, execute each of them
and move the file to the replay/archive directory.
]
variable[files] assign[=] call[name[glob].glob, parameter[constant[./replay/toDo/*]]]
... | keyword[def] identifier[execute_replay] ()-> keyword[None] :
literal[string]
identifier[files] = identifier[glob] . identifier[glob] ( literal[string] )
identifier[sorted_files] = identifier[sorted] ( identifier[files] , identifier[key] = identifier[os] . identifier[path] . identifier[getctime] )
... | def execute_replay() -> None:
"""
Execute all commands.
For every command that is found in replay/toDo, execute each of them
and move the file to the replay/archive directory.
"""
files = glob.glob('./replay/toDo/*')
sorted_files = sorted(files, key=os.path.getctime)
if not sorted_files... |
def remove(self, name):
"""Remove an enum member by name"""
member = self[name]
serial = member.serial
value = member.value
bmask = member.bmask
success = idaapi.del_enum_member(self._eid, value, serial, bmask)
if not success:
raise exceptions.CantDel... | def function[remove, parameter[self, name]]:
constant[Remove an enum member by name]
variable[member] assign[=] call[name[self]][name[name]]
variable[serial] assign[=] name[member].serial
variable[value] assign[=] name[member].value
variable[bmask] assign[=] name[member].bmask
... | keyword[def] identifier[remove] ( identifier[self] , identifier[name] ):
literal[string]
identifier[member] = identifier[self] [ identifier[name] ]
identifier[serial] = identifier[member] . identifier[serial]
identifier[value] = identifier[member] . identifier[value]
id... | def remove(self, name):
"""Remove an enum member by name"""
member = self[name]
serial = member.serial
value = member.value
bmask = member.bmask
success = idaapi.del_enum_member(self._eid, value, serial, bmask)
if not success:
raise exceptions.CantDeleteEnumMember("Can't delete enum ... |
def cut(list_, index=0):
"""Cut a list by index or arg"""
if isinstance(index, int):
cut_ = lambda x: x[index]
else:
cut_ = lambda x: getattr(x, index)
return list(map(cut_, list_)) | def function[cut, parameter[list_, index]]:
constant[Cut a list by index or arg]
if call[name[isinstance], parameter[name[index], name[int]]] begin[:]
variable[cut_] assign[=] <ast.Lambda object at 0x7da20c993a90>
return[call[name[list], parameter[call[name[map], parameter[name[cut_]... | keyword[def] identifier[cut] ( identifier[list_] , identifier[index] = literal[int] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[index] , identifier[int] ):
identifier[cut_] = keyword[lambda] identifier[x] : identifier[x] [ identifier[index] ]
keyword[else] :
... | def cut(list_, index=0):
"""Cut a list by index or arg"""
if isinstance(index, int):
cut_ = lambda x: x[index] # depends on [control=['if'], data=[]]
else:
cut_ = lambda x: getattr(x, index)
return list(map(cut_, list_)) |
def NewWalker(self, reader):
"""Setup an xmltextReader to parse a preparsed XML document.
This reuses the existing @reader xmlTextReader. """
if reader is None: reader__o = None
else: reader__o = reader._o
ret = libxml2mod.xmlReaderNewWalker(reader__o, self._o)
return ... | def function[NewWalker, parameter[self, reader]]:
constant[Setup an xmltextReader to parse a preparsed XML document.
This reuses the existing @reader xmlTextReader. ]
if compare[name[reader] is constant[None]] begin[:]
variable[reader__o] assign[=] constant[None]
varia... | keyword[def] identifier[NewWalker] ( identifier[self] , identifier[reader] ):
literal[string]
keyword[if] identifier[reader] keyword[is] keyword[None] : identifier[reader__o] = keyword[None]
keyword[else] : identifier[reader__o] = identifier[reader] . identifier[_o]
identifie... | def NewWalker(self, reader):
"""Setup an xmltextReader to parse a preparsed XML document.
This reuses the existing @reader xmlTextReader. """
if reader is None:
reader__o = None # depends on [control=['if'], data=[]]
else:
reader__o = reader._o
ret = libxml2mod.xmlReaderNewWa... |
def clear(self):
"""Clear task output: remove value ``budget_inflation_adjusted`` from all :class:`Movie` objects.
"""
self.mark_incomplete()
session = client.get_client().create_session()
movies = session.query(models.Movie)
movies.update({'budget_inflation_adjusted': N... | def function[clear, parameter[self]]:
constant[Clear task output: remove value ``budget_inflation_adjusted`` from all :class:`Movie` objects.
]
call[name[self].mark_incomplete, parameter[]]
variable[session] assign[=] call[call[name[client].get_client, parameter[]].create_session, parame... | keyword[def] identifier[clear] ( identifier[self] ):
literal[string]
identifier[self] . identifier[mark_incomplete] ()
identifier[session] = identifier[client] . identifier[get_client] (). identifier[create_session] ()
identifier[movies] = identifier[session] . identifier[query] ... | def clear(self):
"""Clear task output: remove value ``budget_inflation_adjusted`` from all :class:`Movie` objects.
"""
self.mark_incomplete()
session = client.get_client().create_session()
movies = session.query(models.Movie)
movies.update({'budget_inflation_adjusted': None})
session.com... |
def cmd_command_int(self, args):
'''execute supplied command_int'''
if len(args) != 11:
print("num args{0}".format(len(args)))
print("Usage: command_int frame command current autocontinue param1 param2 param3 param4 x y z")
print("e.g. command_int GLOBAL_RELATIVE_ALT ... | def function[cmd_command_int, parameter[self, args]]:
constant[execute supplied command_int]
if compare[call[name[len], parameter[name[args]]] not_equal[!=] constant[11]] begin[:]
call[name[print], parameter[call[constant[num args{0}].format, parameter[call[name[len], parameter[name[args... | keyword[def] identifier[cmd_command_int] ( identifier[self] , identifier[args] ):
literal[string]
keyword[if] identifier[len] ( identifier[args] )!= literal[int] :
identifier[print] ( literal[string] . identifier[format] ( identifier[len] ( identifier[args] )))
identifier... | def cmd_command_int(self, args):
"""execute supplied command_int"""
if len(args) != 11:
print('num args{0}'.format(len(args)))
print('Usage: command_int frame command current autocontinue param1 param2 param3 param4 x y z')
print('e.g. command_int GLOBAL_RELATIVE_ALT DO_SET_HOME 0 0 0 0 ... |
def parse_elem(element):
"""Parse a OSM node XML element.
Args:
element (etree.Element): XML Element to parse
Returns:
Node: Object representing parsed element
"""
ident = int(element.get('id'))
latitude = element.get('lat')
longitude = e... | def function[parse_elem, parameter[element]]:
constant[Parse a OSM node XML element.
Args:
element (etree.Element): XML Element to parse
Returns:
Node: Object representing parsed element
]
variable[ident] assign[=] call[name[int], parameter[call[name[ele... | keyword[def] identifier[parse_elem] ( identifier[element] ):
literal[string]
identifier[ident] = identifier[int] ( identifier[element] . identifier[get] ( literal[string] ))
identifier[latitude] = identifier[element] . identifier[get] ( literal[string] )
identifier[longitude] = id... | def parse_elem(element):
"""Parse a OSM node XML element.
Args:
element (etree.Element): XML Element to parse
Returns:
Node: Object representing parsed element
"""
ident = int(element.get('id'))
latitude = element.get('lat')
longitude = element.get('lon'... |
def create_network(self):
"""Get an instance of vlan services facade."""
return Network(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | def function[create_network, parameter[self]]:
constant[Get an instance of vlan services facade.]
return[call[name[Network], parameter[name[self].networkapi_url, name[self].user, name[self].password, name[self].user_ldap]]] | keyword[def] identifier[create_network] ( identifier[self] ):
literal[string]
keyword[return] identifier[Network] (
identifier[self] . identifier[networkapi_url] ,
identifier[self] . identifier[user] ,
identifier[self] . identifier[password] ,
identifier[self] .... | def create_network(self):
"""Get an instance of vlan services facade."""
return Network(self.networkapi_url, self.user, self.password, self.user_ldap) |
def _get_systemd_services(root):
'''
Use os.listdir() to get all the unit files
'''
ret = set()
for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,):
# Make sure user has access to the path, and if the path is a
# link it's likely that another entry in SYSTEM_CONFIG_PATHS
#... | def function[_get_systemd_services, parameter[root]]:
constant[
Use os.listdir() to get all the unit files
]
variable[ret] assign[=] call[name[set], parameter[]]
for taget[name[path]] in starred[binary_operation[name[SYSTEM_CONFIG_PATHS] + tuple[[<ast.Name object at 0x7da20c76dd20>]]]] b... | keyword[def] identifier[_get_systemd_services] ( identifier[root] ):
literal[string]
identifier[ret] = identifier[set] ()
keyword[for] identifier[path] keyword[in] identifier[SYSTEM_CONFIG_PATHS] +( identifier[LOCAL_CONFIG_PATH] ,):
identifier[path] = identifier[_root] ( ide... | def _get_systemd_services(root):
"""
Use os.listdir() to get all the unit files
"""
ret = set()
for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,):
# Make sure user has access to the path, and if the path is a
# link it's likely that another entry in SYSTEM_CONFIG_PATHS
#... |
def get_jwt_claims(self, auth_token):
"""Decodes the auth_token into JWT claims represented as a JSON object.
This method first tries to look up the cache and returns the result
immediately in case of a cache hit. When cache misses, the method tries to
decode the given auth token, verif... | def function[get_jwt_claims, parameter[self, auth_token]]:
constant[Decodes the auth_token into JWT claims represented as a JSON object.
This method first tries to look up the cache and returns the result
immediately in case of a cache hit. When cache misses, the method tries to
decode ... | keyword[def] identifier[get_jwt_claims] ( identifier[self] , identifier[auth_token] ):
literal[string]
keyword[def] identifier[_decode_and_verify] ():
identifier[jwt_claims] = identifier[jwt] . identifier[JWT] (). identifier[unpack] ( identifier[auth_token] ). identifier[payload] ()
... | def get_jwt_claims(self, auth_token):
"""Decodes the auth_token into JWT claims represented as a JSON object.
This method first tries to look up the cache and returns the result
immediately in case of a cache hit. When cache misses, the method tries to
decode the given auth token, verify it... |
def p_export(self, p):
'''export : IDENTIFIER LPAREN opt_param_types RPAREN
| IDENTIFIER
| EXPORT LPAREN opt_param_types RPAREN
| ORDER LPAREN opt_param_types RPAREN'''
# unlikely case: the IDENTIFIER is an otherwise reserved name
if len(p) >... | def function[p_export, parameter[self, p]]:
constant[export : IDENTIFIER LPAREN opt_param_types RPAREN
| IDENTIFIER
| EXPORT LPAREN opt_param_types RPAREN
| ORDER LPAREN opt_param_types RPAREN]
if compare[call[name[len], parameter[name[p]]] greater[>... | keyword[def] identifier[p_export] ( identifier[self] , identifier[p] ):
literal[string]
keyword[if] identifier[len] ( identifier[p] )> literal[int] :
identifier[sigs] = identifier[p] [ literal[int] ] keyword[or] ((),)
keyword[else] :
identifier[sigs] =()... | def p_export(self, p):
"""export : IDENTIFIER LPAREN opt_param_types RPAREN
| IDENTIFIER
| EXPORT LPAREN opt_param_types RPAREN
| ORDER LPAREN opt_param_types RPAREN"""
# unlikely case: the IDENTIFIER is an otherwise reserved name
if len(p) > 2:
... |
def from_headers(self, headers):
"""Generate a SpanContext object using the trace context header.
:type headers: dict
:param headers: HTTP request headers.
:rtype: :class:`~opencensus.trace.span_context.SpanContext`
:returns: SpanContext generated from the trace context header.... | def function[from_headers, parameter[self, headers]]:
constant[Generate a SpanContext object using the trace context header.
:type headers: dict
:param headers: HTTP request headers.
:rtype: :class:`~opencensus.trace.span_context.SpanContext`
:returns: SpanContext generated fro... | keyword[def] identifier[from_headers] ( identifier[self] , identifier[headers] ):
literal[string]
keyword[if] identifier[headers] keyword[is] keyword[None] :
keyword[return] identifier[SpanContext] ()
identifier[header] = identifier[headers] . identifier[get] ( identifier[... | def from_headers(self, headers):
"""Generate a SpanContext object using the trace context header.
:type headers: dict
:param headers: HTTP request headers.
:rtype: :class:`~opencensus.trace.span_context.SpanContext`
:returns: SpanContext generated from the trace context header.
... |
def close_files(subseqs):
"""Close file statements."""
print(' . close_files')
lines = Lines()
lines.add(1, 'cpdef inline close_files(self):')
for seq in subseqs:
lines.add(2, 'if self._%s_diskflag:' % seq.name)
lines.add(3, 'fclose(self._%s_fil... | def function[close_files, parameter[subseqs]]:
constant[Close file statements.]
call[name[print], parameter[constant[ . close_files]]]
variable[lines] assign[=] call[name[Lines], parameter[]]
call[name[lines].add, parameter[constant[1], constant[cpdef inline close_files(self):... | keyword[def] identifier[close_files] ( identifier[subseqs] ):
literal[string]
identifier[print] ( literal[string] )
identifier[lines] = identifier[Lines] ()
identifier[lines] . identifier[add] ( literal[int] , literal[string] )
keyword[for] identifier[seq] keyword[in] ... | def close_files(subseqs):
"""Close file statements."""
print(' . close_files')
lines = Lines()
lines.add(1, 'cpdef inline close_files(self):')
for seq in subseqs:
lines.add(2, 'if self._%s_diskflag:' % seq.name)
lines.add(3, 'fclose(self._%s_file)' % seq.name) # depends o... |
def save_grid_data(self):
"""
Save grid data in the data object
"""
if not self.grid.changes:
print('-I- No changes to save')
return
if self.grid_type == 'age':
age_data_type = self.er_magic.age_type
self.er_magic.write_ages = True... | def function[save_grid_data, parameter[self]]:
constant[
Save grid data in the data object
]
if <ast.UnaryOp object at 0x7da1b26afb20> begin[:]
call[name[print], parameter[constant[-I- No changes to save]]]
return[None]
if compare[name[self].grid_type equa... | keyword[def] identifier[save_grid_data] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[grid] . identifier[changes] :
identifier[print] ( literal[string] )
keyword[return]
keyword[if] identifier[self] . identifier[... | def save_grid_data(self):
"""
Save grid data in the data object
"""
if not self.grid.changes:
print('-I- No changes to save')
return # depends on [control=['if'], data=[]]
if self.grid_type == 'age':
age_data_type = self.er_magic.age_type
self.er_magic.write_... |
def mapiv2(ol,map_func,*args,**kwargs):
'''
from elist.elist import *
ol = ['a','b','c','d']
#1
def map_func(index,value,*others):
return(value * index + others[0] +others[-1])
mapiv(ol,map_func,'tailA-','tailB')
#2
mapiv2(ol,lambda index,value,oth... | def function[mapiv2, parameter[ol, map_func]]:
constant[
from elist.elist import *
ol = ['a','b','c','d']
#1
def map_func(index,value,*others):
return(value * index + others[0] +others[-1])
mapiv(ol,map_func,'tailA-','tailB')
#2
mapiv2(ol,lambd... | keyword[def] identifier[mapiv2] ( identifier[ol] , identifier[map_func] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[args] = identifier[list] ( identifier[args] )
keyword[if] ( identifier[args] . identifier[__len__] ()> literal[int] ):
identifier[map_func_args] = i... | def mapiv2(ol, map_func, *args, **kwargs):
"""
from elist.elist import *
ol = ['a','b','c','d']
#1
def map_func(index,value,*others):
return(value * index + others[0] +others[-1])
mapiv(ol,map_func,'tailA-','tailB')
#2
mapiv2(ol,lambda index,value,... |
def extend(cls, name):
"""
派生一个新的 leancloud.Object 子类
:param name: 子类名称
:type name: string_types
:return: 派生的子类
:rtype: ObjectMeta
"""
if six.PY2 and isinstance(name, six.text_type):
# In python2, class name must be a python2 str.
... | def function[extend, parameter[cls, name]]:
constant[
派生一个新的 leancloud.Object 子类
:param name: 子类名称
:type name: string_types
:return: 派生的子类
:rtype: ObjectMeta
]
if <ast.BoolOp object at 0x7da1b0c89480> begin[:]
variable[name] assign[=] call... | keyword[def] identifier[extend] ( identifier[cls] , identifier[name] ):
literal[string]
keyword[if] identifier[six] . identifier[PY2] keyword[and] identifier[isinstance] ( identifier[name] , identifier[six] . identifier[text_type] ):
identifier[name] = identifier[name] . id... | def extend(cls, name):
"""
派生一个新的 leancloud.Object 子类
:param name: 子类名称
:type name: string_types
:return: 派生的子类
:rtype: ObjectMeta
"""
if six.PY2 and isinstance(name, six.text_type):
# In python2, class name must be a python2 str.
name = name.enco... |
def restore_region(self, region, bbox=None, xy=None):
"""
Restore the saved region. If bbox (instance of BboxBase, or
its extents) is given, only the region specified by the bbox
will be restored. *xy* (a tuple of two floasts) optionally
specifies the new position (the LLC of the... | def function[restore_region, parameter[self, region, bbox, xy]]:
constant[
Restore the saved region. If bbox (instance of BboxBase, or
its extents) is given, only the region specified by the bbox
will be restored. *xy* (a tuple of two floasts) optionally
specifies the new positio... | keyword[def] identifier[restore_region] ( identifier[self] , identifier[region] , identifier[bbox] = keyword[None] , identifier[xy] = keyword[None] ):
literal[string]
keyword[if] identifier[bbox] keyword[is] keyword[not] keyword[None] keyword[or] identifier[xy] keyword[is] keyword[not] key... | def restore_region(self, region, bbox=None, xy=None):
"""
Restore the saved region. If bbox (instance of BboxBase, or
its extents) is given, only the region specified by the bbox
will be restored. *xy* (a tuple of two floasts) optionally
specifies the new position (the LLC of the ori... |
def load_overrides(introspection_module):
"""Loads overrides for an introspection module.
Either returns the same module again in case there are no overrides or a
proxy module including overrides. Doesn't cache the result.
"""
namespace = introspection_module.__name__.rsplit(".", 1)[-1]
module... | def function[load_overrides, parameter[introspection_module]]:
constant[Loads overrides for an introspection module.
Either returns the same module again in case there are no overrides or a
proxy module including overrides. Doesn't cache the result.
]
variable[namespace] assign[=] call[call... | keyword[def] identifier[load_overrides] ( identifier[introspection_module] ):
literal[string]
identifier[namespace] = identifier[introspection_module] . identifier[__name__] . identifier[rsplit] ( literal[string] , literal[int] )[- literal[int] ]
identifier[module_keys] =[ identifier[prefix] + litera... | def load_overrides(introspection_module):
"""Loads overrides for an introspection module.
Either returns the same module again in case there are no overrides or a
proxy module including overrides. Doesn't cache the result.
"""
namespace = introspection_module.__name__.rsplit('.', 1)[-1]
module_... |
def add_user(self, username, password, full_name=None, trusted=False, readonly=False):
""" Add user to SQLite database.
* `username` [string]
Username of new user.
* `password` [string]
Password of new user.
* `full_name` [string]
... | def function[add_user, parameter[self, username, password, full_name, trusted, readonly]]:
constant[ Add user to SQLite database.
* `username` [string]
Username of new user.
* `password` [string]
Password of new user.
* `full_name` [string]
... | keyword[def] identifier[add_user] ( identifier[self] , identifier[username] , identifier[password] , identifier[full_name] = keyword[None] , identifier[trusted] = keyword[False] , identifier[readonly] = keyword[False] ):
literal[string]
identifier[char_set] = identifier[string] . identifi... | def add_user(self, username, password, full_name=None, trusted=False, readonly=False):
""" Add user to SQLite database.
* `username` [string]
Username of new user.
* `password` [string]
Password of new user.
* `full_name` [string]
... |
def _default_make_pool(http, proxy_info):
"""Creates a urllib3.PoolManager object that has SSL verification enabled
and uses the certifi certificates."""
if not http.ca_certs:
http.ca_certs = _certifi_where_for_ssl_version()
ssl_disabled = http.disable_ssl_certificate_validation
cert_reqs... | def function[_default_make_pool, parameter[http, proxy_info]]:
constant[Creates a urllib3.PoolManager object that has SSL verification enabled
and uses the certifi certificates.]
if <ast.UnaryOp object at 0x7da20c6c76d0> begin[:]
name[http].ca_certs assign[=] call[name[_certifi_where... | keyword[def] identifier[_default_make_pool] ( identifier[http] , identifier[proxy_info] ):
literal[string]
keyword[if] keyword[not] identifier[http] . identifier[ca_certs] :
identifier[http] . identifier[ca_certs] = identifier[_certifi_where_for_ssl_version] ()
identifier[ssl_disabled] = ... | def _default_make_pool(http, proxy_info):
"""Creates a urllib3.PoolManager object that has SSL verification enabled
and uses the certifi certificates."""
if not http.ca_certs:
http.ca_certs = _certifi_where_for_ssl_version() # depends on [control=['if'], data=[]]
ssl_disabled = http.disable_ssl... |
def install (self, scanner, target, vtarget):
""" Installs the specified scanner on actual target 'target'.
vtarget: virtual target from which 'target' was actualized.
"""
assert isinstance(scanner, Scanner)
assert isinstance(target, basestring)
assert isinstance(vtar... | def function[install, parameter[self, scanner, target, vtarget]]:
constant[ Installs the specified scanner on actual target 'target'.
vtarget: virtual target from which 'target' was actualized.
]
assert[call[name[isinstance], parameter[name[scanner], name[Scanner]]]]
assert[call[name... | keyword[def] identifier[install] ( identifier[self] , identifier[scanner] , identifier[target] , identifier[vtarget] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[scanner] , identifier[Scanner] )
keyword[assert] identifier[isinstance] ( identifier[target] , ident... | def install(self, scanner, target, vtarget):
""" Installs the specified scanner on actual target 'target'.
vtarget: virtual target from which 'target' was actualized.
"""
assert isinstance(scanner, Scanner)
assert isinstance(target, basestring)
assert isinstance(vtarget, basestring)
... |
def sync_out(self, release):
"""Sync our tree to the canonical location"""
if release.get('rsync_out_objs'):
tree = release['canonical_dir']
if not os.path.isdir(tree):
self.log.info('Creating %s', tree)
os.makedirs(tree)
self.call(rele... | def function[sync_out, parameter[self, release]]:
constant[Sync our tree to the canonical location]
if call[name[release].get, parameter[constant[rsync_out_objs]]] begin[:]
variable[tree] assign[=] call[name[release]][constant[canonical_dir]]
if <ast.UnaryOp object at 0x7... | keyword[def] identifier[sync_out] ( identifier[self] , identifier[release] ):
literal[string]
keyword[if] identifier[release] . identifier[get] ( literal[string] ):
identifier[tree] = identifier[release] [ literal[string] ]
keyword[if] keyword[not] identifier[os] . iden... | def sync_out(self, release):
"""Sync our tree to the canonical location"""
if release.get('rsync_out_objs'):
tree = release['canonical_dir']
if not os.path.isdir(tree):
self.log.info('Creating %s', tree)
os.makedirs(tree) # depends on [control=['if'], data=[]]
se... |
def readVersion(self):
""" Read the document version.
::
<designspace format="3">
"""
ds = self.root.findall("[@format]")[0]
raw_format = ds.attrib['format']
try:
self.documentFormatVersion = int(raw_format)
except ValueError:
#... | def function[readVersion, parameter[self]]:
constant[ Read the document version.
::
<designspace format="3">
]
variable[ds] assign[=] call[call[name[self].root.findall, parameter[constant[[@format]]]]][constant[0]]
variable[raw_format] assign[=] call[name[ds].attrib][... | keyword[def] identifier[readVersion] ( identifier[self] ):
literal[string]
identifier[ds] = identifier[self] . identifier[root] . identifier[findall] ( literal[string] )[ literal[int] ]
identifier[raw_format] = identifier[ds] . identifier[attrib] [ literal[string] ]
keyword[try] :... | def readVersion(self):
""" Read the document version.
::
<designspace format="3">
"""
ds = self.root.findall('[@format]')[0]
raw_format = ds.attrib['format']
try:
self.documentFormatVersion = int(raw_format) # depends on [control=['try'], data=[]]
except ValueErr... |
def callback(self, callback):
"""
Set callback for callback queries
:Example:
>>> @bot.callback
>>> def echo(chat, cq):
>>> return cq.answer()
>>> @bot.callback(r"buttonclick-(.+)")
>>> def echo(chat, cq, match):
>>> return chat.reply(ma... | def function[callback, parameter[self, callback]]:
constant[
Set callback for callback queries
:Example:
>>> @bot.callback
>>> def echo(chat, cq):
>>> return cq.answer()
>>> @bot.callback(r"buttonclick-(.+)")
>>> def echo(chat, cq, match):
>... | keyword[def] identifier[callback] ( identifier[self] , identifier[callback] ):
literal[string]
keyword[if] identifier[callable] ( identifier[callback] ):
identifier[self] . identifier[_default_callback] = identifier[callback]
keyword[return] identifier[callback]
... | def callback(self, callback):
"""
Set callback for callback queries
:Example:
>>> @bot.callback
>>> def echo(chat, cq):
>>> return cq.answer()
>>> @bot.callback(r"buttonclick-(.+)")
>>> def echo(chat, cq, match):
>>> return chat.reply(match.... |
def spatial_firing_rate(self,label_x='x',label_y='y',bins=None,resolution=1.0,geometry=None,weight_function=None,normalize_time=True,normalize_n=False,start_units_with_0=True):
"""
`bins` can be either a number of bins (has to be int) or a list of edges.
`bins` can be a tuple (fo... | def function[spatial_firing_rate, parameter[self, label_x, label_y, bins, resolution, geometry, weight_function, normalize_time, normalize_n, start_units_with_0]]:
constant[
`bins` can be either a number of bins (has to be int) or a list of edges.
`bins` can be a tuple (for x and... | keyword[def] identifier[spatial_firing_rate] ( identifier[self] , identifier[label_x] = literal[string] , identifier[label_y] = literal[string] , identifier[bins] = keyword[None] , identifier[resolution] = literal[int] , identifier[geometry] = keyword[None] , identifier[weight_function] = keyword[None] , identifier[n... | def spatial_firing_rate(self, label_x='x', label_y='y', bins=None, resolution=1.0, geometry=None, weight_function=None, normalize_time=True, normalize_n=False, start_units_with_0=True):
"""
`bins` can be either a number of bins (has to be int) or a list of edges.
`bins` can be a tupl... |
def parse_list_parts(data, bucket_name, object_name, upload_id):
"""
Parser for list parts response.
:param data: Response data for list parts.
:param bucket_name: Response for the bucket.
:param object_name: Response for the object.
:param upload_id: Upload id of object name for
the act... | def function[parse_list_parts, parameter[data, bucket_name, object_name, upload_id]]:
constant[
Parser for list parts response.
:param data: Response data for list parts.
:param bucket_name: Response for the bucket.
:param object_name: Response for the object.
:param upload_id: Upload id of... | keyword[def] identifier[parse_list_parts] ( identifier[data] , identifier[bucket_name] , identifier[object_name] , identifier[upload_id] ):
literal[string]
identifier[root] = identifier[S3Element] . identifier[fromstring] ( literal[string] , identifier[data] )
identifier[is_truncated] = identifier[ro... | def parse_list_parts(data, bucket_name, object_name, upload_id):
"""
Parser for list parts response.
:param data: Response data for list parts.
:param bucket_name: Response for the bucket.
:param object_name: Response for the object.
:param upload_id: Upload id of object name for
the act... |
def wrap_stub(elf_file):
""" Wrap an ELF file into a stub 'dict' """
print('Wrapping ELF file %s...' % elf_file)
e = esptool.ELFFile(elf_file)
text_section = e.get_section('.text')
try:
data_section = e.get_section('.data')
except ValueError:
data_section = None
stub = {
... | def function[wrap_stub, parameter[elf_file]]:
constant[ Wrap an ELF file into a stub 'dict' ]
call[name[print], parameter[binary_operation[constant[Wrapping ELF file %s...] <ast.Mod object at 0x7da2590d6920> name[elf_file]]]]
variable[e] assign[=] call[name[esptool].ELFFile, parameter[name[elf_f... | keyword[def] identifier[wrap_stub] ( identifier[elf_file] ):
literal[string]
identifier[print] ( literal[string] % identifier[elf_file] )
identifier[e] = identifier[esptool] . identifier[ELFFile] ( identifier[elf_file] )
identifier[text_section] = identifier[e] . identifier[get_section] ( litera... | def wrap_stub(elf_file):
""" Wrap an ELF file into a stub 'dict' """
print('Wrapping ELF file %s...' % elf_file)
e = esptool.ELFFile(elf_file)
text_section = e.get_section('.text')
try:
data_section = e.get_section('.data') # depends on [control=['try'], data=[]]
except ValueError:
... |
def run(self, blocking: bool=True):
"""
Run the internal control loop.
Args:
blocking (bool): Defaults to `True`. If set to `False`, will
intialize a thread to run the control loop.
Raises:
RuntimeError: If called and not using the internal control... | def function[run, parameter[self, blocking]]:
constant[
Run the internal control loop.
Args:
blocking (bool): Defaults to `True`. If set to `False`, will
intialize a thread to run the control loop.
Raises:
RuntimeError: If called and not using the ... | keyword[def] identifier[run] ( identifier[self] , identifier[blocking] : identifier[bool] = keyword[True] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_run_control_loop] :
identifier[err] =( literal[string]
literal[string] )
ke... | def run(self, blocking: bool=True):
"""
Run the internal control loop.
Args:
blocking (bool): Defaults to `True`. If set to `False`, will
intialize a thread to run the control loop.
Raises:
RuntimeError: If called and not using the internal control loo... |
def transform_alias(self, alias,rest=''):
"""Transform alias to system command string."""
nargs, cmd = self.alias_table[alias]
if ' ' in cmd and os.path.isfile(cmd):
cmd = '"%s"' % cmd
# Expand the %l special to be the user's input line
if cmd.find('%l') >= 0:
... | def function[transform_alias, parameter[self, alias, rest]]:
constant[Transform alias to system command string.]
<ast.Tuple object at 0x7da2043463e0> assign[=] call[name[self].alias_table][name[alias]]
if <ast.BoolOp object at 0x7da204347190> begin[:]
variable[cmd] assign[=] bina... | keyword[def] identifier[transform_alias] ( identifier[self] , identifier[alias] , identifier[rest] = literal[string] ):
literal[string]
identifier[nargs] , identifier[cmd] = identifier[self] . identifier[alias_table] [ identifier[alias] ]
keyword[if] literal[string] keyword[in] identif... | def transform_alias(self, alias, rest=''):
"""Transform alias to system command string."""
(nargs, cmd) = self.alias_table[alias]
if ' ' in cmd and os.path.isfile(cmd):
cmd = '"%s"' % cmd # depends on [control=['if'], data=[]]
# Expand the %l special to be the user's input line
if cmd.find(... |
def Fgamma(m,x):
"""
Incomplete gamma function
>>> np.isclose(Fgamma(0,0),1.0)
True
"""
SMALL=1e-12
x = max(x,SMALL)
return 0.5*pow(x,-m-0.5)*gamm_inc(m+0.5,x) | def function[Fgamma, parameter[m, x]]:
constant[
Incomplete gamma function
>>> np.isclose(Fgamma(0,0),1.0)
True
]
variable[SMALL] assign[=] constant[1e-12]
variable[x] assign[=] call[name[max], parameter[name[x], name[SMALL]]]
return[binary_operation[binary_operation[constant... | keyword[def] identifier[Fgamma] ( identifier[m] , identifier[x] ):
literal[string]
identifier[SMALL] = literal[int]
identifier[x] = identifier[max] ( identifier[x] , identifier[SMALL] )
keyword[return] literal[int] * identifier[pow] ( identifier[x] ,- identifier[m] - literal[int] )* identifier[... | def Fgamma(m, x):
"""
Incomplete gamma function
>>> np.isclose(Fgamma(0,0),1.0)
True
"""
SMALL = 1e-12
x = max(x, SMALL)
return 0.5 * pow(x, -m - 0.5) * gamm_inc(m + 0.5, x) |
def validate(self):
"""
Validate the current file against the SLD schema. This first normalizes
the SLD document, then validates it. Any schema validation error messages
are logged at the INFO level.
@rtype: boolean
@return: A flag indicating if the SLD is valid.
... | def function[validate, parameter[self]]:
constant[
Validate the current file against the SLD schema. This first normalizes
the SLD document, then validates it. Any schema validation error messages
are logged at the INFO level.
@rtype: boolean
@return: A flag indicating i... | keyword[def] identifier[validate] ( identifier[self] ):
literal[string]
identifier[self] . identifier[normalize] ()
keyword[if] identifier[self] . identifier[_node] keyword[is] keyword[None] :
identifier[logging] . identifier[debug] ( literal[string] )
keyword... | def validate(self):
"""
Validate the current file against the SLD schema. This first normalizes
the SLD document, then validates it. Any schema validation error messages
are logged at the INFO level.
@rtype: boolean
@return: A flag indicating if the SLD is valid.
"""... |
def C(self):
'''
Third vertex of triangle, Point subclass.
'''
try:
return self._C
except AttributeError:
pass
self._C = Point(0, 1)
return self._C | def function[C, parameter[self]]:
constant[
Third vertex of triangle, Point subclass.
]
<ast.Try object at 0x7da18fe930a0>
name[self]._C assign[=] call[name[Point], parameter[constant[0], constant[1]]]
return[name[self]._C] | keyword[def] identifier[C] ( identifier[self] ):
literal[string]
keyword[try] :
keyword[return] identifier[self] . identifier[_C]
keyword[except] identifier[AttributeError] :
keyword[pass]
identifier[self] . identifier[_C] = identifier[Point] ( litera... | def C(self):
"""
Third vertex of triangle, Point subclass.
"""
try:
return self._C # depends on [control=['try'], data=[]]
except AttributeError:
pass # depends on [control=['except'], data=[]]
self._C = Point(0, 1)
return self._C |
def render_search_template(self, id=None, body=None, params=None):
"""
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-template.html>`_
:arg id: The id of the stored search template
:arg body: The search definition template and its params
"""
... | def function[render_search_template, parameter[self, id, body, params]]:
constant[
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-template.html>`_
:arg id: The id of the stored search template
:arg body: The search definition template and its params
... | keyword[def] identifier[render_search_template] ( identifier[self] , identifier[id] = keyword[None] , identifier[body] = keyword[None] , identifier[params] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[transport] . identifier[perform_request] (
literal[s... | def render_search_template(self, id=None, body=None, params=None):
"""
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-template.html>`_
:arg id: The id of the stored search template
:arg body: The search definition template and its params
"""
retur... |
def _build_graph(self, tags):
"""Builds a graph from the entities included in the tags.
Note this is used internally.
Args:
tags (list): A list of the tags to include in graph
Returns:
graph : this is the resulting graph of the tagged entities.
"""
... | def function[_build_graph, parameter[self, tags]]:
constant[Builds a graph from the entities included in the tags.
Note this is used internally.
Args:
tags (list): A list of the tags to include in graph
Returns:
graph : this is the resulting graph of the tagged ... | keyword[def] identifier[_build_graph] ( identifier[self] , identifier[tags] ):
literal[string]
identifier[graph] = identifier[SimpleGraph] ()
keyword[for] identifier[tag_index] keyword[in] identifier[xrange] ( identifier[len] ( identifier[tags] )):
keyword[for] identifier[... | def _build_graph(self, tags):
"""Builds a graph from the entities included in the tags.
Note this is used internally.
Args:
tags (list): A list of the tags to include in graph
Returns:
graph : this is the resulting graph of the tagged entities.
"""
grap... |
def update_hints(obj, data):
"""Update the hints on the root-node of a workflow. Usually, schedule
hints are fixed per function. Sometimes a user may want to set hints
manually on a specific promised object. :func:`update_hints` uses the
`update` method on the hints dictionary with `data` as its argumen... | def function[update_hints, parameter[obj, data]]:
constant[Update the hints on the root-node of a workflow. Usually, schedule
hints are fixed per function. Sometimes a user may want to set hints
manually on a specific promised object. :func:`update_hints` uses the
`update` method on the hints dictio... | keyword[def] identifier[update_hints] ( identifier[obj] , identifier[data] ):
literal[string]
identifier[root] = identifier[obj] . identifier[_workflow] . identifier[root]
identifier[obj] . identifier[_workflow] . identifier[nodes] [ identifier[root] ]. identifier[hints] . identifier[update] ( identi... | def update_hints(obj, data):
"""Update the hints on the root-node of a workflow. Usually, schedule
hints are fixed per function. Sometimes a user may want to set hints
manually on a specific promised object. :func:`update_hints` uses the
`update` method on the hints dictionary with `data` as its argumen... |
def _get_app(self, appname):
"""
returns app object or None
"""
try:
app = APPS.get_app_config(appname)
except Exception as e:
self.err(e)
return
return app | def function[_get_app, parameter[self, appname]]:
constant[
returns app object or None
]
<ast.Try object at 0x7da18eb56ef0>
return[name[app]] | keyword[def] identifier[_get_app] ( identifier[self] , identifier[appname] ):
literal[string]
keyword[try] :
identifier[app] = identifier[APPS] . identifier[get_app_config] ( identifier[appname] )
keyword[except] identifier[Exception] keyword[as] identifier[e] :
... | def _get_app(self, appname):
"""
returns app object or None
"""
try:
app = APPS.get_app_config(appname) # depends on [control=['try'], data=[]]
except Exception as e:
self.err(e)
return # depends on [control=['except'], data=['e']]
return app |
def GetAnalyzerInstances(cls, analyzer_names):
"""Retrieves instances for all the specified analyzers.
Args:
analyzer_names (list[str]): names of the analyzers to retrieve.
Returns:
list[BaseAnalyzer]: analyzer instances.
"""
analyzer_instances = []
for analyzer_name, analyzer_clas... | def function[GetAnalyzerInstances, parameter[cls, analyzer_names]]:
constant[Retrieves instances for all the specified analyzers.
Args:
analyzer_names (list[str]): names of the analyzers to retrieve.
Returns:
list[BaseAnalyzer]: analyzer instances.
]
variable[analyzer_instances... | keyword[def] identifier[GetAnalyzerInstances] ( identifier[cls] , identifier[analyzer_names] ):
literal[string]
identifier[analyzer_instances] =[]
keyword[for] identifier[analyzer_name] , identifier[analyzer_class] keyword[in] identifier[iter] ( identifier[cls] . identifier[GetAnalyzers] ()):
... | def GetAnalyzerInstances(cls, analyzer_names):
"""Retrieves instances for all the specified analyzers.
Args:
analyzer_names (list[str]): names of the analyzers to retrieve.
Returns:
list[BaseAnalyzer]: analyzer instances.
"""
analyzer_instances = []
for (analyzer_name, analyzer_cla... |
def config_unset(name,
value_regex=None,
repo=None,
user=None,
password=None,
output_encoding=None,
**kwargs):
r'''
.. versionadded:: 2015.8.0
Ensure that the named config key is not present
name
... | def function[config_unset, parameter[name, value_regex, repo, user, password, output_encoding]]:
constant[
.. versionadded:: 2015.8.0
Ensure that the named config key is not present
name
The name of the configuration key to unset. This value can be a regex,
but the regex must match... | keyword[def] identifier[config_unset] ( identifier[name] ,
identifier[value_regex] = keyword[None] ,
identifier[repo] = keyword[None] ,
identifier[user] = keyword[None] ,
identifier[password] = keyword[None] ,
identifier[output_encoding] = keyword[None] ,
** identifier[kwargs] ):
literal[string]
ident... | def config_unset(name, value_regex=None, repo=None, user=None, password=None, output_encoding=None, **kwargs):
"""
.. versionadded:: 2015.8.0
Ensure that the named config key is not present
name
The name of the configuration key to unset. This value can be a regex,
but the regex must m... |
def encode(self, word):
"""Return the Kölner Phonetik (numeric output) code for a word.
While the output code is numeric, it is still a str because 0s can lead
the code.
Parameters
----------
word : str
The word to transform
Returns
-------
... | def function[encode, parameter[self, word]]:
constant[Return the Kölner Phonetik (numeric output) code for a word.
While the output code is numeric, it is still a str because 0s can lead
the code.
Parameters
----------
word : str
The word to transform
... | keyword[def] identifier[encode] ( identifier[self] , identifier[word] ):
literal[string]
keyword[def] identifier[_after] ( identifier[word] , identifier[pos] , identifier[letters] ):
literal[string]
keyword[return] identifier[pos] > literal[int] keyword[and] identifi... | def encode(self, word):
"""Return the Kölner Phonetik (numeric output) code for a word.
While the output code is numeric, it is still a str because 0s can lead
the code.
Parameters
----------
word : str
The word to transform
Returns
-------
... |
def create_setup_cfg(self, path): # type: (str) -> None
"""
Just setup.cfg
:param path:
:return:
"""
source = """[metadata]
name = {0}
version=0.0.1
""".format(
self.project
)
with io.open(path, "w", encoding="utf-8") as outfile:
... | def function[create_setup_cfg, parameter[self, path]]:
constant[
Just setup.cfg
:param path:
:return:
]
variable[source] assign[=] call[constant[[metadata]
name = {0}
version=0.0.1
].format, parameter[name[self].project]]
with call[name[io].open, parameter[name[p... | keyword[def] identifier[create_setup_cfg] ( identifier[self] , identifier[path] ):
literal[string]
identifier[source] = literal[string] . identifier[format] (
identifier[self] . identifier[project]
)
keyword[with] identifier[io] . identifier[open] ( identifier[path] , li... | def create_setup_cfg(self, path): # type: (str) -> None
'\n Just setup.cfg\n :param path:\n :return:\n '
source = '[metadata]\nname = {0}\nversion=0.0.1 \n'.format(self.project)
with io.open(path, 'w', encoding='utf-8') as outfile:
outfile.write(source) # depends on [co... |
def registration_agency(self, ids, **kwargs):
'''
Determine registration agency for DOIs
:param ids: [Array] DOIs (digital object identifier) or other identifiers
:param kwargs: additional named arguments passed on to `requests.get`, e.g., field
queries (see examples)
... | def function[registration_agency, parameter[self, ids]]:
constant[
Determine registration agency for DOIs
:param ids: [Array] DOIs (digital object identifier) or other identifiers
:param kwargs: additional named arguments passed on to `requests.get`, e.g., field
queries (see... | keyword[def] identifier[registration_agency] ( identifier[self] , identifier[ids] ,** identifier[kwargs] ):
literal[string]
identifier[check_kwargs] ([ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ,
literal[string] , literal[stri... | def registration_agency(self, ids, **kwargs):
"""
Determine registration agency for DOIs
:param ids: [Array] DOIs (digital object identifier) or other identifiers
:param kwargs: additional named arguments passed on to `requests.get`, e.g., field
queries (see examples)
:... |
def build_simple_cnn_text_classifier(tok2vec, nr_class, exclusive_classes=False, **cfg):
"""
Build a simple CNN text classifier, given a token-to-vector model as inputs.
If exclusive_classes=True, a softmax non-linearity is applied, so that the
outputs sum to 1. If exclusive_classes=False, a logistic no... | def function[build_simple_cnn_text_classifier, parameter[tok2vec, nr_class, exclusive_classes]]:
constant[
Build a simple CNN text classifier, given a token-to-vector model as inputs.
If exclusive_classes=True, a softmax non-linearity is applied, so that the
outputs sum to 1. If exclusive_classes=Fa... | keyword[def] identifier[build_simple_cnn_text_classifier] ( identifier[tok2vec] , identifier[nr_class] , identifier[exclusive_classes] = keyword[False] ,** identifier[cfg] ):
literal[string]
keyword[with] identifier[Model] . identifier[define_operators] ({ literal[string] : identifier[chain] }):
... | def build_simple_cnn_text_classifier(tok2vec, nr_class, exclusive_classes=False, **cfg):
"""
Build a simple CNN text classifier, given a token-to-vector model as inputs.
If exclusive_classes=True, a softmax non-linearity is applied, so that the
outputs sum to 1. If exclusive_classes=False, a logistic no... |
def URL(base, path, segments=None, defaults=None):
"""
URL segment handler capable of getting and setting segments by name. The
URL is constructed by joining base, path and segments.
For each segment a property capable of getting and setting that segment is
created dynamically.
"""
# Make a... | def function[URL, parameter[base, path, segments, defaults]]:
constant[
URL segment handler capable of getting and setting segments by name. The
URL is constructed by joining base, path and segments.
For each segment a property capable of getting and setting that segment is
created dynamically.... | keyword[def] identifier[URL] ( identifier[base] , identifier[path] , identifier[segments] = keyword[None] , identifier[defaults] = keyword[None] ):
literal[string]
identifier[url_class] = identifier[type] ( identifier[Segments] . identifier[__name__] , identifier[Segments] . identifier[__bases__] ,
... | def URL(base, path, segments=None, defaults=None):
"""
URL segment handler capable of getting and setting segments by name. The
URL is constructed by joining base, path and segments.
For each segment a property capable of getting and setting that segment is
created dynamically.
"""
# Make a... |
def list(self, date_created_after=values.unset,
date_created_before=values.unset, track=values.unset,
publisher=values.unset, kind=values.unset, limit=None, page_size=None):
"""
Lists SubscribedTrackInstance records from the API as a list.
Unlike stream(), this operatio... | def function[list, parameter[self, date_created_after, date_created_before, track, publisher, kind, limit, page_size]]:
constant[
Lists SubscribedTrackInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before return... | keyword[def] identifier[list] ( identifier[self] , identifier[date_created_after] = identifier[values] . identifier[unset] ,
identifier[date_created_before] = identifier[values] . identifier[unset] , identifier[track] = identifier[values] . identifier[unset] ,
identifier[publisher] = identifier[values] . identifier... | def list(self, date_created_after=values.unset, date_created_before=values.unset, track=values.unset, publisher=values.unset, kind=values.unset, limit=None, page_size=None):
"""
Lists SubscribedTrackInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limi... |
def path_exists_or_creatable_portable(pathname: str) -> bool:
"""OS-portable check for whether current path exists or is creatable.
This function is guaranteed to _never_ raise exceptions.
Returns
------
`True` if the passed pathname is a valid pathname on the current OS _and_
either currently... | def function[path_exists_or_creatable_portable, parameter[pathname]]:
constant[OS-portable check for whether current path exists or is creatable.
This function is guaranteed to _never_ raise exceptions.
Returns
------
`True` if the passed pathname is a valid pathname on the current OS _and_
... | keyword[def] identifier[path_exists_or_creatable_portable] ( identifier[pathname] : identifier[str] )-> identifier[bool] :
literal[string]
keyword[try] :
keyword[return] identifier[is_pathname_valid] ( identifier[pathname] ) keyword[and] (
identifier[os] . identifier[path] . id... | def path_exists_or_creatable_portable(pathname: str) -> bool:
"""OS-portable check for whether current path exists or is creatable.
This function is guaranteed to _never_ raise exceptions.
Returns
------
`True` if the passed pathname is a valid pathname on the current OS _and_
either currently... |
def _read_byte(self):
"""Read a byte from input."""
to_return = ""
if (self._mode == PROP_MODE_SERIAL):
to_return = self._serial.read(1)
elif (self._mode == PROP_MODE_TCP):
to_return = self._socket.recv(1)
elif (self._mode == PROP_MODE_FILE):
... | def function[_read_byte, parameter[self]]:
constant[Read a byte from input.]
variable[to_return] assign[=] constant[]
if compare[name[self]._mode equal[==] name[PROP_MODE_SERIAL]] begin[:]
variable[to_return] assign[=] call[name[self]._serial.read, parameter[constant[1]]]
... | keyword[def] identifier[_read_byte] ( identifier[self] ):
literal[string]
identifier[to_return] = literal[string]
keyword[if] ( identifier[self] . identifier[_mode] == identifier[PROP_MODE_SERIAL] ):
identifier[to_return] = identifier[self] . identifier[_serial] . identifier... | def _read_byte(self):
"""Read a byte from input."""
to_return = ''
if self._mode == PROP_MODE_SERIAL:
to_return = self._serial.read(1) # depends on [control=['if'], data=[]]
elif self._mode == PROP_MODE_TCP:
to_return = self._socket.recv(1) # depends on [control=['if'], data=[]]
el... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.