positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def downloadTo(self, href, localpath):
"""
Download file to localstorage
:param href: remote path
:param localpath: local path
:return: response
"""
for iTry in range(TRYINGS):
logger.info(u("downloadTo(%s): %s %s") % (iTry, href, localpath))
... | Download file to localstorage
:param href: remote path
:param localpath: local path
:return: response |
def _p_iteration(self, P, Bp_solver, Vm, Va, pvpq):
""" Performs a P iteration, updates Va.
"""
dVa = -Bp_solver.solve(P)
# Update voltage.
Va[pvpq] = Va[pvpq] + dVa
V = Vm * exp(1j * Va)
return V, Vm, Va | Performs a P iteration, updates Va. |
def change_type(self, cls):
"""
Change type of diagram in this chart.
Accepts one of classes which extend Diagram.
"""
target_type = cls._type
target = self._embedded.createInstance(target_type)
self._embedded.setDiagram(target)
return cls(target) | Change type of diagram in this chart.
Accepts one of classes which extend Diagram. |
def source_loader(self, source_paths, create_missing_tables=True):
"""Load source from 3 csv files.
First file should contain global settings:
* ``native_lagnauge,languages`` header on first row
* appropriate values on following rows
Example::
native_lagnauge,lang... | Load source from 3 csv files.
First file should contain global settings:
* ``native_lagnauge,languages`` header on first row
* appropriate values on following rows
Example::
native_lagnauge,languages
ru,ru
,en
Second file should contain ... |
def autoreconnect(self, sleep=1, attempt=3, exponential=True, jitter=5):
"""
Tries to reconnect with some delay:
exponential=False: up to `attempt` times with `sleep` seconds between
each try
exponential=True: up to `attempt` times with exponential growing `sleep`
and r... | Tries to reconnect with some delay:
exponential=False: up to `attempt` times with `sleep` seconds between
each try
exponential=True: up to `attempt` times with exponential growing `sleep`
and random delay in range 1..`jitter` (exponential backoff)
:param sleep: time to sleep ... |
def generate_security_hash(self, content_type, object_pk, timestamp):
"""
Generate a HMAC security hash from the provided info.
"""
info = (content_type, object_pk, timestamp)
key_salt = "django.contrib.forms.CommentSecurityForm"
value = "-".join(info)
return salt... | Generate a HMAC security hash from the provided info. |
def clear_url(self):
"""Removes the url.
raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.repository.AssetConten... | Removes the url.
raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.* |
def is_ipaddress(hostname):
"""Detects whether the hostname given is an IP address.
:param str hostname: Hostname to examine.
:return: True if the hostname is an IP address, False otherwise.
"""
if six.PY3 and isinstance(hostname, bytes):
# IDN A-label bytes are ASCII compatible.
ho... | Detects whether the hostname given is an IP address.
:param str hostname: Hostname to examine.
:return: True if the hostname is an IP address, False otherwise. |
def idaunpack(buf):
"""
Special data packing format, used in struct definitions, and .id2 files
sdk functions: pack_dd etc.
"""
buf = bytearray(buf)
def nextval(o):
val = buf[o] ; o += 1
if val == 0xff: # 32 bit value
val, = struct.unpack_from(">L", buf,... | Special data packing format, used in struct definitions, and .id2 files
sdk functions: pack_dd etc. |
def json_to_pages(json, user, preferred_lang=None):
"""
Attept to create/update pages from JSON string json. user is the
user that will be used when creating a page if a page's original
author can't be found. preferred_lang is the language code of the
slugs to include in error messages (defaults t... | Attept to create/update pages from JSON string json. user is the
user that will be used when creating a page if a page's original
author can't be found. preferred_lang is the language code of the
slugs to include in error messages (defaults to
settings.PAGE_DEFAULT_LANGUAGE).
Returns (errors, pag... |
def get_password_from_keyring(entry=None, username=None):
"""
:param entry: The entry in the keychain. This is a caller specific key.
:param username: The username to get the password for. Default is the current user.
"""
if username is None:
username = get_username()
has_keychain ... | :param entry: The entry in the keychain. This is a caller specific key.
:param username: The username to get the password for. Default is the current user. |
def finish():
# type: () -> None
""" Merge current feature into develop. """
pretend = context.get('pretend', False)
if not pretend and (git.staged() or git.unstaged()):
log.err(
"You have uncommitted changes in your repo!\n"
"You need to stash them before you merge the ... | Merge current feature into develop. |
def count(self, value):
"""S.count(value) -> integer -- return number of occurrences of value"""
from pcapkit.protocols.protocol import Protocol
try:
flag = issubclass(value, Protocol)
except TypeError:
flag = issubclass(type(value), Protocol)
if flag or i... | S.count(value) -> integer -- return number of occurrences of value |
def plot_similarity(ensemble, ax=None, jitter=0.1,
scatter_kw=dict(), line_kw=dict()):
"""Plots similarity across optimization runs as a function of model rank.
Parameters
----------
ensemble : Ensemble object
holds optimization results across a range of model ranks
ax :... | Plots similarity across optimization runs as a function of model rank.
Parameters
----------
ensemble : Ensemble object
holds optimization results across a range of model ranks
ax : matplotlib axis (optional)
axis to plot on (defaults to current axis object)
jitter : float (optional... |
def tsort(self):
"""Given a partial ordering, return a totally ordered list.
part is a dict of partial orderings. Each value is a set,
which the key depends on.
The return value is a list of sets, each of which has only
dependencies on items in previous entries in the list.
... | Given a partial ordering, return a totally ordered list.
part is a dict of partial orderings. Each value is a set,
which the key depends on.
The return value is a list of sets, each of which has only
dependencies on items in previous entries in the list.
raise ValueError if o... |
def calc_max_flexural_wavelength(self):
"""
Returns the approximate maximum flexural wavelength
This is important when padding of the grid is required: in Flexure (this
code), grids are padded out to one maximum flexural wavelength, but in any
case, the flexural wavelength is a good character... | Returns the approximate maximum flexural wavelength
This is important when padding of the grid is required: in Flexure (this
code), grids are padded out to one maximum flexural wavelength, but in any
case, the flexural wavelength is a good characteristic distance for any
truncation limit |
def uniq(args):
"""
%prog uniq gffile cdsfasta
Remove overlapping gene models. Similar to formats.gff.uniq(), overlapping
'piles' are processed, one by one.
Here, we use a different algorithm, that retains the best non-overlapping
subset witin each pile, rather than single best model. Scoring ... | %prog uniq gffile cdsfasta
Remove overlapping gene models. Similar to formats.gff.uniq(), overlapping
'piles' are processed, one by one.
Here, we use a different algorithm, that retains the best non-overlapping
subset witin each pile, rather than single best model. Scoring function is
also differe... |
def deactivatePdpContextAccept():
"""DEACTIVATE PDP CONTEXT ACCEPT Section 9.5.9"""
a = TpPd(pd=0x8)
b = MessageType(mesType=0x47) # 01000111
packet = a / b
return packet | DEACTIVATE PDP CONTEXT ACCEPT Section 9.5.9 |
def execute(self, eopatch):
"""Returns the EOPatch with renamed features.
:param eopatch: input EOPatch
:type eopatch: EOPatch
:return: input EOPatch with the renamed features
:rtype: EOPatch
"""
for feature_type, feature_name, new_feature_name in self.feature_ge... | Returns the EOPatch with renamed features.
:param eopatch: input EOPatch
:type eopatch: EOPatch
:return: input EOPatch with the renamed features
:rtype: EOPatch |
def list_clients(self, instance=None):
"""
Lists the clients.
:param Optional[str] instance: A Yamcs instance name.
:rtype: ~collections.Iterable[yamcs.model.Client]
"""
# Server does not do pagination on listings of this resource.
# Return an iterator anyway for... | Lists the clients.
:param Optional[str] instance: A Yamcs instance name.
:rtype: ~collections.Iterable[yamcs.model.Client] |
def create_typed_target (self, type, project, name, sources, requirements, default_build, usage_requirements):
""" Creates a TypedTarget with the specified properties.
The 'name', 'sources', 'requirements', 'default_build' and
'usage_requirements' are assumed to be in the form specified
... | Creates a TypedTarget with the specified properties.
The 'name', 'sources', 'requirements', 'default_build' and
'usage_requirements' are assumed to be in the form specified
by the user in Jamfile corresponding to 'project'. |
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 handle_error(self, exp):
"""Called if a Mapper returns MappingInvalid. Should handle the error
and return it in the appropriate format, can be overridden in order
to change the error format.
:param exp: MappingInvalid exception raised
"""
payload = {
"mes... | Called if a Mapper returns MappingInvalid. Should handle the error
and return it in the appropriate format, can be overridden in order
to change the error format.
:param exp: MappingInvalid exception raised |
def my_address_string(self):
""" For logging client host without resolving. """
addr = getattr(self, 'client_address', ('', None))[0]
# If listed in proxy_ips, use the X-Forwarded-For header, if present.
if addr in self.proxy_ips:
return self.headers.getheader('x-forwarded-f... | For logging client host without resolving. |
def on_next_request(self, py_db, request):
'''
:param NextRequest request:
'''
arguments = request.arguments # : :type arguments: NextArguments
thread_id = arguments.threadId
if py_db.get_use_libraries_filter():
step_cmd_id = CMD_STEP_OVER_MY_CODE
el... | :param NextRequest request: |
def verify_ed25519_signature(public_key, contents, signature, message):
"""Verify that ``signature`` comes from ``public_key`` and ``contents``.
Args:
public_key (Ed25519PublicKey): the key to verify the signature
contents (bytes): the contents that was signed
signature (bytes): the sig... | Verify that ``signature`` comes from ``public_key`` and ``contents``.
Args:
public_key (Ed25519PublicKey): the key to verify the signature
contents (bytes): the contents that was signed
signature (bytes): the signature to verify
message (str): the error message to raise.
Raises... |
def is_available(self) -> bool:
"""Indicate if this Monitor is currently available."""
status_response = self._client.get_state(
'api/monitors/daemonStatus/id:{}/daemon:zmc.json'.format(
self._monitor_id
)
)
if not status_response:
_LO... | Indicate if this Monitor is currently available. |
def _get_persistent_boot_devices(self):
"""Get details of persistent boot devices, its order
:returns: List of dictionary of boot sources and
list of boot device order
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not ... | Get details of persistent boot devices, its order
:returns: List of dictionary of boot sources and
list of boot device order
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server. |
def fetcher_factory(conf):
"""Return initialized fetcher capable of processing given conf."""
global PROMOTERS
applicable = []
if not PROMOTERS:
PROMOTERS = load_promoters()
for promoter in PROMOTERS:
if promoter.is_applicable(conf):
applicable.append((promoter.PRIORITY, ... | Return initialized fetcher capable of processing given conf. |
def SetStorageWriter(self, storage_writer):
"""Sets the storage writer.
Args:
storage_writer (StorageWriter): storage writer.
"""
self._storage_writer = storage_writer
# Reset the last event data information. Each storage file should
# contain event data for their events.
self._last_... | Sets the storage writer.
Args:
storage_writer (StorageWriter): storage writer. |
def summarize_url(url, num_sentences=4, fmt='default'):
'''returns: tuple containing
* single-line summary candidate
* key points
in the format specified.
'''
title, meta, full_text = goose_extractor(url)
if not full_text:
raise ArticleExtractionFail("Couldn't extract: {}... | returns: tuple containing
* single-line summary candidate
* key points
in the format specified. |
def process_npdu(self, npdu):
"""Encode NPDUs from the service access point and send them downstream."""
if _debug: NetworkAdapter._debug("process_npdu %r (net=%r)", npdu, self.adapterNet)
pdu = PDU(user_data=npdu.pduUserData)
npdu.encode(pdu)
self.request(pdu) | Encode NPDUs from the service access point and send them downstream. |
def cross_state_value(state):
"""
Compute the state value of the cross solving search.
"""
centres, edges = state
value = 0
for edge in edges:
if "U" in edge:
if edge["U"] == centres["D"]["D"]:
value += 1
els... | Compute the state value of the cross solving search. |
def weighted_temperature(self, how='geometric_series'):
r"""
A new temperature vector is generated containing a multi-day
average temperature as needed in the load profile function.
Parameters
----------
how : string
string which type to return ("geometric_se... | r"""
A new temperature vector is generated containing a multi-day
average temperature as needed in the load profile function.
Parameters
----------
how : string
string which type to return ("geometric_series" or "mean")
Notes
-----
Equation f... |
def emptyPrinter(self, expr):
"""Fallback printer"""
indent_str = " " * (self._print_level - 1)
lines = []
if isinstance(expr.__class__, Singleton):
# We exploit that Singletons override __expr__ to directly return
# their name
return indent_str + r... | Fallback printer |
def _class_instance_from_name(class_name, *arg, **kwarg):
"""
class_name is of the form modA.modB.modC.class module_path splits on "."
and the import_path is then ['modA','modB','modC'] the __import__ call is
really annoying but essentially it reads like:
import class from modA.modB.modC
- The... | class_name is of the form modA.modB.modC.class module_path splits on "."
and the import_path is then ['modA','modB','modC'] the __import__ call is
really annoying but essentially it reads like:
import class from modA.modB.modC
- Then the module variable points to modC
- Then you get the class from... |
def get_jobs(self, id=None, params=None):
"""
`<>`_
:arg id: The ID of the job(s) to fetch. Accepts glob patterns, or left
blank for all jobs
"""
return self.transport.perform_request(
"GET", _make_path("_rollup", "job", id), params=params
) | `<>`_
:arg id: The ID of the job(s) to fetch. Accepts glob patterns, or left
blank for all jobs |
def decompress_messages(self, partitions_offmsgs):
""" Decompress pre-defined compressed fields for each message. """
for pomsg in partitions_offmsgs:
if pomsg['message']:
pomsg['message'] = self.decompress_fun(pomsg['message'])
yield pomsg | Decompress pre-defined compressed fields for each message. |
def _get_partial_string_timestamp_match_key(self, key, labels):
"""Translate any partial string timestamp matches in key, returning the
new key (GH 10331)"""
if isinstance(labels, MultiIndex):
if (isinstance(key, str) and labels.levels[0].is_all_dates):
# Convert key ... | Translate any partial string timestamp matches in key, returning the
new key (GH 10331) |
def printed_out(self, name):
"""
Create a string representation of the action
"""
opt = self.variables().optional_namestring()
req = self.variables().required_namestring()
out = ''
out += '| |\n'
out += '| |---{}({}{})\n'.format(name, req, opt)
... | Create a string representation of the action |
def add_gemini_query(self, name, query):
"""Add a user defined gemini query
Args:
name (str)
query (str)
"""
logger.info("Adding query {0} with text {1}".format(name, query))
new_query = GeminiQuery(name=name, query=query)
self.session.add(new_que... | Add a user defined gemini query
Args:
name (str)
query (str) |
def repository(self):
"""Repository."""
m = re.match("(.+)(_\d{4}_\d{2}_\d{2}_)(.+)", self.__module__)
if m:
return m.group(1)
m = re.match("(.+)(_release_)(.+)", self.__module__)
if m:
return m.group(1) | Repository. |
def all_table_names_in_schema(self, schema, cache=False,
cache_timeout=None, force=False):
"""Parameters need to be passed as keyword arguments.
For unused parameters, they are referenced in
cache_util.memoized_func decorator.
:param schema: schema nam... | Parameters need to be passed as keyword arguments.
For unused parameters, they are referenced in
cache_util.memoized_func decorator.
:param schema: schema name
:type schema: str
:param cache: whether cache is enabled for the function
:type cache: bool
:param cac... |
def _request(self, url, params={}):
"""Makes a request using the currently open session.
:param url: A url fragment to use in the creation of the master url
"""
r = self._session.get(url=url, params=params, headers=DEFAULT_ORIGIN)
return r | Makes a request using the currently open session.
:param url: A url fragment to use in the creation of the master url |
def _is_valid_endpoint(endpoint):
"""helper for interval_range to check if start/end are valid types"""
return any([is_number(endpoint),
isinstance(endpoint, Timestamp),
isinstance(endpoint, Timedelta),
endpoint is None]) | helper for interval_range to check if start/end are valid types |
def layout(mtf_graph, mesh_shape, mtf_outputs=()):
"""Compute layout rules based on a computational graph and mesh shape.
Args:
mtf_graph: a mtf.Graph.
mesh_shape: an mtf.Shape, str, or listlike of mtf.Dimension.
mtf_outputs: an optional iterable of mtf.Tensor, representing the outputs
of the c... | Compute layout rules based on a computational graph and mesh shape.
Args:
mtf_graph: a mtf.Graph.
mesh_shape: an mtf.Shape, str, or listlike of mtf.Dimension.
mtf_outputs: an optional iterable of mtf.Tensor, representing the outputs
of the computation.
Returns:
a mtf.LayoutRules |
def sync_state(self):
"""Called to synchronize state (e.g. when parameters have changed).
"""
oradius = self.radius + self.width
if oradius < self.radius:
raise ValueError('Outer boundary < inner boundary')
d = dict(points=self.points, radius=self.radius, color=self.... | Called to synchronize state (e.g. when parameters have changed). |
def breeding_wean(request, breeding_id):
"""This view is used to generate a form by which to wean pups which belong to a particular breeding set.
This view typically is used to wean existing pups. This includes the MouseID, Cage, Markings, Gender and Wean Date fields. For other fields use the breeding-chang... | This view is used to generate a form by which to wean pups which belong to a particular breeding set.
This view typically is used to wean existing pups. This includes the MouseID, Cage, Markings, Gender and Wean Date fields. For other fields use the breeding-change page.
It takes a request in the form /bree... |
def remove_group(self, groupname):
"""Delete a group from the JIRA instance.
:param groupname: The group to be deleted from the JIRA instance.
:type groupname: str
:return: Boolean. Returns True on success.
:rtype: bool
"""
# implementation based on
# htt... | Delete a group from the JIRA instance.
:param groupname: The group to be deleted from the JIRA instance.
:type groupname: str
:return: Boolean. Returns True on success.
:rtype: bool |
def counts_map(self):
"""Return 3-D counts map for this component as a Map object.
Returns
-------
map : `~fermipy.skymap.MapBase`
"""
try:
if isinstance(self.like, gtutils.SummedLikelihood):
cmap = self.like.components[0].logLike.countsMap()... | Return 3-D counts map for this component as a Map object.
Returns
-------
map : `~fermipy.skymap.MapBase` |
def convolve(data, h, res_g=None, sub_blocks=None):
"""
convolves 1d-3d data with kernel h
data and h can either be numpy arrays or gpu buffer objects (OCLArray,
which must be float32 then)
boundary conditions are clamping to zero at edge.
"""
if not len(data.shape) in [1, 2, 3]:
... | convolves 1d-3d data with kernel h
data and h can either be numpy arrays or gpu buffer objects (OCLArray,
which must be float32 then)
boundary conditions are clamping to zero at edge. |
def start(sc, timedelta_formatter=_pretty_time_delta, bar_width=20, sleep_time=0.5):
"""Creates a :class:`ProgressPrinter` that polls the SparkContext for information
about active stage progress and prints that information to stderr.
The printer runs in a thread and is useful for showing text-based
pro... | Creates a :class:`ProgressPrinter` that polls the SparkContext for information
about active stage progress and prints that information to stderr.
The printer runs in a thread and is useful for showing text-based
progress bars in interactive environments (e.g., REPLs, Jupyter Notebooks).
This function ... |
def atan(x):
""" tan(x)
Trigonometric arc tan function.
"""
_math = infer_math(x)
if _math is math:
return _math.atan(x)
else:
return _math.arctan(x) | tan(x)
Trigonometric arc tan function. |
def _get_3d_plot(self, label_stable=True):
"""
Shows the plot using pylab. Usually I won"t do imports in methods,
but since plotting is a fairly expensive library to load and not all
machines have matplotlib installed, I have done it this way.
"""
import matplotlib.pyplo... | Shows the plot using pylab. Usually I won"t do imports in methods,
but since plotting is a fairly expensive library to load and not all
machines have matplotlib installed, I have done it this way. |
def upsert(self, doc, namespace, timestamp):
"""Update or insert a document into Solr
This method should call whatever add/insert/update method exists for
the backend engine and add the document in there. The input will
always be one mongo document, represented as a Python dictionary.
... | Update or insert a document into Solr
This method should call whatever add/insert/update method exists for
the backend engine and add the document in there. The input will
always be one mongo document, represented as a Python dictionary. |
def increment(self, member, amount=1):
"""Increment the score of ``member`` by ``amount``."""
self._dict[member] += amount
return self._dict[member] | Increment the score of ``member`` by ``amount``. |
def _bson_to_dict(data, opts):
"""Decode a BSON string to document_class."""
try:
if _raw_document_class(opts.document_class):
return opts.document_class(data, opts)
_, end = _get_object_size(data, 0, len(data))
return _elements_to_dict(data, 4, end, opts)
except InvalidB... | Decode a BSON string to document_class. |
def get_permalink_ids_iter(self):
'''
Method to get permalink ids from content. To be bound to the class last
thing.
'''
permalink_id_key = self.settings['PERMALINK_ID_METADATA_KEY']
permalink_ids = self.metadata.get(permalink_id_key, '')
for permalink_id in permalink_ids.split(','):
... | Method to get permalink ids from content. To be bound to the class last
thing. |
def linear_copy(self, deep=False):
"""
Returns a copy of the input unstructured grid containing only
linear cells. Converts the following cell types to their
linear equivalents.
- VTK_QUADRATIC_TETRA --> VTK_TETRA
- VTK_QUADRATIC_PYRAMID --> VTK_PYRAMID
... | Returns a copy of the input unstructured grid containing only
linear cells. Converts the following cell types to their
linear equivalents.
- VTK_QUADRATIC_TETRA --> VTK_TETRA
- VTK_QUADRATIC_PYRAMID --> VTK_PYRAMID
- VTK_QUADRATIC_WEDGE --> VTK_WEDGE
- VTK_... |
def _build_master(cls):
"""
Prepare the master working set.
"""
ws = cls()
try:
from __main__ import __requires__
except ImportError:
# The main program does not list any requirements
return ws
# ensure the requirements are met... | Prepare the master working set. |
def match_objective_id(self, objective_id, match):
"""Sets the objective ``Id`` for this query.
arg: objective_id (osid.id.Id): an objective ``Id``
arg: match (boolean): ``true`` for a positive match,
``false`` for a negative match
raise: NullArgument - ``objectiv... | Sets the objective ``Id`` for this query.
arg: objective_id (osid.id.Id): an objective ``Id``
arg: match (boolean): ``true`` for a positive match,
``false`` for a negative match
raise: NullArgument - ``objective_id`` is ``null``
*compliance: mandatory -- This meth... |
def replace_namespaced_replica_set_scale(self, name, namespace, body, **kwargs):
"""
replace scale of the specified ReplicaSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namesp... | replace scale of the specified ReplicaSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_replica_set_scale(name, namespace, body, async_req=True)
>>> result = thread.get()
... |
def drop_table(self, tablename, silent=False):
"""
Drop a table
:Parameters:
- tablename: string
- slient: boolean. If false and the table doesn't exists an exception will be raised;
Otherwise it will be ignored
:Return: Nothing
"""
i... | Drop a table
:Parameters:
- tablename: string
- slient: boolean. If false and the table doesn't exists an exception will be raised;
Otherwise it will be ignored
:Return: Nothing |
def get_classname(o):
""" Returns the classname of an object r a class
:param o:
:return:
"""
if inspect.isclass(o):
target = o
elif callable(o):
target = o
else:
target = o.__class__
try:
return target.__qualname__
except AttributeError: # pragma: n... | Returns the classname of an object r a class
:param o:
:return: |
def igphyml(input_file=None, tree_file=None, root=None, verbose=False):
'''
Computes a phylogenetic tree using IgPhyML.
.. note::
IgPhyML must be installed. It can be downloaded from https://github.com/kbhoehn/IgPhyML.
Args:
input_file (str): Path to a Phylip-formatted multip... | Computes a phylogenetic tree using IgPhyML.
.. note::
IgPhyML must be installed. It can be downloaded from https://github.com/kbhoehn/IgPhyML.
Args:
input_file (str): Path to a Phylip-formatted multiple sequence alignment. Required.
tree_file (str): Path to the output tree f... |
def exec_command(self, cmd, tmp_path, sudo_user, sudoable=False, executable='/bin/sh'):
''' run a command on the remote host '''
vvv("EXEC COMMAND %s" % cmd)
if self.runner.sudo and sudoable:
raise errors.AnsibleError("fireball does not use sudo, but runs as whoever it was initiate... | run a command on the remote host |
def _try_dump(cnf, outpath, otype, fmsg, extra_opts=None):
"""
:param cnf: Configuration object to print out
:param outpath: Output file path or None
:param otype: Output type or None
:param fmsg: message if it cannot detect otype by 'inpath'
:param extra_opts: Map object will be given to API.du... | :param cnf: Configuration object to print out
:param outpath: Output file path or None
:param otype: Output type or None
:param fmsg: message if it cannot detect otype by 'inpath'
:param extra_opts: Map object will be given to API.dump as extra options |
def render_export_form(self, request, context, form_url=''):
"""
Render the from submission export form.
"""
context.update({
'has_change_permission': self.has_change_permission(request),
'form_url': mark_safe(form_url),
'opts': self.opts,
... | Render the from submission export form. |
def feet(kilometers=0, meters=0, miles=0, nautical=0):
"""
TODO docs.
"""
ret = 0.
if nautical:
kilometers += nautical / nm(1.)
if meters:
kilometers += meters / 1000.
if kilometers:
miles += mi(kilometers=kilometers)
ret += miles * 5280
return ret | TODO docs. |
def get_bootdev(self):
"""Get current boot device override information.
Provides the current requested boot device. Be aware that not all IPMI
devices support this. Even in BMCs that claim to, occasionally the
BIOS or UEFI fail to honor it. This is usually only applicable to the
... | Get current boot device override information.
Provides the current requested boot device. Be aware that not all IPMI
devices support this. Even in BMCs that claim to, occasionally the
BIOS or UEFI fail to honor it. This is usually only applicable to the
next reboot.
:raises: ... |
def random_rollout_subsequences(rollouts, num_subsequences, subsequence_length):
"""Chooses a random frame sequence of given length from a set of rollouts."""
def choose_subsequence():
# TODO(koz4k): Weigh rollouts by their lengths so sampling is uniform over
# frames and not rollouts.
rollout = random.... | Chooses a random frame sequence of given length from a set of rollouts. |
def _add_flow_v1_2(self, src, port, timeout, datapath):
"""enter a flow entry for the packet from the slave i/f
with idle_timeout. for OpenFlow ver1.2 and ver1.3."""
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
match = parser.OFPMatch(
in_port=port, et... | enter a flow entry for the packet from the slave i/f
with idle_timeout. for OpenFlow ver1.2 and ver1.3. |
def keyring_remove(key, yes, **kwargs):
"""
Removes a public key from the keyring.
Does nothing if a key is already not in the keyring. If none is specified - clears the keyring.
To force the cocaine-runtime to refresh its keyring, call `refresh` method.
"""
if key is None:
if not yes:
... | Removes a public key from the keyring.
Does nothing if a key is already not in the keyring. If none is specified - clears the keyring.
To force the cocaine-runtime to refresh its keyring, call `refresh` method. |
def build_to_target_size_from_token_counts(cls,
target_size,
token_counts,
min_val,
max_val,
... | Builds a SubwordTextTokenizer that has `vocab_size` near `target_size`.
Uses simple recursive binary search to find a minimum token count that most
closely matches the `target_size`.
Args:
target_size: Desired vocab_size to approximate.
token_counts: A dictionary of token c... |
def to_identifier(s):
"""
Convert snake_case to camel_case.
"""
if s.startswith('GPS'):
s = 'Gps' + s[3:]
return ''.join([i.capitalize() for i in s.split('_')]) if '_' in s else s | Convert snake_case to camel_case. |
def define_objective_with_I(I, *args):
"""Define a polynomial using measurements and an I matrix describing a Bell
inequality.
:param I: The I matrix of a Bell inequality in the Collins-Gisin notation.
:type I: list of list of int.
:param args: Either the measurements of Alice and Bob or a `Probabi... | Define a polynomial using measurements and an I matrix describing a Bell
inequality.
:param I: The I matrix of a Bell inequality in the Collins-Gisin notation.
:type I: list of list of int.
:param args: Either the measurements of Alice and Bob or a `Probability`
class describing their ... |
def _init_individual(subjs, voxels, TRs):
"""Initializes the individual components `S_i` to empty (all zeros).
Parameters
----------
subjs : int
The number of subjects.
voxels : list of int
A list with the number of voxels per subject.
TRs : in... | Initializes the individual components `S_i` to empty (all zeros).
Parameters
----------
subjs : int
The number of subjects.
voxels : list of int
A list with the number of voxels per subject.
TRs : int
The number of timepoints in the data.
... |
def post_copy_notes(self, post_id, other_post_id):
"""Function to copy notes (requires login).
Parameters:
post_id (int):
other_post_id (int): The id of the post to copy notes to.
"""
return self._get('posts/{0}/copy_notes.json'.format(post_id),
... | Function to copy notes (requires login).
Parameters:
post_id (int):
other_post_id (int): The id of the post to copy notes to. |
def Stop(self):
"""Signals the worker threads to shut down and waits until it exits."""
self._shutdown = True
self._new_updates.set() # Wake up the transmission thread.
if self._main_thread is not None:
self._main_thread.join()
self._main_thread = None
if self._transmission_thread is ... | Signals the worker threads to shut down and waits until it exits. |
def _TypecheckDecorator(subject=None, **kwargs):
"""Dispatches type checks based on what the subject is.
Functions or methods are annotated directly. If this method is called
with keyword arguments only, return a decorator.
"""
if subject is None:
return _TypecheckDecoratorFactory(kwargs)
elif inspect.... | Dispatches type checks based on what the subject is.
Functions or methods are annotated directly. If this method is called
with keyword arguments only, return a decorator. |
def _parse_row(rowvalues, rowtypes):
"""
Scan a single row from an Excel file, and return the list of ranges
corresponding to each consecutive span of non-empty cells in this row.
If all cells are empty, return an empty list. Each "range" in the list
is a tuple of the form `(startcol, endcol)`.
... | Scan a single row from an Excel file, and return the list of ranges
corresponding to each consecutive span of non-empty cells in this row.
If all cells are empty, return an empty list. Each "range" in the list
is a tuple of the form `(startcol, endcol)`.
For example, if the row is the following:
... |
def variable_names(self):
"""
Returns the names of all environment variables.
:return: the names of the variables
:rtype: list
"""
result = []
names = javabridge.call(self.jobject, "getVariableNames", "()Ljava/util/Set;")
for name in javabridge.iterate_co... | Returns the names of all environment variables.
:return: the names of the variables
:rtype: list |
def dot(self, serie, r_max):
"""Draw a dot line"""
serie_node = self.svg.serie(serie)
view_values = list(map(self.view, serie.points))
for i, value in safe_enumerate(serie.values):
x, y = view_values[i]
if self.logarithmic:
log10min = log10(self._... | Draw a dot line |
def create_entity(self):
"""Create entity if `flow_collection` is defined in process.
Following rules applies for adding `Data` object to `Entity`:
* Only add `Data object` to `Entity` if process has defined
`flow_collection` field
* Add object to existing `Entity`, if all paren... | Create entity if `flow_collection` is defined in process.
Following rules applies for adding `Data` object to `Entity`:
* Only add `Data object` to `Entity` if process has defined
`flow_collection` field
* Add object to existing `Entity`, if all parents that are part
of it (but ... |
def message_to_objects(
message: str, sender: str, sender_key_fetcher:Callable[[str], str]=None, user: UserType =None,
) -> List:
"""Takes in a message extracted by a protocol and maps it to entities.
:param message: XML payload
:type message: str
:param sender: Payload sender id
:type mess... | Takes in a message extracted by a protocol and maps it to entities.
:param message: XML payload
:type message: str
:param sender: Payload sender id
:type message: str
:param sender_key_fetcher: Function to fetch sender public key. If not given, key will always be fetched
over network. The f... |
def get_image(verbose=False):
"""Get the image as a TensorFlow variable.
Returns:
A `tf.Variable`, which must be initialized prior to use:
invoke `sess.run(result.initializer)`."""
base_data = tf.constant(image_data(verbose=verbose))
base_image = tf.image.decode_image(base_data, channels=3)
base_imag... | Get the image as a TensorFlow variable.
Returns:
A `tf.Variable`, which must be initialized prior to use:
invoke `sess.run(result.initializer)`. |
def list_instances(self, hourly=True, monthly=True, tags=None, cpus=None,
memory=None, hostname=None, domain=None,
local_disk=None, datacenter=None, nic_speed=None,
public_ip=None, private_ip=None, **kwargs):
"""Retrieve a list of all virtual ... | Retrieve a list of all virtual servers on the account.
Example::
# Print out a list of hourly instances in the DAL05 data center.
for vsi in mgr.list_instances(hourly=True, datacenter='dal05'):
print vsi['fullyQualifiedDomainName'], vsi['primaryIpAddress']
... |
def tab(topics, complete):
"""Utility sub-command for tabcompletion
This command is meant to be called by a tab completion
function and is given a the currently entered topics,
along with a boolean indicating whether or not the
last entered argument is complete.
"""
# Discard `be tab`
... | Utility sub-command for tabcompletion
This command is meant to be called by a tab completion
function and is given a the currently entered topics,
along with a boolean indicating whether or not the
last entered argument is complete. |
def user_can_edit_news(user):
"""
Check if the user has permission to edit any of the registered NewsItem
types.
"""
newsitem_models = [model.get_newsitem_model()
for model in NEWSINDEX_MODEL_CLASSES]
if user.is_active and user.is_superuser:
# admin can edit news ... | Check if the user has permission to edit any of the registered NewsItem
types. |
def do_handshake(self, timeout):
'perform a SSL/TLS handshake'
tout = _timeout(timeout)
if not self._blocking:
return self._sslobj.do_handshake()
while 1:
try:
return self._sslobj.do_handshake()
except ssl.SSLError, exc:
... | perform a SSL/TLS handshake |
def recover_hashmap_model_from_data(model_class, original_data, modified_data, deleted_data, field_type):
"""
Function to reconstruct a model from DirtyModel basic information: original data, the modified and deleted
fields.
Necessary for pickle an object
"""
model = model_class(field_type=field... | Function to reconstruct a model from DirtyModel basic information: original data, the modified and deleted
fields.
Necessary for pickle an object |
def ls(args):
"""
List S3 buckets. See also "aws s3 ls". Use "aws s3 ls NAME" to list bucket contents.
"""
table = []
for bucket in filter_collection(resources.s3.buckets, args):
bucket.LocationConstraint = clients.s3.get_bucket_location(Bucket=bucket.name)["LocationConstraint"]
clou... | List S3 buckets. See also "aws s3 ls". Use "aws s3 ls NAME" to list bucket contents. |
def getAllowedMethods(self):
"""Returns the allowed methods for this analysis, either if the method
was assigned directly (by using "Allows manual entry of results") or
indirectly via Instrument ("Allows instrument entry of results") in
Analysis Service Edit View.
:return: A list... | Returns the allowed methods for this analysis, either if the method
was assigned directly (by using "Allows manual entry of results") or
indirectly via Instrument ("Allows instrument entry of results") in
Analysis Service Edit View.
:return: A list with the methods allowed for this analy... |
def log(self, format_, args, level=logging.INFO):
"""
This function is called for anything that needs to get logged.
It logs to the logger of this listener.
It is not defined in the standard handler class; our version
has an additional `level` argument that allows to control the... | This function is called for anything that needs to get logged.
It logs to the logger of this listener.
It is not defined in the standard handler class; our version
has an additional `level` argument that allows to control the
logging level in the standard Python logging support.
... |
def PlaceCall(self, *Targets):
"""Places a call to a single user or creates a conference call.
:Parameters:
Targets : str
One or more call targets. If multiple targets are specified, a conference call is
created. The call target can be a Skypename, phone number, or spe... | Places a call to a single user or creates a conference call.
:Parameters:
Targets : str
One or more call targets. If multiple targets are specified, a conference call is
created. The call target can be a Skypename, phone number, or speed dial code.
:return: A call obj... |
def scale(self, s=None):
"""Set/get actor's scaling factor.
:param s: scaling factor(s).
:type s: float, list
.. note:: if `s==(sx,sy,sz)` scale differently in the three coordinates."""
if s is None:
return np.array(self.GetScale())
self.SetScale(s)
... | Set/get actor's scaling factor.
:param s: scaling factor(s).
:type s: float, list
.. note:: if `s==(sx,sy,sz)` scale differently in the three coordinates. |
def one(ctx, interactive, enable_phantomjs, enable_puppeteer, scripts):
"""
One mode not only means all-in-one, it runs every thing in one process over
tornado.ioloop, for debug purpose
"""
ctx.obj['debug'] = False
g = ctx.obj
g['testing_mode'] = True
if scripts:
from pyspider.... | One mode not only means all-in-one, it runs every thing in one process over
tornado.ioloop, for debug purpose |
def place_analysis_summary_report(feature, parent):
"""Retrieve an HTML place analysis table report from a multi exposure
analysis.
"""
_ = feature, parent # NOQA
analysis_dir = get_analysis_dir(exposure_place['key'])
if analysis_dir:
return get_impact_report_as_string(analysis_dir)
... | Retrieve an HTML place analysis table report from a multi exposure
analysis. |
def _map_relations(relations, p, language='any'):
'''
:param: :class:`list` relations: Relations to be mapped. These are
concept or collection id's.
:param: :class:`skosprovider.providers.VocabularyProvider` p: Provider
to look up id's.
:param string language: Language to render the rela... | :param: :class:`list` relations: Relations to be mapped. These are
concept or collection id's.
:param: :class:`skosprovider.providers.VocabularyProvider` p: Provider
to look up id's.
:param string language: Language to render the relations' labels in
:rtype: :class:`list` |
def truncate_graph_bbox(G, north, south, east, west, truncate_by_edge=False, retain_all=False):
"""
Remove every node in graph that falls outside a bounding box.
Needed because overpass returns entire ways that also include nodes outside
the bbox if the way (that is, a way with a single OSM ID) has a n... | Remove every node in graph that falls outside a bounding box.
Needed because overpass returns entire ways that also include nodes outside
the bbox if the way (that is, a way with a single OSM ID) has a node inside
the bbox at some point.
Parameters
----------
G : networkx multidigraph
nort... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.