code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_settings_json(self):
"""Convert generator settings to JSON.
Returns
-------
`dict`
JSON data.
"""
return {
'scanner': None if self.scanner is None else self.scanner.save(),
'parser': None if self.parser is None else self.parser... | Convert generator settings to JSON.
Returns
-------
`dict`
JSON data. |
def isTagEqual(self, other):
'''
isTagEqual - Compare if a tag contains the same tag name and attributes as another tag,
i.e. if everything between < and > parts of this tag are the same.
Does NOT compare children, etc. Does NOT compare if these are the same exact t... | isTagEqual - Compare if a tag contains the same tag name and attributes as another tag,
i.e. if everything between < and > parts of this tag are the same.
Does NOT compare children, etc. Does NOT compare if these are the same exact tag in the html (use regular == operator for that)
... |
def ackermann_naive(m: int, n: int) -> int:
"""Ackermann number.
"""
if m == 0:
return n + 1
elif n == 0:
return ackermann(m - 1, 1)
else:
return ackermann(m - 1, ackermann(m, n - 1)) | Ackermann number. |
def hsvToRGB(h, s, v):
"""
Convert HSV (hue, saturation, value) color space to RGB (red, green blue)
color space.
**Parameters**
**h** : float
Hue, a number in [0, 360].
**s** : float
Saturation, a number in [0, 1].
**v... | Convert HSV (hue, saturation, value) color space to RGB (red, green blue)
color space.
**Parameters**
**h** : float
Hue, a number in [0, 360].
**s** : float
Saturation, a number in [0, 1].
**v** : float
Va... |
def blockType(self, kind):
"""Read block type switch descriptor for given kind of blockType."""
NBLTYPES = self.verboseRead(TypeCountAlphabet(
'BT#'+kind[0].upper(),
description='{} block types'.format(kind),
))
self.numberOfBlockTypes[kind] = NBLTYPES
... | Read block type switch descriptor for given kind of blockType. |
def _initAsteriskVersion(self):
"""Query Asterisk Manager Interface for Asterisk Version to configure
system for compatibility with multiple versions
.
CLI Command - core show version
"""
if self._ami_version > util.SoftwareVersion('1.0'):
cmd = "core show ve... | Query Asterisk Manager Interface for Asterisk Version to configure
system for compatibility with multiple versions
.
CLI Command - core show version |
def set_back(self, x: int, y: int, r: int, g: int, b: int) -> None:
"""Set the background color of one cell.
Args:
x (int): X position to change.
y (int): Y position to change.
r (int): Red background color, from 0 to 255.
g (int): Green background color,... | Set the background color of one cell.
Args:
x (int): X position to change.
y (int): Y position to change.
r (int): Red background color, from 0 to 255.
g (int): Green background color, from 0 to 255.
b (int): Blue background color, from 0 to 255. |
def _save_np(obj, pathfileext, compressed=False):
func = np.savez_compressed if compressed else np.savez
dId = obj.Id._todict()
# tofu.geom
if obj.Id.Cls=='Ves':
func(pathfileext, Id=dId, arrayorder=obj._arrayorder, Clock=obj._Clock,
Poly=obj.Poly, Lim=obj.Lim, Sino_RefPt=obj.sino... | elif obj.Id.Cls=='GLOS':
LIdLOS = [ll.Id.todict() for ll in obj.LLOS]
LDs, Lus = np.array([ll.D for ll in obj.LLOS]).T, np.array([ll.u for ll in obj.LLOS]).T
func(pathfileext, Idsave=Idsave, LIdLOS=LIdLOS, LDs=LDs, Lus=Lus, Sino_RefPt=obj.Sino_RefPt, arrayorder=obj._arrayorder, Clock=obj._Clock)... |
def check_authorization(self):
"""
Check for the presence of a basic auth Authorization header and
if the credentials contained within in are valid.
:return: Whether or not the credentials are valid.
:rtype: bool
"""
try:
store = self.__config.get('basic_auth')
if store is None:
return True
... | Check for the presence of a basic auth Authorization header and
if the credentials contained within in are valid.
:return: Whether or not the credentials are valid.
:rtype: bool |
def surface_nodes(self):
"""
:param points: a list of Point objects
:returns: a Node of kind 'griddedSurface'
"""
line = []
for point in self.mesh:
line.append(point.longitude)
line.append(point.latitude)
line.append(point.depth)
... | :param points: a list of Point objects
:returns: a Node of kind 'griddedSurface' |
def _post_deactivate_injection(self):
"""
Injects functions after the deactivation routine of child classes got called
:return: None
"""
# Lets be sure that active is really set to false.
self.active = False
self.app.signals.send("plugin_deactivate_post", self)
... | Injects functions after the deactivation routine of child classes got called
:return: None |
def omegac(self,R):
"""
NAME:
omegac
PURPOSE:
calculate the circular angular speed at R in potential Pot
INPUT:
Pot - Potential instance or list of such instances
R - Galactocentric rad... | NAME:
omegac
PURPOSE:
calculate the circular angular speed at R in potential Pot
INPUT:
Pot - Potential instance or list of such instances
R - Galactocentric radius (can be Quantity)
OUTPUT:
... |
def log(self, level, prefix = ''):
"""Writes the contents of the Extension to the logging system.
"""
logging.log(level, "%sname: %s", prefix, self.__name)
logging.log(level, "%soptions: %s", prefix, self.__options) | Writes the contents of the Extension to the logging system. |
def _parse_sid_response(res):
"""Parse response format for request for new channel SID.
Example format (after parsing JS):
[ [0,["c","SID_HERE","",8]],
[1,[{"gsid":"GSESSIONID_HERE"}]]]
Returns (SID, gsessionid) tuple.
"""
res = json.loads(list(ChunkParser().get_chunks(res))[0])
... | Parse response format for request for new channel SID.
Example format (after parsing JS):
[ [0,["c","SID_HERE","",8]],
[1,[{"gsid":"GSESSIONID_HERE"}]]]
Returns (SID, gsessionid) tuple. |
def gettext(ui_file_path):
"""
Let you use gettext instead of the Qt tools for l18n
"""
with open(ui_file_path, 'r') as fin:
content = fin.read()
# replace ``_translate("context", `` by ``_(``
content = re.sub(r'_translate\(".*",\s', '_(', content)
content = content.replace(
... | Let you use gettext instead of the Qt tools for l18n |
def get_perceel_by_id_and_sectie(self, id, sectie):
'''
Get a `perceel`.
:param id: An id for a `perceel`.
:param sectie: The :class:`Sectie` that contains the perceel.
:rtype: :class:`Perceel`
'''
sid = sectie.id
aid = sectie.afdeling.id
gid = se... | Get a `perceel`.
:param id: An id for a `perceel`.
:param sectie: The :class:`Sectie` that contains the perceel.
:rtype: :class:`Perceel` |
def download_wiki():
"""Download WikiPedia pages of ambiguous units."""
ambiguous = [i for i in l.UNITS.items() if len(i[1]) > 1]
ambiguous += [i for i in l.DERIVED_ENT.items() if len(i[1]) > 1]
pages = set([(j.name, j.uri) for i in ambiguous for j in i[1]])
print
objs = []
for num, page in... | Download WikiPedia pages of ambiguous units. |
def from_tree(cls, repo, *treeish, **kwargs):
"""Merge the given treeish revisions into a new index which is returned.
The original index will remain unaltered
:param repo:
The repository treeish are located in.
:param treeish:
One, two or three Tree Objects, Co... | Merge the given treeish revisions into a new index which is returned.
The original index will remain unaltered
:param repo:
The repository treeish are located in.
:param treeish:
One, two or three Tree Objects, Commits or 40 byte hexshas. The result
changes ... |
def get_chat_ids(self):
"""Returns unique chat IDs from `/start` command messages sent to our bot by users.
Those chat IDs can be used to send messages to chats.
:rtype: list
"""
updates = self.get_updates()
chat_ids = []
if updates:
for update in upd... | Returns unique chat IDs from `/start` command messages sent to our bot by users.
Those chat IDs can be used to send messages to chats.
:rtype: list |
def fetch_ensembl_exons(build='37'):
"""Fetch the ensembl genes
Args:
build(str): ['37', '38']
"""
LOG.info("Fetching ensembl exons build %s ...", build)
if build == '37':
url = 'http://grch37.ensembl.org'
else:
url = 'http://www.ensembl.org'
dataset_name = ... | Fetch the ensembl genes
Args:
build(str): ['37', '38'] |
def make(world_name, gl_version=GL_VERSION.OPENGL4, window_res=None, cam_res=None, verbose=False):
"""Creates a holodeck environment using the supplied world name.
Args:
world_name (str): The name of the world to load as an environment. Must match the name of a world in an
installed package... | Creates a holodeck environment using the supplied world name.
Args:
world_name (str): The name of the world to load as an environment. Must match the name of a world in an
installed package.
gl_version (int, optional): The OpenGL version to use (Linux only). Defaults to GL_VERSION.OPENG... |
def format_bytes_size(val):
"""
Take a number of bytes and convert it to a human readable number.
:param int val: The number of bytes to format.
:return: The size in a human readable format.
:rtype: str
"""
if not val:
return '0 bytes'
for sz_name in ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB']:
if val < ... | Take a number of bytes and convert it to a human readable number.
:param int val: The number of bytes to format.
:return: The size in a human readable format.
:rtype: str |
def inspect_members(self):
"""
Returns the list of all troposphere members we are able to
construct
"""
if not self._inspect_members:
TemplateGenerator._inspect_members = \
self._import_all_troposphere_modules()
return self._inspect_members | Returns the list of all troposphere members we are able to
construct |
def create_machine_group(self, project_name, group_detail):
""" create machine group in a project
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type group_detail: MachineGroupDetail
:param g... | create machine group in a project
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type group_detail: MachineGroupDetail
:param group_detail: the machine group detail config
:return: CreateMa... |
async def send_tokens(payment_handle: int, tokens: int, address: str) -> str:
"""
Sends tokens to an address
payment_handle is always 0
:param payment_handle: Integer
:param tokens: Integer
:param address: String
Example:
payment_handle = 0
amount ... | Sends tokens to an address
payment_handle is always 0
:param payment_handle: Integer
:param tokens: Integer
:param address: String
Example:
payment_handle = 0
amount = 1000
address = await Wallet.create_payment_address('00000000000000000000000001234567')
... |
def execute(self, eopatch=None, bbox=None, time_interval=None):
"""
Creates OGC (WMS or WCS) request, downloads requested data and stores it together
with valid data mask in newly created EOPatch. Returns the EOPatch.
:param eopatch:
:type eopatch: EOPatch or None
:param... | Creates OGC (WMS or WCS) request, downloads requested data and stores it together
with valid data mask in newly created EOPatch. Returns the EOPatch.
:param eopatch:
:type eopatch: EOPatch or None
:param bbox: specifies the bounding box of the requested image. Coordinates must be in
... |
def check_base_suggested_attributes(self, dataset):
'''
Check the global suggested attributes for 2.0 templates. These go an extra step besides
just checking that they exist.
:param netCDF4.Dataset dataset: An open netCDF dataset
:creator_type = "" ; //............................ | Check the global suggested attributes for 2.0 templates. These go an extra step besides
just checking that they exist.
:param netCDF4.Dataset dataset: An open netCDF dataset
:creator_type = "" ; //........................................ SUGGESTED - Specifies type of creator with one of the fo... |
def _display_token(self):
"""
Display token information or redirect to login prompt if none is
available.
"""
if self.token is None:
return "301 Moved", "", {"Location": "/login"}
return ("200 OK",
self.TOKEN_TEMPLATE.format(
... | Display token information or redirect to login prompt if none is
available. |
def yahoo(base, target):
"""Parse data from Yahoo."""
api_url = 'http://download.finance.yahoo.com/d/quotes.csv'
resp = requests.get(
api_url,
params={
'e': '.csv',
'f': 'sl1d1t1',
's': '{0}{1}=X'.format(base, target)
},
timeout=1,
)
... | Parse data from Yahoo. |
def degree_circle(self,EdgeAttribute=None,network=None,NodeAttribute=None,\
nodeList=None,singlePartition=None,verbose=None):
"""
Execute the Degree Sorted Circle Layout on a network.
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights... | Execute the Degree Sorted Circle Layout on a network.
:param EdgeAttribute (string, optional): The name of the edge column contai
ning numeric values that will be used as weights in the layout algor
ithm. Only columns containing numeric values are shown
:param network (string, optional): Specifies a network ... |
def to_python(cls, value, **kwargs):
"""String deserialisation just return the value as a string"""
if not value:
return ''
try:
return str(value)
except:
pass
try:
return value.encode('utf-8')
except:
pass
... | String deserialisation just return the value as a string |
def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1):
"""Builds the operations adding a Keyword Criterion to each AdGroup.
Args:
adgroup_operations: a list containing the operations that will add AdGroups.
number_of_keywords: an int defining the number of Keywords to be created.
... | Builds the operations adding a Keyword Criterion to each AdGroup.
Args:
adgroup_operations: a list containing the operations that will add AdGroups.
number_of_keywords: an int defining the number of Keywords to be created.
Returns:
a list containing the operations that will create a new Keyword Criter... |
def get_remote_url(self, remote='origin', cached=True):
"""Get a git remote URL for this instance."""
if hasattr(self.__class__, '_remote_url') and cached:
url = self.__class__._remote_url
else:
r = self.get_remote(remote)
try:
url = list(r.url... | Get a git remote URL for this instance. |
def _get_ensemble_bed_files(items):
"""
get all ensemble structural BED file calls, skipping any normal samples from
tumor/normal calls
"""
bed_files = []
for data in items:
for sv in data.get("sv", []):
if sv["variantcaller"] == "sv-ensemble":
if ("vrn_file" ... | get all ensemble structural BED file calls, skipping any normal samples from
tumor/normal calls |
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
cb_ = _get_connection()
try:
jid_doc = cb_.get(six.text_type(jid))
except couchbase.exceptions.NotFoundError:
return {}
ret = {}
try:
ret = jid_doc.value['load']
ret['Minions'] = ... | Return the load data that marks a specified jid |
def vlink(s_expnum, s_ccd, s_version, s_ext,
l_expnum, l_ccd, l_version, l_ext, s_prefix=None, l_prefix=None):
"""make a link between two version of a file.
@param s_expnum:
@param s_ccd:
@param s_version:
@param s_ext:
@param l_expnum:
@param l_ccd:
@param l_version:
@par... | make a link between two version of a file.
@param s_expnum:
@param s_ccd:
@param s_version:
@param s_ext:
@param l_expnum:
@param l_ccd:
@param l_version:
@param l_ext:
@param s_prefix:
@param l_prefix:
@return: |
def hover_pixmap(self, value):
"""
Setter for **self.__hover_pixmap** attribute.
:param value: Attribute value.
:type value: QPixmap
"""
if value is not None:
assert type(value) is QPixmap, "'{0}' attribute: '{1}' type is not 'QPixmap'!".format(
... | Setter for **self.__hover_pixmap** attribute.
:param value: Attribute value.
:type value: QPixmap |
def omim_terms(case_obj):
"""Extract all OMIM phenotypes available for the case
Args:
case_obj(dict): a scout case object
Returns:
disorders(list): a list of OMIM disorder objects
"""
LOG.info("Collecting OMIM disorders for case {}".format(case_obj.get('display_name')))
disorders... | Extract all OMIM phenotypes available for the case
Args:
case_obj(dict): a scout case object
Returns:
disorders(list): a list of OMIM disorder objects |
def get_streaming(self, path, stype="M3U8_AUTO_480", **kwargs):
"""获得视频的m3u8列表
:param path: 视频文件路径
:param stype: 返回stream类型, 已知有``M3U8_AUTO_240``/``M3U8_AUTO_480``/``M3U8_AUTO_720``
.. warning::
M3U8_AUTO_240会有问题, 目前480P是最稳定的, 也是百度网盘默认的
:return: str 播放(列表)需要... | 获得视频的m3u8列表
:param path: 视频文件路径
:param stype: 返回stream类型, 已知有``M3U8_AUTO_240``/``M3U8_AUTO_480``/``M3U8_AUTO_720``
.. warning::
M3U8_AUTO_240会有问题, 目前480P是最稳定的, 也是百度网盘默认的
:return: str 播放(列表)需要的信息 |
def create_html(self, filename=None):
"""Create a circle visual from a geojson data source"""
if isinstance(self.style, str):
style = "'{}'".format(self.style)
else:
style = self.style
options = dict(
gl_js_version=GL_JS_VERSION,
... | Create a circle visual from a geojson data source |
def make_conditional(
self, request_or_environ, accept_ranges=False, complete_length=None
):
"""Make the response conditional to the request. This method works
best if an etag was defined for the response already. The `add_etag`
method can be used to do that. If called without eta... | Make the response conditional to the request. This method works
best if an etag was defined for the response already. The `add_etag`
method can be used to do that. If called without etag just the date
header is set.
This does nothing if the request method in the request or environ is... |
def parse(self, parser):
"""Parse a translatable tag."""
lineno = next(parser.stream).lineno
num_called_num = False
# find all the variables referenced. Additionally a variable can be
# defined in the body of the trans block too, but this is checked at
# a later state.
... | Parse a translatable tag. |
def apply_patch(self):
"""
Fix default socket lib to handle client disconnection while receiving data (Broken pipe)
"""
if sys.version_info >= (3, 0):
# No patch for python >= 3.0
pass
else:
from .patch.socket import socket as patch
... | Fix default socket lib to handle client disconnection while receiving data (Broken pipe) |
def boundary_polygon(self, time):
"""
Get coordinates of object boundary in counter-clockwise order
"""
ti = np.where(time == self.times)[0][0]
com_x, com_y = self.center_of_mass(time)
# If at least one point along perimeter of the mask rectangle is unmasked, find_boundar... | Get coordinates of object boundary in counter-clockwise order |
def to_value_list(original_strings, corenlp_values=None):
"""Convert a list of strings to a list of Values
Args:
original_strings (list[basestring])
corenlp_values (list[basestring or None])
Returns:
list[Value]
"""
assert isinstance(original_strings, (list, tuple, set))
... | Convert a list of strings to a list of Values
Args:
original_strings (list[basestring])
corenlp_values (list[basestring or None])
Returns:
list[Value] |
def name(object):
"Try to find some reasonable name for the object."
return (getattr(object, 'name', 0) or getattr(object, '__name__', 0)
or getattr(getattr(object, '__class__', 0), '__name__', 0)
or str(object)) | Try to find some reasonable name for the object. |
def getVariable(dbg, thread_id, frame_id, scope, attrs):
"""
returns the value of a variable
:scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, FRAME
BY_ID means we'll traverse the list of all objects alive to get the object.
:attrs: after reaching the proper scope, we have to get the attributes un... | returns the value of a variable
:scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, FRAME
BY_ID means we'll traverse the list of all objects alive to get the object.
:attrs: after reaching the proper scope, we have to get the attributes until we find
the proper location (i.e.: obj\tattr1\tattr2)... |
def copy_ecu_with_frames(ecu_or_glob, source_db, target_db):
# type: (typing.Union[cm.Ecu, str], cm.CanMatrix, cm.CanMatrix) -> None
"""
Copy ECU(s) identified by Name or as Object from source CAN matrix to target CAN matrix.
This function additionally copy all relevant Frames and Defines.
:param e... | Copy ECU(s) identified by Name or as Object from source CAN matrix to target CAN matrix.
This function additionally copy all relevant Frames and Defines.
:param ecu_or_glob: Ecu instance or glob pattern for Ecu name
:param source_db: Source CAN matrix
:param target_db: Destination CAN matrix |
def use(self, func, when='whenever'):
''' Append a middleware to the algorithm '''
#NOTE A middleware Object ?
# self.use() is usually called from initialize(), so no logger yet
print('registering middleware {}'.format(func.__name__))
self.middlewares.append({
'call':... | Append a middleware to the algorithm |
def get_descriptor_defaults(self, api_info, hostname=None, x_google_api_name=False):
"""Gets a default configuration for a service.
Args:
api_info: _ApiInfo object for this service.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
... | Gets a default configuration for a service.
Args:
api_info: _ApiInfo object for this service.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Returns:
A dictionary with the default configuration. |
def dev_get_chunk(dev_name, state, pugrp=None, punit=None):
"""
Get a chunk-descriptor for the first chunk in the given state.
If the pugrp and punit is set, then search only that pugrp/punit
@returns the first chunk in the given state if one exists, None otherwise
"""
rprt = dev_get_rprt(dev... | Get a chunk-descriptor for the first chunk in the given state.
If the pugrp and punit is set, then search only that pugrp/punit
@returns the first chunk in the given state if one exists, None otherwise |
def generate(env):
"Add RPCGEN Builders and construction variables for an Environment."
client = Builder(action=rpcgen_client, suffix='_clnt.c', src_suffix='.x')
header = Builder(action=rpcgen_header, suffix='.h', src_suffix='.x')
service = Builder(action=rpcgen_service, suffix='_svc.c', ... | Add RPCGEN Builders and construction variables for an Environment. |
def _compile_int_g(self):
"""Time Domain Simulation - update algebraic equations and Jacobian"""
string = '"""\n'
# evaluate the algebraic equations g
string += 'system.dae.init_g()\n'
for gcall, call in zip(self.gcall, self.gcalls):
if gcall:
string ... | Time Domain Simulation - update algebraic equations and Jacobian |
def createFromSource(cls, vs, name, registry):
''' returns a registry component for anything that's a valid package
name (this does not guarantee that the component actually exists in
the registry: use availableVersions() for that).
'''
# we deliberately allow only lowerc... | returns a registry component for anything that's a valid package
name (this does not guarantee that the component actually exists in
the registry: use availableVersions() for that). |
def _get_build_prefix():
""" Returns a safe build_prefix """
path = os.path.join(
tempfile.gettempdir(),
'pip_build_%s' % __get_username().replace(' ', '_')
)
if WINDOWS:
""" on windows(tested on 7) temp dirs are isolated """
return path
try:
os.mkdir(path)
... | Returns a safe build_prefix |
def entropy_H(self, data):
"""Calculate the entropy of a chunk of data."""
if len(data) == 0:
return 0.0
occurences = array.array('L', [0]*256)
for x in data:
occurences[ord(x)] += 1
entropy = 0
for x in occurenc... | Calculate the entropy of a chunk of data. |
def _newproject(command, path, name, settings):
"""
Helper to create new project.
"""
key = None
title = _get_project_title()
template = _get_template(settings)
# Init repo
git = sh.git.bake(_cwd=path)
puts(git.init())
if template.get("url"):
# Create submodule
... | Helper to create new project. |
def get_text_stream(name, encoding=None, errors='strict'):
"""Returns a system stream for text processing. This usually returns
a wrapped stream around a binary stream returned from
:func:`get_binary_stream` but it also can take shortcuts on Python 3
for already correctly configured streams.
:para... | Returns a system stream for text processing. This usually returns
a wrapped stream around a binary stream returned from
:func:`get_binary_stream` but it also can take shortcuts on Python 3
for already correctly configured streams.
:param name: the name of the stream to open. Valid names are ``'stdin'... |
def update(self, response, **kwargs):
'''
If a record matching the instance already exists in the database, update
both the column and venue column attributes, else create a new record.
'''
response_cls = super(
LocationResponseClassLegacyAccessor, self)._get_instance... | If a record matching the instance already exists in the database, update
both the column and venue column attributes, else create a new record. |
def from_Solis(filepath, name=None, parent=None, verbose=True) -> Data:
"""Create a data object from Andor Solis software (ascii exports).
Parameters
----------
filepath : path-like
Path to .txt file.
Can be either a local or remote file (http/ftp).
Can be compressed with gz/bz2... | Create a data object from Andor Solis software (ascii exports).
Parameters
----------
filepath : path-like
Path to .txt file.
Can be either a local or remote file (http/ftp).
Can be compressed with gz/bz2, decompression based on file name.
name : string (optional)
Name t... |
def parse_plays_stream(self):
"""Generate and yield a stream of parsed plays. Useful for per play processing."""
lx_doc = self.html_doc()
if lx_doc is not None:
parser = PlayParser(self.game_key.season, self.game_key.game_type)
plays = lx_doc.xpath('//tr[@class =... | Generate and yield a stream of parsed plays. Useful for per play processing. |
def accpro20_summary(self, cutoff):
"""Parse the ACCpro output file and return a summary of percent exposed/buried residues based on a cutoff.
Below the cutoff = buried
Equal to or greater than cutoff = exposed
The default cutoff used in accpro is 25%.
The output file is just a... | Parse the ACCpro output file and return a summary of percent exposed/buried residues based on a cutoff.
Below the cutoff = buried
Equal to or greater than cutoff = exposed
The default cutoff used in accpro is 25%.
The output file is just a FASTA formatted file, so you can get residue l... |
def embedded_preview(src_path):
''' Returns path to temporary copy of embedded QuickLook preview, if it exists '''
try:
assert(exists(src_path) and isdir(src_path))
preview_list = glob(join(src_path, '[Q|q]uicklook', '[P|p]review.*'))
assert(preview_list) # Assert there's at least one preview file
... | Returns path to temporary copy of embedded QuickLook preview, if it exists |
def solve(self):
"""Start (or re-start) optimisation. This method implements the
framework for the iterations of a FISTA algorithm. There is
sufficient flexibility in overriding the component methods that
it calls that it is usually not necessary to override this method
in derive... | Start (or re-start) optimisation. This method implements the
framework for the iterations of a FISTA algorithm. There is
sufficient flexibility in overriding the component methods that
it calls that it is usually not necessary to override this method
in derived clases.
If option... |
def attach_volume_to_device(self, volume_id, device_id):
"""Attaches the created Volume to a Device.
"""
try:
volume = self.manager.get_volume(volume_id)
volume.attach(device_id)
except packet.baseapi.Error as msg:
raise PacketManagerException(msg)
... | Attaches the created Volume to a Device. |
def ctcBeamSearch(mat, classes, lm, k, beamWidth):
"""
beam search as described by the paper of Hwang et al. and the paper of Graves et al.
"""
blankIdx = len(classes)
maxT, maxC = mat.shape
# initialise beam state
last = BeamState()
labeling = ()
last.entries[labeling] = BeamEntry... | beam search as described by the paper of Hwang et al. and the paper of Graves et al. |
def _search_dirs(self, dirs, basename, extension=""):
"""Search a list of directories for a given filename or directory name.
Iterator over the supplied directories, returning the first file
found with the supplied name and extension.
:param dirs: a list of directories
:... | Search a list of directories for a given filename or directory name.
Iterator over the supplied directories, returning the first file
found with the supplied name and extension.
:param dirs: a list of directories
:param basename: the filename
:param extension: the file e... |
def parse_scale(x):
"""Splits a "%s:%d" string and returns the string and number.
:return: A ``(string, int)`` pair extracted from ``x``.
:raise ValueError: the string ``x`` does not respect the input format.
"""
match = re.match(r'^(.+?):(\d+)$', x)
if not match:
raise ValueError('Inv... | Splits a "%s:%d" string and returns the string and number.
:return: A ``(string, int)`` pair extracted from ``x``.
:raise ValueError: the string ``x`` does not respect the input format. |
def get_markdown_levels(lines, levels=set((0, 1, 2, 3, 4, 5, 6))):
r""" Return a list of 2-tuples with a level integer for the heading levels
>>> get_markdown_levels('paragraph \n##bad\n# hello\n ### world\n')
[(0, 'paragraph '), (2, 'bad'), (0, '# hello'), (3, 'world')]
>>> get_markdown_levels('- bul... | r""" Return a list of 2-tuples with a level integer for the heading levels
>>> get_markdown_levels('paragraph \n##bad\n# hello\n ### world\n')
[(0, 'paragraph '), (2, 'bad'), (0, '# hello'), (3, 'world')]
>>> get_markdown_levels('- bullet \n##bad\n# hello\n ### world\n')
[(0, '- bullet '), (2, 'bad')... |
def _compute_geometric_decay_term(self, C, mag, dists):
"""
Compute and return geometric decay term in equation 3,
page 970.
"""
c1 = self.CONSTS['c1']
return (
(C['b4'] + C['b5'] * (mag - c1)) *
np.log(np.sqrt(dists.rjb ** 2.0 + C['b6'] **... | Compute and return geometric decay term in equation 3,
page 970. |
def calculate_ef_var(tpf, fpf):
"""
determine variance due to actives (efvar_a) decoys (efvar_d) and s2, the slope of the ROC curve tangent to the
fpf @ which the enrichment factor was calculated
:param tpf: float tpf @ which the enrichment factor was calculated
:param fpf: float fpf @ which the enr... | determine variance due to actives (efvar_a) decoys (efvar_d) and s2, the slope of the ROC curve tangent to the
fpf @ which the enrichment factor was calculated
:param tpf: float tpf @ which the enrichment factor was calculated
:param fpf: float fpf @ which the enrichment factor was calculated
:return ef... |
def makeringlatticeCIJ(n, k, seed=None):
'''
This function generates a directed lattice network with toroidal
boundary counditions (i.e. with ring-like "wrapping around").
Parameters
----------
N : int
number of vertices
K : int
number of edges
seed : hashable, optional
... | This function generates a directed lattice network with toroidal
boundary counditions (i.e. with ring-like "wrapping around").
Parameters
----------
N : int
number of vertices
K : int
number of edges
seed : hashable, optional
If None (default), use the np.random's global... |
def read_records(file):
"""Eagerly read a collection of amazon Record protobuf objects from file."""
records = []
for record_data in read_recordio(file):
record = Record()
record.ParseFromString(record_data)
records.append(record)
return records | Eagerly read a collection of amazon Record protobuf objects from file. |
def list_users(verbose=True, hashes=False):
'''
List user accounts
verbose : boolean
return all information
hashes : boolean
include NT HASH and LM HASH in verbose output
CLI Example:
.. code-block:: bash
salt '*' pdbedit.list
'''
users = {} if verbose else []... | List user accounts
verbose : boolean
return all information
hashes : boolean
include NT HASH and LM HASH in verbose output
CLI Example:
.. code-block:: bash
salt '*' pdbedit.list |
def response(self, parameters):
r"""Complex response of the Cole-Cole model::
:math:`\hat{\rho} = \rho_0 \left(1 - \sum_i m_i (1 - \frac{1}{1 + (j
\omega \tau_i)^c_i})\right)`
Parameters
----------
parameters: list or tuple or numpy.ndarray
Cole-Cole model pa... | r"""Complex response of the Cole-Cole model::
:math:`\hat{\rho} = \rho_0 \left(1 - \sum_i m_i (1 - \frac{1}{1 + (j
\omega \tau_i)^c_i})\right)`
Parameters
----------
parameters: list or tuple or numpy.ndarray
Cole-Cole model parameters: rho0, m, tau, c (all linear)
... |
def authenticate(devices, params, facet, check_only):
"""
Interactively authenticates a AuthenticateRequest using an attached U2F
device.
"""
for device in devices[:]:
try:
device.open()
except:
devices.remove(device)
try:
prompted = False
... | Interactively authenticates a AuthenticateRequest using an attached U2F
device. |
def set_server_callback(self, handle):
"""
Set up on_change events for bokeh server interactions.
"""
if self.on_events:
for event in self.on_events:
handle.on_event(event, self.on_event)
if self.on_changes:
for change in self.on_changes:
... | Set up on_change events for bokeh server interactions. |
def _ExecuteTransaction(self, transaction):
"""Get connection from pool and execute transaction."""
def Action(connection):
connection.cursor.execute("START TRANSACTION")
for query in transaction:
connection.cursor.execute(query["query"], query["args"])
connection.cursor.execute("COMM... | Get connection from pool and execute transaction. |
def rate(self):
"""Report the insertion rate in records per second"""
end = self._end_time if self._end_time else time.time()
return self._count / (end - self._start_time) | Report the insertion rate in records per second |
def adjustSize( self ):
"""
Adjusts the size of this node to support the length of its contents.
"""
cell = self.scene().cellWidth() * 2
minheight = cell
minwidth = 2 * cell
# fit to the grid size
metrics = QFontMetrics(QApplication.font())
... | Adjusts the size of this node to support the length of its contents. |
def __op(name, val, fmt=None, const=False, consume=0, produce=0):
"""
provides sensible defaults for a code, and registers it with the
__OPTABLE for lookup.
"""
name = name.lower()
# fmt can either be a str representing the struct to unpack, or a
# callable to do more complex unpacking. If... | provides sensible defaults for a code, and registers it with the
__OPTABLE for lookup. |
def bubble_sizes_ref(self, series):
"""
The Excel worksheet reference to the range containing the bubble
sizes for *series* (not including the column heading cell).
"""
top_row = self.series_table_row_offset(series) + 2
bottom_row = top_row + len(series) - 1
retur... | The Excel worksheet reference to the range containing the bubble
sizes for *series* (not including the column heading cell). |
def _do_request(self, url, params=None, data=None, headers=None):
"""
Realiza as requisições diversas utilizando a biblioteca requests,
tratando de forma genérica as exceções.
"""
if not headers:
headers = {'content-type': 'application/json'}
try:
... | Realiza as requisições diversas utilizando a biblioteca requests,
tratando de forma genérica as exceções. |
def pb2dict(obj):
"""
Takes a ProtoBuf Message obj and convertes it to a dict.
"""
adict = {}
if not obj.IsInitialized():
return None
for field in obj.DESCRIPTOR.fields:
if not getattr(obj, field.name):
continue
if not field.label == FD.LABEL_REPEATED:
... | Takes a ProtoBuf Message obj and convertes it to a dict. |
def get_log_entry_log_assignment_session(self, proxy):
"""Gets the session for assigning log entry to log mappings.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.logging.LogEntryLogAssignmentSession) - a
``LogEntryLogAssignmentSession``
raise: NullArgument - `... | Gets the session for assigning log entry to log mappings.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.logging.LogEntryLogAssignmentSession) - a
``LogEntryLogAssignmentSession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFailed - unable to c... |
def download(self, location, local_dir='.'):
'''Download content from bucket/prefix/location.
Location can be a directory or a file (e.g., my_dir or my_dir/my_image.tif)
If location is a directory, all files in the directory are
downloaded. If it is a file, then that file is dow... | Download content from bucket/prefix/location.
Location can be a directory or a file (e.g., my_dir or my_dir/my_image.tif)
If location is a directory, all files in the directory are
downloaded. If it is a file, then that file is downloaded.
Args:
location (str)... |
def delete(self, request, *args, **kwargs):
"""
Processes deletion of the specified instance.
:param request: the request instance.
:rtype: django.http.HttpResponse.
"""
#noinspection PyAttributeOutsideInit
self.object = self.get_object()
success_url = se... | Processes deletion of the specified instance.
:param request: the request instance.
:rtype: django.http.HttpResponse. |
def get_log(self, offset, count=10, callback=None):
'''
Retrieve log records from camera.
cmd: getLog
param:
offset: log offset for first record
count: number of records to return
'''
params = {'offset': offset, 'count': count}
return self.ex... | Retrieve log records from camera.
cmd: getLog
param:
offset: log offset for first record
count: number of records to return |
def _build_query_url(self, page = None, verbose = False):
"""
builds the url to call
"""
query = []
# # build the filters
# for afilter in self.filters.keys():
# value = self.filters[afilter]
# print"filter:%s value:%s" % (afilter,value)
# v... | builds the url to call |
def reboot(self, timeout=1):
"""Reboot the device"""
namespace = System.getServiceType("reboot")
uri = self.getControlURL(namespace)
self.execute(uri, namespace, "Reboot", timeout=timeout) | Reboot the device |
def select_token(request, scopes='', new=False):
"""
Presents the user with a selection of applicable tokens for the requested view.
"""
@tokens_required(scopes=scopes, new=new)
def _token_list(r, tokens):
context = {
'tokens': tokens,
'base_template': app_settings.E... | Presents the user with a selection of applicable tokens for the requested view. |
def google_storage_url(self, sat):
"""
Returns a google storage url the contains the scene provided.
:param sat:
Expects an object created by scene_interpreter method
:type sat:
dict
:returns:
(String) The URL to a google storage file
... | Returns a google storage url the contains the scene provided.
:param sat:
Expects an object created by scene_interpreter method
:type sat:
dict
:returns:
(String) The URL to a google storage file |
def updateUserRole(self,
user,
role):
"""
The Update User Role operation allows the administrator of an org
anization to update the role of a user within a portal.
Inputs:
role - Sets the user's role.
Roles are t... | The Update User Role operation allows the administrator of an org
anization to update the role of a user within a portal.
Inputs:
role - Sets the user's role.
Roles are the following:
org_user - Ability to add items, create groups, and
... |
def _one_projector(args: Dict[str, Any], index: int) -> Union[int, np.ndarray]:
"""Returns a projector onto the |1> subspace of the index-th qubit."""
num_shard_qubits = args['num_shard_qubits']
shard_num = args['shard_num']
if index >= num_shard_qubits:
return _kth_bit(shard_num, index - num_sh... | Returns a projector onto the |1> subspace of the index-th qubit. |
def rate_limits(self):
"""Returns a list of rate limit details."""
if not self._rate_limits:
self._rate_limits = utilities.get_rate_limits(self.response)
return self._rate_limits | Returns a list of rate limit details. |
def read_val(self, key:str) -> Union[List[float],Tuple[List[float],List[float]]]:
"Read a hyperparameter `key` in the optimizer dictionary."
val = [pg[key] for pg in self.opt.param_groups[::2]]
if is_tuple(val[0]): val = [o[0] for o in val], [o[1] for o in val]
return val | Read a hyperparameter `key` in the optimizer dictionary. |
def execute_no_results(self, sock_info, generator):
"""Execute all operations, returning no results (w=0).
"""
# Cannot have both unacknowledged write and bypass document validation.
if self.bypass_doc_val and sock_info.max_wire_version >= 4:
raise OperationFailure("Cannot se... | Execute all operations, returning no results (w=0). |
def stop_all(self):
"""
Stop all nodes
"""
pool = Pool(concurrency=3)
for node in self.nodes.values():
pool.append(node.stop)
yield from pool.join() | Stop all nodes |
def array_type(data_types, field):
"""
Allows conversion of Django ArrayField to SQLAlchemy Array.
Takes care of mapping the type of the array element.
"""
from sqlalchemy.dialects import postgresql
internal_type = field.base_field.get_internal_type()
# currently no support for multi-dimen... | Allows conversion of Django ArrayField to SQLAlchemy Array.
Takes care of mapping the type of the array element. |
def asof_locs(self, where, mask):
"""
Find the locations (indices) of the labels from the index for
every entry in the `where` argument.
As in the `asof` function, if the label (a particular entry in
`where`) is not in the index, the latest index label upto the
passed la... | Find the locations (indices) of the labels from the index for
every entry in the `where` argument.
As in the `asof` function, if the label (a particular entry in
`where`) is not in the index, the latest index label upto the
passed label is chosen and its index returned.
If all ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.