code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def bed_to_bedpe(bedfile, bedpefile, pairsbedfile=None, matesfile=None, ca=False, strand=False):
"""
This converts the bedfile to bedpefile, assuming the reads are from CA.
"""
fp = must_open(bedfile)
fw = must_open(bedpefile, "w")
if pairsbedfile:
fwpairs = must_open(pairsbedfile, "w")
... | This converts the bedfile to bedpefile, assuming the reads are from CA. |
def get_repository(self, entity_cls):
"""Retrieve a Repository for the Model with a live connection"""
entity_record = self._get_entity_by_class(entity_cls)
provider = self.get_provider(entity_record.provider_name)
return provider.get_repository(entity_record.entity_cls) | Retrieve a Repository for the Model with a live connection |
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
... | List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list... |
def update_device(self, device_id, **kwargs):
"""Update existing device in catalog.
.. code-block:: python
existing_device = api.get_device(...)
updated_device = api.update_device(
existing_device.id,
certificate_fingerprint = "something new"
... | Update existing device in catalog.
.. code-block:: python
existing_device = api.get_device(...)
updated_device = api.update_device(
existing_device.id,
certificate_fingerprint = "something new"
)
:param str device_id: The ID of the d... |
def plot_trajectory_with_elegans(
obs, width=350, height=350, config=None, grid=True, wireframe=False,
max_count=10, camera_position=(-22, 23, 32), camera_rotation=(-0.6, 0.5, 0.6),
plot_range=None):
"""
Generate a plot from received instance of TrajectoryObserver and show it
on IPyt... | Generate a plot from received instance of TrajectoryObserver and show it
on IPython notebook.
Parameters
----------
obs : TrajectoryObserver
TrajectoryObserver to render.
width : float, default 350
Width of the plotting area.
height : float, default 350
Height of the plo... |
def load_configuration_from_text_file(register, configuration_file):
'''Loading configuration from text files to register object
Parameters
----------
register : pybar.fei4.register object
configuration_file : string
Full path (directory and filename) of the configuration file. If na... | Loading configuration from text files to register object
Parameters
----------
register : pybar.fei4.register object
configuration_file : string
Full path (directory and filename) of the configuration file. If name is not given, reload configuration from file. |
def save_firefox_profile(self, remove_old=False):
"""Function to save the firefox profile to the permanant one"""
self.logger.info("Saving profile from %s to %s" % (self._profile.path, self._profile_path))
if remove_old:
if os.path.exists(self._profile_path):
try:
... | Function to save the firefox profile to the permanant one |
def _compute_betas_gwr(y, x, wi):
"""
compute MLE coefficients using iwls routine
Methods: p189, Iteratively (Re)weighted Least Squares (IWLS),
Fotheringham, A. S., Brunsdon, C., & Charlton, M. (2002).
Geographically weighted regression: the analysis of spatially varying relationships.
"""
... | compute MLE coefficients using iwls routine
Methods: p189, Iteratively (Re)weighted Least Squares (IWLS),
Fotheringham, A. S., Brunsdon, C., & Charlton, M. (2002).
Geographically weighted regression: the analysis of spatially varying relationships. |
def enable_audit_device(self, device_type, description=None, options=None, path=None):
"""Enable a new audit device at the supplied path.
The path can be a single word name or a more complex, nested path.
Supported methods:
PUT: /sys/audit/{path}. Produces: 204 (empty body)
... | Enable a new audit device at the supplied path.
The path can be a single word name or a more complex, nested path.
Supported methods:
PUT: /sys/audit/{path}. Produces: 204 (empty body)
:param device_type: Specifies the type of the audit device.
:type device_type: str | uni... |
def check_timeseries_id(self, dataset):
'''
Checks that if a variable exists for the time series id it has the appropriate attributes
:param netCDF4.Dataset dataset: An open netCDF dataset
'''
timeseries_ids = dataset.get_variables_by_attributes(cf_role='timeseries_id')
... | Checks that if a variable exists for the time series id it has the appropriate attributes
:param netCDF4.Dataset dataset: An open netCDF dataset |
def _AlignDecodedDataOffset(self, decoded_data_offset):
"""Aligns the encoded file with the decoded data offset.
Args:
decoded_data_offset (int): decoded data offset.
"""
self._file_object.seek(0, os.SEEK_SET)
self._decoder = self._GetDecoder()
self._decoded_data = b''
encoded_data_... | Aligns the encoded file with the decoded data offset.
Args:
decoded_data_offset (int): decoded data offset. |
def notify_slack(title, content, attachment_color="#4bb543", short_threshold=40, token=None,
channel=None, mention_user=None, **kwargs):
"""
Sends a slack notification and returns *True* on success. The communication with the slack API
might have some delays and is therefore handled by a thread. The... | Sends a slack notification and returns *True* on success. The communication with the slack API
might have some delays and is therefore handled by a thread. The format of the notification
depends on *content*. If it is a string, a simple text notification is sent. Otherwise, it
should be a dictionary whose f... |
def FileEntryExistsByPathSpec(self, path_spec):
"""Determines if a file entry for a path specification exists.
Args:
path_spec (PathSpec): a path specification.
Returns:
bool: True if the file entry exists, false otherwise.
"""
location = getattr(path_spec, 'location', None)
if lo... | Determines if a file entry for a path specification exists.
Args:
path_spec (PathSpec): a path specification.
Returns:
bool: True if the file entry exists, false otherwise. |
def stft(func=None, **kwparams):
"""
Short Time Fourier Transform block processor / phase vocoder wrapper.
This function can be used in many ways:
* Directly as a signal processor builder, wrapping a spectrum block/grain
processor function;
* Directly as a decorator to a block processor;
* Called with... | Short Time Fourier Transform block processor / phase vocoder wrapper.
This function can be used in many ways:
* Directly as a signal processor builder, wrapping a spectrum block/grain
processor function;
* Directly as a decorator to a block processor;
* Called without the ``func`` parameter for a partial ... |
def subfeature (feature_name, value_string, subfeature, subvalues, attributes = []):
""" Declares a subfeature.
feature_name: Root feature that is not a subfeature.
value_string: An optional value-string specifying which feature or
subfeature values this subfeature is spe... | Declares a subfeature.
feature_name: Root feature that is not a subfeature.
value_string: An optional value-string specifying which feature or
subfeature values this subfeature is specific to,
if any.
subfeature: The name of the subfeature ... |
def select_params_from_section_schema(section_schema, param_class=Param,
deep=False):
"""Selects the parameters of a config section schema.
:param section_schema: Configuration file section schema to use.
:return: Generator of params
"""
# pylint: disable=inva... | Selects the parameters of a config section schema.
:param section_schema: Configuration file section schema to use.
:return: Generator of params |
def _to_repeatmasker_string(pairwise_alignment, column_width=DEFAULT_COL_WIDTH,
m_name_width=DEFAULT_MAX_NAME_WIDTH):
"""
generate a repeatmasker formated representation of this pairwise alignment.
:param column_width: number of characters to output per line of alignment
:param m_na... | generate a repeatmasker formated representation of this pairwise alignment.
:param column_width: number of characters to output per line of alignment
:param m_name_width: truncate names on alignment lines to this length
(set to None for no truncation) |
def _make_y_title(self):
"""Make the Y-Axis title"""
if self._y_title:
yc = self.margin_box.top + self.view.height / 2
for i, title_line in enumerate(self._y_title, 1):
text = self.svg.node(
self.nodes['title'],
'text',
... | Make the Y-Axis title |
def check_bottleneck(text):
"""Avoid mixing metaphors about bottles and their necks.
source: Sir Ernest Gowers
source_url: http://bit.ly/1CQPH61
"""
err = "mixed_metaphors.misc.bottleneck"
msg = u"Mixed metaphor — bottles with big necks are easy to pass through."
list = [
"bigge... | Avoid mixing metaphors about bottles and their necks.
source: Sir Ernest Gowers
source_url: http://bit.ly/1CQPH61 |
def beacon_link(variant_obj, build=None):
"""Compose link to Beacon Network."""
build = build or 37
url_template = ("https://beacon-network.org/#/search?pos={this[position]}&"
"chrom={this[chromosome]}&allele={this[alternative]}&"
"ref={this[reference]}&rs=GRCh37")
... | Compose link to Beacon Network. |
def do_ams_put(endpoint, path, body, access_token, rformat="json", ds_min_version="3.0;NetFx"):
'''Do a AMS HTTP PUT request and return JSON.
Args:
endpoint (str): Azure Media Services Initial Endpoint.
path (str): Azure Media Services Endpoint Path.
body (str): Azure Media Services Con... | Do a AMS HTTP PUT request and return JSON.
Args:
endpoint (str): Azure Media Services Initial Endpoint.
path (str): Azure Media Services Endpoint Path.
body (str): Azure Media Services Content Body.
access_token (str): A valid Azure authentication token.
rformat (str): A req... |
def expand_macros(raw_text, macros):
"""
this gets called before the sakefile is parsed. it looks for
macros defined anywhere in the sakefile (the start of the line
is '#!') and then replaces all occurences of '$variable' with the
value defined in the macro. it then returns the contents of the
f... | this gets called before the sakefile is parsed. it looks for
macros defined anywhere in the sakefile (the start of the line
is '#!') and then replaces all occurences of '$variable' with the
value defined in the macro. it then returns the contents of the
file with the macros expanded. |
def add_group_member(self, grp_name, user):
"""
Add the given user to the named group.
Both group and user must already exist for this to succeed.
Args:
name (string): Name of group.
user_name (string): User to add to group.
Raises:
requests... | Add the given user to the named group.
Both group and user must already exist for this to succeed.
Args:
name (string): Name of group.
user_name (string): User to add to group.
Raises:
requests.HTTPError on failure. |
def url(self):
"""The URL as a string of the resource."""
if not self._url[2].endswith('/'):
self._url[2] += '/'
return RestURL.url.__get__(self) | The URL as a string of the resource. |
def _set_session_style(self, v, load=False):
"""
Setter method for session_style, mapped from YANG variable /mpls_state/rsvp/sessions/psbs/session_style (session-reservation-style)
If this variable is read-only (config: false) in the
source YANG file, then _set_session_style is considered as a private
... | Setter method for session_style, mapped from YANG variable /mpls_state/rsvp/sessions/psbs/session_style (session-reservation-style)
If this variable is read-only (config: false) in the
source YANG file, then _set_session_style is considered as a private
method. Backends looking to populate this variable sho... |
def _ostaunicode(src):
# type: (str) -> bytes
'''
Internal function to create an OSTA byte string from a source string.
'''
if have_py_3:
bytename = src
else:
bytename = src.decode('utf-8') # type: ignore
try:
enc = bytename.encode('latin-1')
encbyte = b'\x0... | Internal function to create an OSTA byte string from a source string. |
def check_layer(layer, has_geometry=True):
"""Helper to check layer validity.
This function wil; raise InvalidLayerError if the layer is invalid.
:param layer: The layer to check.
:type layer: QgsMapLayer
:param has_geometry: If the layer must have a geometry. True by default.
If it's a r... | Helper to check layer validity.
This function wil; raise InvalidLayerError if the layer is invalid.
:param layer: The layer to check.
:type layer: QgsMapLayer
:param has_geometry: If the layer must have a geometry. True by default.
If it's a raster layer, we will no check this parameter. If w... |
def cli(env, columns, sortby, volume_id):
"""List ACLs."""
block_manager = SoftLayer.BlockStorageManager(env.client)
access_list = block_manager.get_block_volume_access_list(
volume_id=volume_id)
table = formatting.Table(columns.columns)
table.sortby = sortby
for key, type_name in [('al... | List ACLs. |
def _select_best_remaining_qubit(self, prog_qubit):
"""
Select the best remaining hardware qubit for the next program qubit.
"""
reliab_store = {}
for hw_qubit in self.available_hw_qubits:
reliab = 1
for n in self.prog_graph.neighbors(prog_qubit):
... | Select the best remaining hardware qubit for the next program qubit. |
def _fix_labels(self):
"""For each system, make sure tag _0 is the brightest, and make sure
system 0 contains the brightest star in the highest-resolution image
"""
for s in self.systems:
mag0 = np.inf
n0 = None
for n in self.get_system(s):
... | For each system, make sure tag _0 is the brightest, and make sure
system 0 contains the brightest star in the highest-resolution image |
def fetch(self, addon_id, data={}, **kwargs):
""""
Fetch addon for given Id
Args:
addon_id : Id for which addon object has to be retrieved
Returns:
addon dict for given subscription Id
"""
return super(Addon, self).fetch(addon_id, data, **kwargs) | Fetch addon for given Id
Args:
addon_id : Id for which addon object has to be retrieved
Returns:
addon dict for given subscription Id |
def MakeExecutableTemplate(self, output_file=None):
"""Windows templates also include the nanny."""
super(WindowsClientBuilder,
self).MakeExecutableTemplate(output_file=output_file)
self.MakeBuildDirectory()
self.BuildWithPyInstaller()
# Get any dll's that pyinstaller forgot:
for mod... | Windows templates also include the nanny. |
def plot_station_mapping(
target_latitude,
target_longitude,
isd_station,
distance_meters,
target_label="target",
): # pragma: no cover
""" Plots this mapping on a map."""
try:
import matplotlib.pyplot as plt
except ImportError:
raise ImportError("Plotting requires matpl... | Plots this mapping on a map. |
def call_bad_cb(self, tb):
"""
If bad_cb returns True then keep it
:param tb: traceback that caused exception
:return:
"""
with LiveExecution.lock:
if self.bad_cb and not self.bad_cb(tb):
self.bad_cb = None | If bad_cb returns True then keep it
:param tb: traceback that caused exception
:return: |
def getExtensionArgs(self):
"""Get a dictionary of unqualified simple registration
arguments representing this request.
This method is essentially the inverse of
C{L{parseExtensionArgs}}. This method serializes the simple
registration request fields.
@rtype: {str:str}
... | Get a dictionary of unqualified simple registration
arguments representing this request.
This method is essentially the inverse of
C{L{parseExtensionArgs}}. This method serializes the simple
registration request fields.
@rtype: {str:str} |
def process_index(self, url, page):
"""Process the contents of a PyPI page"""
def scan(link):
# Process a URL to see if it's for a package page
if link.startswith(self.index_url):
parts = list(map(
urllib.parse.unquote, link[len(self.index_url... | Process the contents of a PyPI page |
def verify_exif(filename):
'''
Check that image file has the required EXIF fields.
Incompatible files will be ignored server side.
'''
# required tags in IFD name convention
required_exif = required_fields()
exif = ExifRead(filename)
required_exif_exist = exif.fields_exist(required_exif)... | Check that image file has the required EXIF fields.
Incompatible files will be ignored server side. |
def inspect_tables(conn, database_metadata):
" List tables and their row counts, excluding uninteresting tables. "
tables = {}
table_names = [
r["name"]
for r in conn.execute(
'select * from sqlite_master where type="table"'
)
]
for table in table_names:
... | List tables and their row counts, excluding uninteresting tables. |
def schedule_job(self, job):
"""
schedule a job to the type of workers spawned by self.start_workers.
:param job: the job to schedule for running.
:return:
"""
l = _reraise_with_traceback(job.get_lambda_to_execute())
future = self.workers.submit(l, update_progr... | schedule a job to the type of workers spawned by self.start_workers.
:param job: the job to schedule for running.
:return: |
def assert_reset(self, asserted):
"""Assert or de-assert target reset line"""
try:
self._invalidate_cached_registers()
self._link.assert_reset(asserted)
except DAPAccess.Error as exc:
six.raise_from(self._convert_exception(exc), exc) | Assert or de-assert target reset line |
def organization_users(self, id, permission_set=None, role=None, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/users#list-users"
api_path = "/api/v2/organizations/{id}/users.json"
api_path = api_path.format(id=id)
api_query = {}
if "query" in kwargs.keys():
... | https://developer.zendesk.com/rest_api/docs/core/users#list-users |
def _repr_categories_info(self):
"""
Returns a string representation of the footer.
"""
category_strs = self._repr_categories()
dtype = getattr(self.categories, 'dtype_str',
str(self.categories.dtype))
levheader = "Categories ({length}, {dtype}):... | Returns a string representation of the footer. |
def av(self, data, lon_str=LON_STR, lat_str=LAT_STR,
land_mask_str=LAND_MASK_STR, sfc_area_str=SFC_AREA_STR):
"""Time-average of region-averaged data.
Parameters
----------
data : xarray.DataArray
The array to compute the regional time-average of
lat_str, ... | Time-average of region-averaged data.
Parameters
----------
data : xarray.DataArray
The array to compute the regional time-average of
lat_str, lon_str, land_mask_str, sfc_area_str : str, optional
The name of the latitude, longitude, land mask, and surface area
... |
def convert(outputfile, inputfile, to_format, from_format):
"""
Convert pretrained word embedding file in one format to another.
"""
emb = word_embedding.WordEmbedding.load(
inputfile, format=_input_choices[from_format][1],
binary=_input_choices[from_format][2])
emb.save(outputfile, ... | Convert pretrained word embedding file in one format to another. |
def liftover(args):
"""
%prog liftover lobstr_v3.0.2_hg38_ref.bed hg38.upper.fa
LiftOver CODIS/Y-STR markers.
"""
p = OptionParser(liftover.__doc__)
p.add_option("--checkvalid", default=False, action="store_true",
help="Check minscore, period and length")
opts, args = p.pars... | %prog liftover lobstr_v3.0.2_hg38_ref.bed hg38.upper.fa
LiftOver CODIS/Y-STR markers. |
def __safe_errback(self, room_data, err_condition, err_text):
"""
Safe use of the callback method, to avoid errors propagation
:param room_data: A RoomData object
:param err_condition: Category of error
:param err_text: Description of the error
"""
method = room_... | Safe use of the callback method, to avoid errors propagation
:param room_data: A RoomData object
:param err_condition: Category of error
:param err_text: Description of the error |
def log_errors(f, self, *args, **kwargs):
"""decorator to log unhandled exceptions raised in a method.
For use wrapping on_recv callbacks, so that exceptions
do not cause the stream to be closed.
"""
try:
return f(self, *args, **kwargs)
except Exception:
self.log.error("Unca... | decorator to log unhandled exceptions raised in a method.
For use wrapping on_recv callbacks, so that exceptions
do not cause the stream to be closed. |
def stop_socket(self, conn_key):
"""Stop a websocket given the connection key
:param conn_key: Socket connection key
:type conn_key: string
:returns: connection key string if successful, False otherwise
"""
if conn_key not in self._conns:
return
# d... | Stop a websocket given the connection key
:param conn_key: Socket connection key
:type conn_key: string
:returns: connection key string if successful, False otherwise |
def readlines(self):
"""Returns a list of all lines (optionally parsed) in the file."""
if self.grammar:
tot = []
# Used this way instead of a 'for' loop against
# self.file.readlines() so that there wasn't two copies of the file
# in memory.
... | Returns a list of all lines (optionally parsed) in the file. |
def is_nameserver(self, path):
'''Is the node pointed to by @ref path a name server (specialisation
of directory nodes)?
'''
node = self.get_node(path)
if not node:
return False
return node.is_nameserver | Is the node pointed to by @ref path a name server (specialisation
of directory nodes)? |
def get_fermi_interextrapolated(self, c, T, warn=True, c_ref=1e10, **kwargs):
"""
Similar to get_fermi except that when get_fermi fails to converge,
an interpolated or extrapolated fermi (depending on c) is returned with
the assumption that the fermi level changes linearly with log(abs(c... | Similar to get_fermi except that when get_fermi fails to converge,
an interpolated or extrapolated fermi (depending on c) is returned with
the assumption that the fermi level changes linearly with log(abs(c)).
Args:
c (float): doping concentration in 1/cm3. c<0 represents n-type
... |
def compile(self, X, verbose=False):
"""method to validate and prepare data-dependent parameters
Parameters
---------
X : array-like
Input dataset
verbose : bool
whether to show warnings
Returns
-------
None
"""
i... | method to validate and prepare data-dependent parameters
Parameters
---------
X : array-like
Input dataset
verbose : bool
whether to show warnings
Returns
-------
None |
def apply_relationships(self, data, obj):
"""Apply relationship provided by data to obj
:param dict data: data provided by the client
:param DeclarativeMeta obj: the sqlalchemy object to plug relationships to
:return boolean: True if relationship have changed else False
"""
... | Apply relationship provided by data to obj
:param dict data: data provided by the client
:param DeclarativeMeta obj: the sqlalchemy object to plug relationships to
:return boolean: True if relationship have changed else False |
def _parse_caps_bank(bank):
'''
Parse the <bank> element of the connection capabilities XML.
'''
result = {
'id': int(bank.get('id')),
'level': int(bank.get('level')),
'type': bank.get('type'),
'size': "{} {}".format(bank.get('size'), bank.get('unit')),
'cpus': ba... | Parse the <bank> element of the connection capabilities XML. |
def water(target, temperature='pore.temperature', salinity='pore.salinity'):
r"""
Calculates vapor pressure of pure water or seawater given by [1] based on
Raoult's law. The pure water vapor pressure is given by [2]
Parameters
----------
target : OpenPNM Object
The object for which thes... | r"""
Calculates vapor pressure of pure water or seawater given by [1] based on
Raoult's law. The pure water vapor pressure is given by [2]
Parameters
----------
target : OpenPNM Object
The object for which these values are being calculated. This
controls the length of the calculate... |
def sort_protein_group(pgroup, sortfunctions, sortfunc_index):
"""Recursive function that sorts protein group by a number of sorting
functions."""
pgroup_out = []
subgroups = sortfunctions[sortfunc_index](pgroup)
sortfunc_index += 1
for subgroup in subgroups:
if len(subgroup) > 1 and sor... | Recursive function that sorts protein group by a number of sorting
functions. |
def get_kgXref_hg19(self):
""" Get UCSC kgXref table for Build 37.
Returns
-------
pandas.DataFrame
kgXref table if loading was successful, else None
"""
if self._kgXref_hg19 is None:
self._kgXref_hg19 = self._load_kgXref(self._get_path_kgXref_hg1... | Get UCSC kgXref table for Build 37.
Returns
-------
pandas.DataFrame
kgXref table if loading was successful, else None |
def ReadCronJobs(self, cronjob_ids=None, cursor=None):
"""Reads all cronjobs from the database."""
query = ("SELECT job, UNIX_TIMESTAMP(create_time), enabled, "
"forced_run_requested, last_run_status, "
"UNIX_TIMESTAMP(last_run_time), current_run_id, state, "
"UNIX_TIMESTA... | Reads all cronjobs from the database. |
def overwrite_file_check(args, filename):
"""If filename exists, overwrite or modify it to be unique."""
if not args['overwrite'] and os.path.exists(filename):
# Confirm overwriting of the file, or modify filename
if args['no_overwrite']:
overwrite = False
else:
t... | If filename exists, overwrite or modify it to be unique. |
def calculate_batch_normalization_output_shapes(operator):
'''
Allowed input/output patterns are
1. [N, C] ---> [N, C]
2. [N, C, H, W] ---> [N, C, H, W]
This operator just uses the operator input shape as its output shape.
'''
check_input_and_output_numbers(operator, input_count_ran... | Allowed input/output patterns are
1. [N, C] ---> [N, C]
2. [N, C, H, W] ---> [N, C, H, W]
This operator just uses the operator input shape as its output shape. |
def _set_labels(self, catalogue):
"""Returns a dictionary of the unique labels in `catalogue` and the
count of all tokens associated with each, and sets the record
of each Text to its corresponding label.
Texts that do not have a label specified are set to the empty
string.
... | Returns a dictionary of the unique labels in `catalogue` and the
count of all tokens associated with each, and sets the record
of each Text to its corresponding label.
Texts that do not have a label specified are set to the empty
string.
Token counts are included in the results... |
def pin_assets(self, file_or_dir_path: Path) -> List[Dict[str, str]]:
"""
Return a dict containing the IPFS hash, file name, and size of a file.
"""
if file_or_dir_path.is_dir():
asset_data = [dummy_ipfs_pin(path) for path in file_or_dir_path.glob("*")]
elif file_or_d... | Return a dict containing the IPFS hash, file name, and size of a file. |
def register_component(self, path):
"""
Registers a Component using given path.
Usage::
>>> manager = Manager()
>>> manager.register_component("tests_component_a.rc")
True
>>> manager.components
{u'core.tests_component_a': <manager.co... | Registers a Component using given path.
Usage::
>>> manager = Manager()
>>> manager.register_component("tests_component_a.rc")
True
>>> manager.components
{u'core.tests_component_a': <manager.components_manager.Profile object at 0x11c9eb0>}
... |
def get_features(cls, entry):
"""
get list of `models.Feature` from XML node entry
:param entry: XML node entry
:return: list of :class:`pyuniprot.manager.models.Feature`
"""
features = []
for feature in entry.iterfind("./feature"):
feature_dict = {... | get list of `models.Feature` from XML node entry
:param entry: XML node entry
:return: list of :class:`pyuniprot.manager.models.Feature` |
def get_sort_limit():
""" returns the 'sort_limit' from the request
"""
limit = _.convert(get("sort_limit"), _.to_int)
if (limit < 1):
limit = None # catalog raises IndexError if limit < 1
return limit | returns the 'sort_limit' from the request |
def _match_iter_generic(self, path_elements, start_at):
"""Implementation of match_iter for >1 self.elements"""
length = len(path_elements)
# If bound to start, we stop searching at the first element
if self.bound_start:
end = 1
else:
end = length - self.... | Implementation of match_iter for >1 self.elements |
def point_plane_distance(points,
plane_normal,
plane_origin=[0.0, 0.0, 0.0]):
"""
The minimum perpendicular distance of a point to a plane.
Parameters
-----------
points: (n, 3) float, points in space
plane_normal: (3,) float, normal vecto... | The minimum perpendicular distance of a point to a plane.
Parameters
-----------
points: (n, 3) float, points in space
plane_normal: (3,) float, normal vector
plane_origin: (3,) float, plane origin in space
Returns
------------
distances: (n,) float, distance from point to pl... |
def add_edge(self, vertex1, vertex2, multicolor, merge=True, data=None):
""" Creates a new :class:`bg.edge.BGEdge` object from supplied information and adds it to current instance of :class:`BreakpointGraph`.
Proxies a call to :meth:`BreakpointGraph._BreakpointGraph__add_bgedge` method.
:param... | Creates a new :class:`bg.edge.BGEdge` object from supplied information and adds it to current instance of :class:`BreakpointGraph`.
Proxies a call to :meth:`BreakpointGraph._BreakpointGraph__add_bgedge` method.
:param vertex1: first vertex instance out of two in current :class:`BreakpointGraph`
... |
def _get_contours(self):
"""
Returns a list of contours in the path, as BezierPath objects.
A contour is a sequence of lines and curves separated from the next contour by a MOVETO.
For example, the glyph "o" has two contours: the inner circle and the outer circle.
"""
# O... | Returns a list of contours in the path, as BezierPath objects.
A contour is a sequence of lines and curves separated from the next contour by a MOVETO.
For example, the glyph "o" has two contours: the inner circle and the outer circle. |
def keys(self, element=None, mode=None):
r"""
This subclass works exactly like ``keys`` when no arguments are passed,
but optionally accepts an ``element`` and/or a ``mode``, which filters
the output to only the requested keys.
The default behavior is exactly equivalent to the n... | r"""
This subclass works exactly like ``keys`` when no arguments are passed,
but optionally accepts an ``element`` and/or a ``mode``, which filters
the output to only the requested keys.
The default behavior is exactly equivalent to the normal ``keys``
method.
Parameter... |
def mail_message(smtp_server, message, from_address, rcpt_addresses):
"""
Send mail using smtp.
"""
if smtp_server[0] == '/':
# Sending the message with local sendmail
p = os.popen(smtp_server, 'w')
p.write(message)
p.close()
else:
# Sending the message using ... | Send mail using smtp. |
def pre(*content, sep='\n'):
"""
Make mono-width text block (Markdown)
:param content:
:param sep:
:return:
"""
return _md(_join(*content, sep=sep), symbols=MD_SYMBOLS[3]) | Make mono-width text block (Markdown)
:param content:
:param sep:
:return: |
def lookup(cls, backend, obj):
"""
Given an object, lookup the corresponding customized option
tree if a single custom tree is applicable.
"""
ids = set([el for el in obj.traverse(lambda x: x.id) if el is not None])
if len(ids) == 0:
raise Exception("Object do... | Given an object, lookup the corresponding customized option
tree if a single custom tree is applicable. |
def geojson_polygon_to_mask(feature, shape, lat_idx, lon_idx):
"""Convert a GeoJSON polygon feature to a numpy array
Args:
feature (pygeoj.Feature): polygon feature to draw
shape (tuple(int, int)): shape of 2D target numpy array to draw polygon in
lat_idx (func): function converting a l... | Convert a GeoJSON polygon feature to a numpy array
Args:
feature (pygeoj.Feature): polygon feature to draw
shape (tuple(int, int)): shape of 2D target numpy array to draw polygon in
lat_idx (func): function converting a latitude to the (fractional) row index in the map
lon_idx (func... |
def mark_error(self, dispatch, error_log, message_cls):
"""Marks a dispatch as having error or consequently as failed
if send retry limit for that message type is exhausted.
Should be used within send().
:param Dispatch dispatch: a Dispatch
:param str error_log: error message
... | Marks a dispatch as having error or consequently as failed
if send retry limit for that message type is exhausted.
Should be used within send().
:param Dispatch dispatch: a Dispatch
:param str error_log: error message
:param MessageBase message_cls: MessageBase heir |
def lookup(values, name=None):
"""
Creates the grammar for a Lookup (L) field, accepting only values from a
list.
Like in the Alphanumeric field, the result will be stripped of all heading
and trailing whitespaces.
:param values: values allowed
:param name: name for the field
:return: ... | Creates the grammar for a Lookup (L) field, accepting only values from a
list.
Like in the Alphanumeric field, the result will be stripped of all heading
and trailing whitespaces.
:param values: values allowed
:param name: name for the field
:return: grammar for the lookup field |
def _call(self, x, out=None):
"""Multiply ``x`` and write to ``out`` if given."""
if out is None:
return x * self.multiplicand
elif not self.__range_is_field:
if self.__domain_is_field:
out.lincomb(x, self.multiplicand)
else:
ou... | Multiply ``x`` and write to ``out`` if given. |
def u2ver(self):
"""
Get the major/minor version of the urllib2 lib.
@return: The urllib2 version.
@rtype: float
"""
try:
part = urllib2.__version__.split('.', 1)
return float('.'.join(part))
except Exception, e:
log.exception... | Get the major/minor version of the urllib2 lib.
@return: The urllib2 version.
@rtype: float |
def callback(msg, _):
"""Callback function called by libnl upon receiving messages from the kernel.
Positional arguments:
msg -- nl_msg class instance containing the data sent by the kernel.
Returns:
An integer, value of NL_OK. It tells libnl to proceed with processing the next kernel message.
... | Callback function called by libnl upon receiving messages from the kernel.
Positional arguments:
msg -- nl_msg class instance containing the data sent by the kernel.
Returns:
An integer, value of NL_OK. It tells libnl to proceed with processing the next kernel message. |
def find_templates(input_dir):
"""
_find_templates_
traverse the input_dir structure and return a list
of template files ending with .mustache
:param input_dir: Path to start recursive search for
mustache templates
:returns: List of file paths corresponding to templates
"""
temp... | _find_templates_
traverse the input_dir structure and return a list
of template files ending with .mustache
:param input_dir: Path to start recursive search for
mustache templates
:returns: List of file paths corresponding to templates |
def _handle_result(self, result):
"""Mark the result as completed, insert the `CompiledResultNode` into
the manifest, and mark any descendants (potentially with a 'cause' if
the result was an ephemeral model) as skipped.
"""
is_ephemeral = result.node.is_ephemeral_model
i... | Mark the result as completed, insert the `CompiledResultNode` into
the manifest, and mark any descendants (potentially with a 'cause' if
the result was an ephemeral model) as skipped. |
def fill(self, color, start=0, end=-1):
"""Fill the entire strip with RGB color tuple"""
start = max(start, 0)
if end < 0 or end >= self.numLEDs:
end = self.numLEDs - 1
for led in range(start, end + 1): # since 0-index include end in range
self._set_base(led, col... | Fill the entire strip with RGB color tuple |
def set_widgets(self):
"""Set widgets on the Source tab."""
# Just set values based on existing keywords
source = self.parent.get_existing_keyword('source')
if source or source == 0:
self.leSource.setText(source)
else:
self.leSource.clear()
source... | Set widgets on the Source tab. |
def find_files(self):
"""
Find all file paths for publishing, yield (urlname, kwargs)
"""
# yield blueprint paths first
if getattr(self, 'blueprint_name', None):
for path in walk_directory(os.path.join(self.path, self.blueprint_name), ignore=self.project.EXCLUDES):
... | Find all file paths for publishing, yield (urlname, kwargs) |
def get_value(self, spreadsheet_id: str, range_name: str) -> dict:
"""
get value by range
:param spreadsheet_id:
:param range_name:
:return:
"""
service = self.__get_service()
result = service.spreadsheets().values().get(spreadsheetId=spreadsheet_id, range... | get value by range
:param spreadsheet_id:
:param range_name:
:return: |
def get_hmac(password):
"""Returns a Base64 encoded HMAC+SHA512 of the password signed with
the salt specified by ``SECURITY_PASSWORD_SALT``.
:param password: The password to sign
"""
salt = _security.password_salt
if salt is None:
raise RuntimeError(
'The configuration val... | Returns a Base64 encoded HMAC+SHA512 of the password signed with
the salt specified by ``SECURITY_PASSWORD_SALT``.
:param password: The password to sign |
def preprocess(string):
"""
Preprocess string to transform all diacritics and remove other special characters than appropriate
:param string:
:return:
"""
string = unicode(string, encoding="utf-8")
return regex.sub('', string).encode('utf-8') | Preprocess string to transform all diacritics and remove other special characters than appropriate
:param string:
:return: |
def most_read_creators_card(num=10):
"""
Displays a card showing the Creators who have the most Readings
associated with their Publications.
In spectator_core tags, rather than spectator_reading so it can still be
used on core pages, even if spectator_reading isn't installed.
"""
if spectat... | Displays a card showing the Creators who have the most Readings
associated with their Publications.
In spectator_core tags, rather than spectator_reading so it can still be
used on core pages, even if spectator_reading isn't installed. |
def to_datetime(date_or_datetime):
"""
Convert a date object to a datetime object,
or return as it is if it's not a date object.
:param date_or_datetime: date or datetime object
:return: a datetime object
"""
if isinstance(date_or_datetime, date) and \
not isinstance(date_or_dat... | Convert a date object to a datetime object,
or return as it is if it's not a date object.
:param date_or_datetime: date or datetime object
:return: a datetime object |
def profiler(sorting=('tottime',), stripDirs=True,
limit=20, path='', autoclean=True):
"""
Creates a profile wrapper around a method to time out
all the operations that it runs through. For more
information, look into the hotshot Profile documentation
online for the built-in Python... | Creates a profile wrapper around a method to time out
all the operations that it runs through. For more
information, look into the hotshot Profile documentation
online for the built-in Python package.
:param sorting <tuple> ( <key>, .. )
:param stripDirs <bool>
:param ... |
def as_set(self, include_weak=False):
"""Convert the `ETags` object into a python set. Per default all the
weak etags are not part of this set."""
rv = set(self._strong)
if include_weak:
rv.update(self._weak)
return rv | Convert the `ETags` object into a python set. Per default all the
weak etags are not part of this set. |
def get_ISSNs(self):
"""
Get list of VALID ISSNs (``022a``).
Returns:
list: List with *valid* ISSN strings.
"""
invalid_issns = set(self.get_invalid_ISSNs())
return [
self._clean_isbn(issn)
for issn in self["022a"]
if self... | Get list of VALID ISSNs (``022a``).
Returns:
list: List with *valid* ISSN strings. |
def compute_samples(channels, nsamples=None):
'''
create a generator which computes the samples.
essentially it creates a sequence of the sum of each function in the channel
at each sample in the file for each channel.
'''
return islice(izip(*(imap(sum, izip(*channel)) for channel in channels)),... | create a generator which computes the samples.
essentially it creates a sequence of the sum of each function in the channel
at each sample in the file for each channel. |
def grid_str(self, path=None, start=None, end=None,
border=True, start_chr='s', end_chr='e',
path_chr='x', empty_chr=' ', block_chr='#',
show_weight=False):
"""
create a printable string from the grid using ASCII characters
:param path: list of... | create a printable string from the grid using ASCII characters
:param path: list of nodes that show the path
:param start: start node
:param end: end node
:param border: create a border around the grid
:param start_chr: character for the start (default "s")
:param end_ch... |
def field2length(self, field, **kwargs):
"""Return the dictionary of OpenAPI field attributes for a set of
:class:`Length <marshmallow.validators.Length>` validators.
:param Field field: A marshmallow field.
:rtype: dict
"""
attributes = {}
validators = [
... | Return the dictionary of OpenAPI field attributes for a set of
:class:`Length <marshmallow.validators.Length>` validators.
:param Field field: A marshmallow field.
:rtype: dict |
def libvlc_video_set_logo_int(p_mi, option, value):
'''Set logo option as integer. Options that take a different type value
are ignored.
Passing libvlc_logo_enable as option value has the side effect of
starting (arg !0) or stopping (arg 0) the logo filter.
@param p_mi: libvlc media player instance.... | Set logo option as integer. Options that take a different type value
are ignored.
Passing libvlc_logo_enable as option value has the side effect of
starting (arg !0) or stopping (arg 0) the logo filter.
@param p_mi: libvlc media player instance.
@param option: logo option to set, values of libvlc_vi... |
def select_name(source, name):
'''
Yields all the elements with the given name
source - if an element, starts with all child elements in order; can also be any other iterator
name - will yield only elements with this name
'''
return filter(lambda x: x.xml_name == name, select_elements(source)) | Yields all the elements with the given name
source - if an element, starts with all child elements in order; can also be any other iterator
name - will yield only elements with this name |
def with_preference_param(self):
"""Add the preference param to the ES request and return a new Search.
The preference param avoids the bouncing effect with multiple
replicas, documented on ES documentation.
See: https://www.elastic.co/guide/en/elasticsearch/guide/current
/_sear... | Add the preference param to the ES request and return a new Search.
The preference param avoids the bouncing effect with multiple
replicas, documented on ES documentation.
See: https://www.elastic.co/guide/en/elasticsearch/guide/current
/_search_options.html#_preference for more informa... |
def glow_hparams():
"""Glow Hparams."""
hparams = common_hparams.basic_params1()
hparams.clip_grad_norm = None
hparams.weight_decay = 0.0
hparams.learning_rate_constant = 3e-4
hparams.batch_size = 32
# can be prev_level, prev_step or normal.
# see: glow_ops.merge_level_and_latent_dist
hparams.add_hpar... | Glow Hparams. |
def validate_name(self, name, agent):
"""
Finds the modification of name which is not yet in the list
:param name: the (new) name for the agent
:param agent: the agent instance to allow the same name as the previous one if necessary
:return: the best modification of name not yet ... | Finds the modification of name which is not yet in the list
:param name: the (new) name for the agent
:param agent: the agent instance to allow the same name as the previous one if necessary
:return: the best modification of name not yet in a listwidget |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.