code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def val_to_edge(edges, x):
"""Convert axis coordinate to bin index."""
edges = np.array(edges)
w = edges[1:] - edges[:-1]
w = np.insert(w, 0, w[0])
ibin = np.digitize(np.array(x, ndmin=1), edges - 0.5 * w) - 1
ibin[ibin < 0] = 0
return ibin | Convert axis coordinate to bin index. |
def propose_live(self):
"""Return a live point/axes to be used by other sampling methods."""
# Copy a random live point.
i = self.rstate.randint(self.nlive)
u = self.live_u[i, :]
# Check for ellipsoid overlap.
ell_idxs = self.mell.within(u)
nidx = len(ell_idxs)
... | Return a live point/axes to be used by other sampling methods. |
def createNoiseExperimentArgs():
"""Run the probability of false negatives with noise experiment."""
experimentArguments = []
n = 6000
for a in [128]:
noisePct = 0.75
while noisePct <= 0.85:
noise = int(round(noisePct*a,0))
# Some parameter combinations are just not worth running!
expe... | Run the probability of false negatives with noise experiment. |
def grey_erosion(image, radius=None, mask=None, footprint=None):
'''Perform a grey erosion with masking'''
if footprint is None:
if radius is None:
footprint = np.ones((3,3),bool)
radius = 1
else:
footprint = strel_disk(radius)==1
else:
radius = ma... | Perform a grey erosion with masking |
def _dispatch_call_args(cls=None, bound_call=None, unbound_call=None,
attr='_call'):
"""Check the arguments of ``_call()`` or similar for conformity.
The ``_call()`` method of `Operator` is allowed to have the
following signatures:
Python 2 and 3:
- ``_call(self, x)``
... | Check the arguments of ``_call()`` or similar for conformity.
The ``_call()`` method of `Operator` is allowed to have the
following signatures:
Python 2 and 3:
- ``_call(self, x)``
- ``_call(self, vec, out)``
- ``_call(self, x, out=None)``
Python 3 only:
- ``_call(self... |
def is_value_type_valid_for_exact_conditions(self, value):
""" Method to validate if the value is valid for exact match type evaluation.
Args:
value: Value to validate.
Returns:
Boolean: True if value is a string, boolean, or number. Otherwise False.
"""
# No need to check for bool sin... | Method to validate if the value is valid for exact match type evaluation.
Args:
value: Value to validate.
Returns:
Boolean: True if value is a string, boolean, or number. Otherwise False. |
def unhandled(self, key):
"""Handle other keyboard actions not handled by the ListBox widget.
"""
self.key = key
self.size = self.tui.get_cols_rows()
if self.search is True:
if self.enter is False and self.no_matches is False:
if len(key) == 1 and key... | Handle other keyboard actions not handled by the ListBox widget. |
def setInstrumentParameters(self, instrpars):
""" This method overrides the superclass to set default values into
the parameter dictionary, in case empty entries are provided.
"""
pri_header = self._image[0].header
self.proc_unit = instrpars['proc_unit']
if self._isN... | This method overrides the superclass to set default values into
the parameter dictionary, in case empty entries are provided. |
def matrix2lha(M):
"""Inverse function to lha2matrix: return a LHA-like list given a tensor."""
l = []
ind = np.indices(M.shape).reshape(M.ndim, M.size).T
for i in ind:
l.append([j+1 for j in i] + [M[tuple(i)]])
return l | Inverse function to lha2matrix: return a LHA-like list given a tensor. |
def enable_mfa_device(self, user_name, serial_number,
auth_code_1, auth_code_2):
"""
Enables the specified MFA device and associates it with the
specified user.
:type user_name: string
:param user_name: The username of the user
:type se... | Enables the specified MFA device and associates it with the
specified user.
:type user_name: string
:param user_name: The username of the user
:type serial_number: string
:param seriasl_number: The serial number which uniquely identifies
t... |
def receipt(df):
"""
Return a dataframe to verify if a item has a receipt.
"""
mutated_df = df[['IdPRONAC', 'idPlanilhaItem']].astype(str)
mutated_df['pronac_planilha_itens'] = (
f"{mutated_df['IdPRONAC']}/{mutated_df['idPlanilhaItem']}"
)
return (
mutated_df
.set_in... | Return a dataframe to verify if a item has a receipt. |
def control_surface_encode(self, target, idSurface, mControl, bControl):
'''
Control for surface; pending and order to origin.
target : The system setting the commands (uint8_t)
idSurface : ID control surface send 0: thr... | Control for surface; pending and order to origin.
target : The system setting the commands (uint8_t)
idSurface : ID control surface send 0: throttle 1: aileron 2: elevator 3: rudder (uint8_t)
mControl : Pending (float)
... |
def lock(self, timeout=10):
"""
Advisory lock.
Use to ensure that only one LocalSyncClient is working on the Target at the same time.
"""
logger.debug("Locking %s", self.lock_file)
if not os.path.exists(self.lock_file):
self.ensure_path(self.lock_file)
... | Advisory lock.
Use to ensure that only one LocalSyncClient is working on the Target at the same time. |
def start_with(self, x):
"""Returns all arguments beginning with given string (or list thereof)"""
_args = []
for arg in self.all:
if is_collection(x):
for _x in x:
if arg.startswith(x):
_args.append(a... | Returns all arguments beginning with given string (or list thereof) |
def start_transports(self):
"""start thread transports."""
self.transport = Transport(
self.queue, self.batch_size, self.batch_interval,
self.session_factory)
thread = threading.Thread(target=self.transport.loop)
self.threads.append(thread)
thread.daemon =... | start thread transports. |
def scopus_url(self):
"""URL to the abstract page on Scopus."""
scopus_url = self.coredata.find('link[@rel="scopus"]', ns)
try:
return scopus_url.get('href')
except AttributeError: # scopus_url is None
return None | URL to the abstract page on Scopus. |
def known(self, words: List[str]) -> List[str]:
"""
Return a list of given words that found in the spelling dictionary
:param str words: A list of words to check if they are in the spelling dictionary
"""
return list(w for w in words if w in self.__WORDS) | Return a list of given words that found in the spelling dictionary
:param str words: A list of words to check if they are in the spelling dictionary |
def makeCloneMap(columnsShape, outputCloningWidth, outputCloningHeight=-1):
"""Make a two-dimensional clone map mapping columns to clone master.
This makes a map that is (numColumnsHigh, numColumnsWide) big that can
be used to figure out which clone master to use for each column. Here are
a few sample calls
... | Make a two-dimensional clone map mapping columns to clone master.
This makes a map that is (numColumnsHigh, numColumnsWide) big that can
be used to figure out which clone master to use for each column. Here are
a few sample calls
>>> makeCloneMap(columnsShape=(10, 6), outputCloningWidth=4)
(array([[ 0, 1,... |
def deserialize_header_auth(stream, algorithm, verifier=None):
"""Deserializes a MessageHeaderAuthentication object from a source stream.
:param stream: Source data stream
:type stream: io.BytesIO
:param algorithm: The AlgorithmSuite object type contained in the header
:type algorith: aws_encryptio... | Deserializes a MessageHeaderAuthentication object from a source stream.
:param stream: Source data stream
:type stream: io.BytesIO
:param algorithm: The AlgorithmSuite object type contained in the header
:type algorith: aws_encryption_sdk.identifiers.AlgorithmSuite
:param verifier: Signature verifi... |
def stats(request, server_name):
"""
Show server statistics.
"""
server_name = server_name.strip('/')
data = _context_data({
'title': _('Memcache Statistics for %s') % server_name,
'cache_stats': _get_cache_stats(server_name),
},
request)
return render_to_response('me... | Show server statistics. |
def _short_string_handler_factory():
"""Generates the short string (double quoted) handler."""
def before(c, ctx, is_field_name, is_clob):
assert not (is_clob and is_field_name)
is_string = not is_clob and not is_field_name
if is_string:
ctx.set_ion_type(IonType.STRING)
... | Generates the short string (double quoted) handler. |
def populate(self,
size,
names_library=None,
reuse_names=False,
random_branches=False,
branch_range=(0, 1),
support_range=(0, 1)):
"""
Generates a random topology by populating current node.
:argument None names_library: If provided, names lib... | Generates a random topology by populating current node.
:argument None names_library: If provided, names library
(list, set, dict, etc.) will be used to name nodes.
:argument False reuse_names: If True, node names will not be
necessarily unique, which makes the process a bit more
... |
def add_translation(self, rna: Rna, protein: Protein) -> str:
"""Add a translation relation from a RNA to a protein.
:param rna: An RNA node
:param protein: A protein node
"""
return self.add_unqualified_edge(rna, protein, TRANSLATED_TO) | Add a translation relation from a RNA to a protein.
:param rna: An RNA node
:param protein: A protein node |
def _create_autostart_entry(autostart_data: AutostartSettings, autostart_file: Path):
"""Create an autostart .desktop file in the autostart directory, if possible."""
try:
source_desktop_file = get_source_desktop_file(autostart_data.desktop_file_name)
except FileNotFoundError:
_logger.except... | Create an autostart .desktop file in the autostart directory, if possible. |
def post(self, value, addend, unit):
"""A date adder endpoint."""
value = value or dt.datetime.utcnow()
if unit == "minutes":
delta = dt.timedelta(minutes=addend)
else:
delta = dt.timedelta(days=addend)
result = value + delta
return {"result": resu... | A date adder endpoint. |
def delete_publisher_asset(self, publisher_name, asset_type=None):
"""DeletePublisherAsset.
[Preview API] Delete publisher asset like logo
:param str publisher_name: Internal name of the publisher
:param str asset_type: Type of asset. Default value is 'logo'.
"""
route_va... | DeletePublisherAsset.
[Preview API] Delete publisher asset like logo
:param str publisher_name: Internal name of the publisher
:param str asset_type: Type of asset. Default value is 'logo'. |
def does_external_program_run(prog, verbose):
"""Test to see if the external programs can be run."""
try:
with open('/dev/null') as null:
subprocess.call([prog, '-h'], stdout=null, stderr=null)
result = True
except OSError:
if verbose > 1:
print("couldn't run ... | Test to see if the external programs can be run. |
def merge_data(*data_frames, **kwargs):
"""
Merge DataFrames by column. Number of rows in tables must be the same.
This method can be called both outside and as a DataFrame method.
:param list[DataFrame] data_frames: DataFrames to be merged.
:param bool auto_rename: if True, fields in source DataF... | Merge DataFrames by column. Number of rows in tables must be the same.
This method can be called both outside and as a DataFrame method.
:param list[DataFrame] data_frames: DataFrames to be merged.
:param bool auto_rename: if True, fields in source DataFrames will be renamed in the output.
:return: m... |
def assign_rates(self, mu=1.0, pi=None, W=None):
"""
Overwrite the GTR model given the provided data
Parameters
----------
mu : float
Substitution rate
W : nxn matrix
Substitution matrix
pi : n vector
Equilibrium frequenc... | Overwrite the GTR model given the provided data
Parameters
----------
mu : float
Substitution rate
W : nxn matrix
Substitution matrix
pi : n vector
Equilibrium frequencies |
def _gwf_channel(path, series_class=TimeSeries, verbose=False):
"""Find the right channel name for a LOSC GWF file
"""
channels = list(io_gwf.iter_channel_names(file_path(path)))
if issubclass(series_class, StateVector):
regex = DQMASK_CHANNEL_REGEX
else:
regex = STRAIN_CHANNEL_REGEX... | Find the right channel name for a LOSC GWF file |
def add_marccountry_tag(dom):
"""
Add ``<mods:placeTerm>`` tag with proper content.
"""
marccountry = dom.find("mods:placeTerm", {"authority": "marccountry"})
# don't add again if already defined
if marccountry:
return
marccountry_tag = dhtmlparser.HTMLElement(
"mods:place"... | Add ``<mods:placeTerm>`` tag with proper content. |
def setup_new_conf(self):
# pylint: disable=too-many-branches, too-many-locals
"""Broker custom setup_new_conf method
This function calls the base satellite treatment and manages the configuration needed
for a broker daemon:
- get and configure its pollers, reactionners and rece... | Broker custom setup_new_conf method
This function calls the base satellite treatment and manages the configuration needed
for a broker daemon:
- get and configure its pollers, reactionners and receivers relation
- configure the modules
:return: None |
def _cleanup_closed(self) -> None:
"""Double confirmation for transport close.
Some broken ssl servers may leave socket open without proper close.
"""
if self._cleanup_closed_handle:
self._cleanup_closed_handle.cancel()
for transport in self._cleanup_closed_transport... | Double confirmation for transport close.
Some broken ssl servers may leave socket open without proper close. |
def lwp_cookie_str(cookie):
"""Return string representation of Cookie in an the LWP cookie file format.
Actually, the format is extended a bit -- see module docstring.
"""
h = [(cookie.name, cookie.value),
("path", cookie.path),
("domain", cookie.domain)]
if cookie.port is not No... | Return string representation of Cookie in an the LWP cookie file format.
Actually, the format is extended a bit -- see module docstring. |
def get_draft_secret_key():
"""
Return the secret key used to generate draft mode HMACs. It will be
randomly generated on first access. Existing draft URLs can be invalidated
by deleting or updating the ``DRAFT_SECRET_KEY`` setting.
"""
# TODO: Per URL secret keys, so we can invalidate draft URL... | Return the secret key used to generate draft mode HMACs. It will be
randomly generated on first access. Existing draft URLs can be invalidated
by deleting or updating the ``DRAFT_SECRET_KEY`` setting. |
def on_patch(self, req, resp, handler=None, **kwargs):
"""Respond on POST HTTP request assuming resource creation flow.
This request handler assumes that POST requests are associated with
resource creation. Thus default flow for such requests is:
* Create new resource instances and pre... | Respond on POST HTTP request assuming resource creation flow.
This request handler assumes that POST requests are associated with
resource creation. Thus default flow for such requests is:
* Create new resource instances and prepare their representation by
calling its bulk creation m... |
def decrypt(source, dest=None, passphrase=None):
"""Attempts to decrypt a file"""
if not os.path.exists(source):
raise CryptoritoError("Encrypted file %s not found" % source)
cmd = [gnupg_bin(), gnupg_verbose(), "--decrypt", gnupg_home(),
passphrase_file(passphrase)]
if dest:
... | Attempts to decrypt a file |
def _notify_fn(self):
"""The notify thread function."""
self._notifyrunning = True
while self._notifyrunning:
try:
with IHCController._mutex:
# Are there are any new ids to be added?
if self._newnotifyids:
... | The notify thread function. |
def _setsetting(setting, default):
"""Dynamically sets the variable named in `setting`
This method uses `_getsetting()` to either fetch the setting from Django's
settings module, or else fallback to the default value; it then sets a
variable in this module with the returned value.
"""
value = _... | Dynamically sets the variable named in `setting`
This method uses `_getsetting()` to either fetch the setting from Django's
settings module, or else fallback to the default value; it then sets a
variable in this module with the returned value. |
def get_child_values(parent, names):
""" return a list of values for the specified child fields. If field not in Element then replace with nan. """
vals = []
for name in names:
if parent.hasElement(name):
vals.append(XmlHelper.as_value(parent.getElement(name)))
... | return a list of values for the specified child fields. If field not in Element then replace with nan. |
def keep(self, diff):
""" Mark this diff (or volume) to be kept in path. """
self._keepVol(diff.toVol)
self._keepVol(diff.fromVol) | Mark this diff (or volume) to be kept in path. |
def authenticate_credentials(self, payload):
"""
Returns an active user that matches the payload's user id and email.
"""
User = get_user_model() # noqa
username = jwt_get_username_from_payload_handler(payload)
if not username:
msg = _('Invalid payload.')
... | Returns an active user that matches the payload's user id and email. |
def __load_child_classes(self, ac: AssetClass):
""" Loads child classes/stocks """
# load child classes for ac
db = self.__get_session()
entities = (
db.query(dal.AssetClass)
.filter(dal.AssetClass.parentid == ac.id)
.order_by(dal.AssetClass.sortorder)... | Loads child classes/stocks |
def dump(self, force=False):
"""
Encodes the value using DER
:param force:
If the encoded contents already exist, clear them and regenerate
to ensure they are in DER format instead of BER format
:return:
A byte string of the DER-encoded value
... | Encodes the value using DER
:param force:
If the encoded contents already exist, clear them and regenerate
to ensure they are in DER format instead of BER format
:return:
A byte string of the DER-encoded value |
def main():
"""Run the bot."""
args = parser.parse_args()
initialize_logging(args)
# Allow expansion of paths even if the shell doesn't do it
config_path = os.path.abspath(os.path.expanduser(args.config))
client = kitnirc.client.Client()
controller = kitnirc.modular.Controller(client, conf... | Run the bot. |
def throttle( self, wait=True ):
"""
If the wait parameter is True, this method returns True after suspending the current
thread as necessary to ensure that no less than the configured minimum interval passed
since the most recent time an invocation of this method returned True in any th... | If the wait parameter is True, this method returns True after suspending the current
thread as necessary to ensure that no less than the configured minimum interval passed
since the most recent time an invocation of this method returned True in any thread.
If the wait parameter is False, this m... |
def confirm_user_avatar(self, user, cropping_properties):
"""Confirm the temporary avatar image previously uploaded with the specified cropping.
After a successful registry with :py:meth:`create_temp_user_avatar`, use this method to confirm the avatar for
use. The final avatar can be a subarea ... | Confirm the temporary avatar image previously uploaded with the specified cropping.
After a successful registry with :py:meth:`create_temp_user_avatar`, use this method to confirm the avatar for
use. The final avatar can be a subarea of the uploaded image, which is customized with the
``croppin... |
def binormalize(A, tol=1e-5, maxiter=10):
"""Binormalize matrix A. Attempt to create unit l_1 norm rows.
Parameters
----------
A : csr_matrix
sparse matrix (n x n)
tol : float
tolerance
x : array
guess at the diagonal
maxiter : int
maximum number of iteratio... | Binormalize matrix A. Attempt to create unit l_1 norm rows.
Parameters
----------
A : csr_matrix
sparse matrix (n x n)
tol : float
tolerance
x : array
guess at the diagonal
maxiter : int
maximum number of iterations to try
Returns
-------
C : csr_ma... |
def update(self):
"""Cache the list into the data section of the record"""
from ambry.orm.exc import NotFoundError
from requests.exceptions import ConnectionError, HTTPError
from boto.exception import S3ResponseError
d = {}
try:
for k, v in self.list(full=T... | Cache the list into the data section of the record |
def vatm(model,
x,
logits,
eps,
num_iterations=1,
xi=1e-6,
clip_min=None,
clip_max=None,
scope=None):
"""
Tensorflow implementation of the perturbation method used for virtual
adversarial training: https://arxiv.org/abs/1507.00677
:param mo... | Tensorflow implementation of the perturbation method used for virtual
adversarial training: https://arxiv.org/abs/1507.00677
:param model: the model which returns the network unnormalized logits
:param x: the input placeholder
:param logits: the model's unnormalized output tensor (the input to
... |
def register_provider(self, provider):
'''
Register a :class:`skosprovider.providers.VocabularyProvider`.
:param skosprovider.providers.VocabularyProvider provider: The provider
to register.
:raises RegistryException: A provider with this id or uri has already
b... | Register a :class:`skosprovider.providers.VocabularyProvider`.
:param skosprovider.providers.VocabularyProvider provider: The provider
to register.
:raises RegistryException: A provider with this id or uri has already
been registered. |
def _fill_schemas_from_definitions(self, obj):
"""At first create schemas without 'AllOf'
:param obj:
:return: None
"""
if obj.get('definitions'):
self.schemas.clear()
all_of_stack = []
for name, definition in obj['definitions'].items():
... | At first create schemas without 'AllOf'
:param obj:
:return: None |
def fa(arr, t, dist='norm', mode='high'):
"""Return the value corresponding to the given return period.
Parameters
----------
arr : xarray.DataArray
Maximized/minimized input data with a `time` dimension.
t : int or sequence
Return period. The period depends on the resolution of the inp... | Return the value corresponding to the given return period.
Parameters
----------
arr : xarray.DataArray
Maximized/minimized input data with a `time` dimension.
t : int or sequence
Return period. The period depends on the resolution of the input data. If the input array's resolution is
... |
def _post(self, url, data=None, json=None, params=None, headers=None):
"""Wraps a POST request with a url check"""
url = self.clean_url(url)
response = requests.post(url, data=data, json=json, params=params,
headers=headers, timeout=self.timeout,
... | Wraps a POST request with a url check |
def list_relations(self):
''' list every relation in the database as (src, relation, dst) '''
for node in self.iter_nodes():
for relation, target in self.relations_of(node.obj, True):
yield node.obj, relation, target | list every relation in the database as (src, relation, dst) |
def get_attribute(self, attribute, value=None, features=False):
"""This returns a list of GFF objects (or GFF Features) with the given attribute and if supplied, those
attributes with the specified value
:param attribute: The 'info' field attribute we are querying
:param value: Optional... | This returns a list of GFF objects (or GFF Features) with the given attribute and if supplied, those
attributes with the specified value
:param attribute: The 'info' field attribute we are querying
:param value: Optional keyword, only return attributes equal to this value
:param feature... |
def tcp_ping(
task: Task, ports: List[int], timeout: int = 2, host: Optional[str] = None
) -> Result:
"""
Tests connection to a tcp port and tries to establish a three way
handshake. To be used for network discovery or testing.
Arguments:
ports (list of int): tcp ports to ping
timeo... | Tests connection to a tcp port and tries to establish a three way
handshake. To be used for network discovery or testing.
Arguments:
ports (list of int): tcp ports to ping
timeout (int, optional): defaults to 2
host (string, optional): defaults to ``hostname``
Returns:
Res... |
def getAccounts(self):
""" Return all accounts installed in the wallet database
"""
pubkeys = self.getPublicKeys()
accounts = []
for pubkey in pubkeys:
# Filter those keys not for our network
if pubkey[: len(self.prefix)] == self.prefix:
ac... | Return all accounts installed in the wallet database |
def visit_EnumeratorList(self, node):
"""Replace enumerator expressions with '...' stubs."""
for type, enum in node.children():
if enum.value is None:
pass
elif isinstance(enum.value, (c_ast.BinaryOp, c_ast.UnaryOp)):
enum.value = c_ast.Constant("i... | Replace enumerator expressions with '...' stubs. |
def pencil3():
'''Install or update latest Pencil version 3, a GUI prototyping tool.
While it is the newer one and the GUI is more fancy, it is the "more beta"
version of pencil. For exmaple, to display a svg export may fail from
within a reveal.js presentation.
More info:
Homepage: http:... | Install or update latest Pencil version 3, a GUI prototyping tool.
While it is the newer one and the GUI is more fancy, it is the "more beta"
version of pencil. For exmaple, to display a svg export may fail from
within a reveal.js presentation.
More info:
Homepage: http://pencil.evolus.vn/Nex... |
def open_with_external_spyder(self, text):
"""Load file in external Spyder's editor, if available
This method is used only for embedded consoles
(could also be useful if we ever implement the magic %edit command)"""
match = get_error_match(to_text_string(text))
if match:
... | Load file in external Spyder's editor, if available
This method is used only for embedded consoles
(could also be useful if we ever implement the magic %edit command) |
def value(self):
"""
Return the current evaluation of a condition statement
"""
return ''.join(map(str, self.evaluate(self.trigger.user))) | Return the current evaluation of a condition statement |
def sync(self):
"""Retrieve lights from ElkM1"""
for i in range(4):
self.elk.send(ps_encode(i))
self.get_descriptions(TextDescriptions.LIGHT.value) | Retrieve lights from ElkM1 |
def new_table(self, name, add_id=True, **kwargs):
"""
Create a new table, if it does not exist, or update an existing table if it does
:param name: Table name
:param add_id: If True, add an id field ( default is True )
:param kwargs: Other options passed to table object
... | Create a new table, if it does not exist, or update an existing table if it does
:param name: Table name
:param add_id: If True, add an id field ( default is True )
:param kwargs: Other options passed to table object
:return: |
def bsp_father(node: tcod.bsp.BSP) -> Optional[tcod.bsp.BSP]:
"""
.. deprecated:: 2.0
Use :any:`BSP.parent` instead.
"""
return node.parent | .. deprecated:: 2.0
Use :any:`BSP.parent` instead. |
def _repr_pretty_(self, p, cycle):
"""method that defines ``Struct``'s pretty printing rules for iPython
Args:
p (IPython.lib.pretty.RepresentationPrinter): pretty printer object
cycle (bool): is ``True`` if pretty detected a cycle
"""
if cycle:
p.tex... | method that defines ``Struct``'s pretty printing rules for iPython
Args:
p (IPython.lib.pretty.RepresentationPrinter): pretty printer object
cycle (bool): is ``True`` if pretty detected a cycle |
def retry_on_integrity_error(self):
"""Re-raise :class:`~sqlalchemy.exc.IntegrityError` as `DBSerializationError`.
This is mainly useful to handle race conditions in atomic
blocks. For example, even if prior to a database INSERT we
have verified that there is no existing row with the gi... | Re-raise :class:`~sqlalchemy.exc.IntegrityError` as `DBSerializationError`.
This is mainly useful to handle race conditions in atomic
blocks. For example, even if prior to a database INSERT we
have verified that there is no existing row with the given
primary key, we still may get an
... |
def get_selection(self):
"""
Read text from the X selection
Usage: C{clipboard.get_selection()}
@return: text contents of the mouse selection
@rtype: C{str}
@raise Exception: if no text was found in the selection
"""
Gdk.threads_enter()
t... | Read text from the X selection
Usage: C{clipboard.get_selection()}
@return: text contents of the mouse selection
@rtype: C{str}
@raise Exception: if no text was found in the selection |
def _add_item(self, dim_vals, data, sort=True, update=True):
"""
Adds item to the data, applying dimension types and ensuring
key conforms to Dimension type and values.
"""
sort = sort and self.sort
if not isinstance(dim_vals, tuple):
dim_vals = (dim_vals,)
... | Adds item to the data, applying dimension types and ensuring
key conforms to Dimension type and values. |
def _validate(self, msg):
"""Validate an Enum value.
Raises:
TypeError if the value is not an instance of self._message_type.
"""
if not isinstance(msg, self._message_type):
raise TypeError('Expected a %s instance for %s property',
self._message_type.__name__,
... | Validate an Enum value.
Raises:
TypeError if the value is not an instance of self._message_type. |
def _makeColorableInstance(self, clazz, args, kwargs):
"""
Create an object, if fill, stroke or strokewidth
is not specified, get them from the _canvas
:param clazz:
:param args:
:param kwargs:
:return:
"""
kwargs = dict(kwargs)
fill = kw... | Create an object, if fill, stroke or strokewidth
is not specified, get them from the _canvas
:param clazz:
:param args:
:param kwargs:
:return: |
def GpuUsage(**kargs):
""" Get the current GPU usage of available GPUs """
usage = (False, None)
gpu_status = {'vent_usage': {'dedicated': [], 'mem_mb': {}}}
path_dirs = PathDirs(**kargs)
path_dirs.host_config()
template = Template(template=path_dirs.cfg_file)
# get running jobs using gpus... | Get the current GPU usage of available GPUs |
def set(self, id, translation, domain='messages'):
"""
Sets a message translation.
"""
assert isinstance(id, (str, unicode))
assert isinstance(translation, (str, unicode))
assert isinstance(domain, (str, unicode))
self.add({id: translation}, domain) | Sets a message translation. |
def workers(self, pattern=None, negate=False, stats=True):
"""Filters known workers and prints their current status.
Args:
Filter args:
pattern (Optional[str]): a pattern to filter workers
ex.: '^dispatch|^email' to filter names starting with that
... | Filters known workers and prints their current status.
Args:
Filter args:
pattern (Optional[str]): a pattern to filter workers
ex.: '^dispatch|^email' to filter names starting with that
or 'dispatch.*123456' to filter that exact name and nu... |
def frames(self):
"""
Returns the length of a video stream in frames. Returns 0 if not a video stream.
"""
f=0
if self.isVideo() or self.isAudio():
if self.__dict__['nb_frames']:
try:
f=int(self.__dict__['nb_frames'])
... | Returns the length of a video stream in frames. Returns 0 if not a video stream. |
def get_required_status_checks(self):
"""
:calls: `GET /repos/:owner/:repo/branches/:branch/protection/required_status_checks <https://developer.github.com/v3/repos/branches>`_
:rtype: :class:`github.RequiredStatusChecks.RequiredStatusChecks`
"""
headers, data = self._requester.r... | :calls: `GET /repos/:owner/:repo/branches/:branch/protection/required_status_checks <https://developer.github.com/v3/repos/branches>`_
:rtype: :class:`github.RequiredStatusChecks.RequiredStatusChecks` |
def create_legacy_graph_tasks():
"""Create tasks to recursively parse the legacy graph."""
return [
transitive_hydrated_targets,
transitive_hydrated_target,
hydrated_targets,
hydrate_target,
find_owners,
hydrate_sources,
hydrate_bundles,
RootRule(OwnersRequest),
] | Create tasks to recursively parse the legacy graph. |
def _recomputeRecordFromKNN(self, record):
"""
returns the classified labeling of record
"""
inputs = {
"categoryIn": [None],
"bottomUpIn": self._getStateAnomalyVector(record),
}
outputs = {"categoriesOut": numpy.zeros((1,)),
"bestPrototypeIndices":numpy.zeros((1,)),
... | returns the classified labeling of record |
def _GetArgsDescription(self, args_type):
"""Get a simplified description of the args_type for a flow."""
args = {}
if args_type:
for type_descriptor in args_type.type_infos:
if not type_descriptor.hidden:
args[type_descriptor.name] = {
"description": type_descriptor.de... | Get a simplified description of the args_type for a flow. |
def eventFilter(self, widget, event):
"""A filter to control the zooming and panning of the figure canvas."""
# ---- Zooming
if event.type() == QEvent.Wheel:
modifiers = QApplication.keyboardModifiers()
if modifiers == Qt.ControlModifier:
if event.angleDe... | A filter to control the zooming and panning of the figure canvas. |
def build_schema(m, c_c):
'''
Build an xsd schema from a bridgepoint component.
'''
schema = ET.Element('xs:schema')
schema.set('xmlns:xs', 'http://www.w3.org/2001/XMLSchema')
global_filter = lambda selected: ooaofooa.is_global(selected)
for s_dt in m.select_many('S_DT', global_filter):
... | Build an xsd schema from a bridgepoint component. |
def metadata_path(self):
"""Determine the metadata path."""
xml_name = _granule_identifier_to_xml_name(self.granule_identifier)
metadata_path = os.path.join(self.granule_path, xml_name)
try:
assert os.path.isfile(metadata_path) or \
metadata_path in self.datas... | Determine the metadata path. |
def grok_template_file(src):
"""Determine the real deal template file"""
if not src.startswith('builtin:'):
return abspath(src)
builtin = src.split(':')[1]
builtin = "templates/%s.j2" % builtin
return resource_filename(__name__, builtin) | Determine the real deal template file |
def add_options(self, parser, env=None):
"""Non-camel-case version of func name for backwards compatibility.
.. warning ::
DEPRECATED: Do not use this method,
use :meth:`options <nose.plugins.base.IPluginInterface.options>`
instead.
"""
# FIXME raise d... | Non-camel-case version of func name for backwards compatibility.
.. warning ::
DEPRECATED: Do not use this method,
use :meth:`options <nose.plugins.base.IPluginInterface.options>`
instead. |
def set_token(self):
"""Get token using Client ID/Secret credentials.
:raises: AuthenticationError if credentials invalid, or call fails.
"""
super(ServicePrincipalCredentials, self).set_token()
try:
token = self._context.acquire_token_with_client_credentials(
... | Get token using Client ID/Secret credentials.
:raises: AuthenticationError if credentials invalid, or call fails. |
def customize_form_field(self, name, field):
"""
Allows views to customize their form fields. By default, Smartmin replaces the plain textbox
date input with it's own DatePicker implementation.
"""
if isinstance(field, forms.fields.DateField) and isinstance(field.widget, forms.w... | Allows views to customize their form fields. By default, Smartmin replaces the plain textbox
date input with it's own DatePicker implementation. |
def rename_state_fluent(name: str) -> str:
'''Returns current state fluent canonical name.
Args:
name (str): The next state fluent name.
Returns:
str: The current state fluent name.
'''
i = name.index('/')
functor = name[:i]
arity = name[i+1:]
return "{}'/{}".format(fun... | Returns current state fluent canonical name.
Args:
name (str): The next state fluent name.
Returns:
str: The current state fluent name. |
def convert(self, request, response, data):
"""
Performs the desired formatting.
:param request: The webob Request object describing the
request.
:param response: The webob Response object describing the
response.
:param data: The... | Performs the desired formatting.
:param request: The webob Request object describing the
request.
:param response: The webob Response object describing the
response.
:param data: The data dictionary list returned by the
prepa... |
def update_detail(self, request):
"""
:param request: an apiv2 request object
:return: request if successful with entities set on request
"""
entity = request.context_params[self.detail_property_name]
updated_entity = self.update_entity(
request,
e... | :param request: an apiv2 request object
:return: request if successful with entities set on request |
def alias(cls, typemap, base, *names):
""" Declare an alternate (humane) name for a measurement protocol parameter """
cls.parameter_alias[base] = (typemap, base)
for i in names:
cls.parameter_alias[i] = (typemap, base) | Declare an alternate (humane) name for a measurement protocol parameter |
def send(x, inter=0, loop=0, count=None, verbose=None, realtime=None, *args, **kargs):
"""Send packets at layer 3
send(packets, [inter=0], [loop=0], [verbose=conf.verb]) -> None"""
__gen_send(conf.L3socket(*args, **kargs), x, inter=inter, loop=loop, count=count,verbose=verbose, realtime=realtime) | Send packets at layer 3
send(packets, [inter=0], [loop=0], [verbose=conf.verb]) -> None |
def get_queues(self, service_desk_id, include_count=False, start=0, limit=50):
"""
Returns a page of queues defined inside a service desk, for a given service desk ID.
The returned queues will include an issue count for each queue (represented in issueCount field)
if the query param incl... | Returns a page of queues defined inside a service desk, for a given service desk ID.
The returned queues will include an issue count for each queue (represented in issueCount field)
if the query param includeCount is set to true (defaults to false).
Permissions: The calling user must be an agen... |
def scoreatpercentile(data,per,axis=0):
'like the function in scipy.stats but with an axis argument and works on arrays'
a = np.sort(data,axis=axis)
idx = per/100. * (data.shape[axis]-1)
if (idx % 1 == 0):
return a[[slice(None) if ii != axis else idx for ii in range(a.ndim)]]
else:
... | like the function in scipy.stats but with an axis argument and works on arrays |
def extend( self, itemseq ):
"""
Add sequence of elements to end of ParseResults list of elements.
Example::
patt = OneOrMore(Word(alphas))
# use a parse action to append the reverse of the matched strings, to make a palindrome
def make_palindrome(tokens):
... | Add sequence of elements to end of ParseResults list of elements.
Example::
patt = OneOrMore(Word(alphas))
# use a parse action to append the reverse of the matched strings, to make a palindrome
def make_palindrome(tokens):
tokens.extend(reversed([t[::-1] f... |
def expected_number_of_transactions_in_first_n_periods(self, n):
r"""
Return expected number of transactions in first n n_periods.
Expected number of transactions occurring across first n transaction
opportunities.
Used by Fader and Hardie to assess in-sample fit.
.. ma... | r"""
Return expected number of transactions in first n n_periods.
Expected number of transactions occurring across first n transaction
opportunities.
Used by Fader and Hardie to assess in-sample fit.
.. math:: Pr(X(n) = x| \alpha, \beta, \gamma, \delta)
See (7) in Fade... |
def run(self, visitor):
"""
:param visitor: visitor to call with every node in the domain tree.
:type visitor: subclass of
:class:`everest.entities.traversal.DomainVisitor`
"""
if __debug__:
self.__log_run(visitor)
visitor.prepare()
if self... | :param visitor: visitor to call with every node in the domain tree.
:type visitor: subclass of
:class:`everest.entities.traversal.DomainVisitor` |
def detach_all_classes(self):
"""
Detach from all tracked classes.
"""
classes = list(self._observers.keys())
for cls in classes:
self.detach_class(cls) | Detach from all tracked classes. |
def list_directories(dir_pathname,
recursive=True,
topdown=True,
followlinks=False):
"""
Enlists all the directories using their absolute paths within the specified
directory, optionally recursively.
:param dir_pathname:
The directo... | Enlists all the directories using their absolute paths within the specified
directory, optionally recursively.
:param dir_pathname:
The directory to traverse.
:param recursive:
``True`` for walking recursively through the directory tree;
``False`` otherwise.
:param topdown:
... |
def on_click_dispatcher(self, module_name, event, command):
"""
Dispatch on_click config parameters to either:
- Our own methods for special py3status commands (listed below)
- The i3-msg program which is part of i3wm
"""
if command is None:
return
... | Dispatch on_click config parameters to either:
- Our own methods for special py3status commands (listed below)
- The i3-msg program which is part of i3wm |
def lazy_approximate_personalized_pagerank(s,
r,
w_i,
a_i,
out_degree,
in_degree,
... | Calculates the approximate personalized PageRank starting from a seed node with self-loops.
Introduced in: Andersen, R., Chung, F., & Lang, K. (2006, October).
Local graph partitioning using pagerank vectors.
In Foundations of Computer Science, 2006. FOCS'06. 47th Annual IEEE ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.