code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def main(argv=None): # pragma: no coverage
""" Main entry point when the user runs the `trytravis` command. """
try:
colorama.init()
if argv is None:
argv = sys.argv[1:]
_main(argv)
except RuntimeError as e:
print(colorama.Fore.RED + 'ERROR: ' +
str... | Main entry point when the user runs the `trytravis` command. |
def num_rings(self):
"""The number of rings a device with
the :attr:`~libinput.constant.DeviceCapability.TABLET_PAD`
capability provides.
Returns:
int: The number of rings or 0 if the device has no rings.
Raises:
AttributeError
"""
num = self._libinput.libinput_device_tablet_pad_get_num_rings(
... | The number of rings a device with
the :attr:`~libinput.constant.DeviceCapability.TABLET_PAD`
capability provides.
Returns:
int: The number of rings or 0 if the device has no rings.
Raises:
AttributeError |
def open_interpreter(self, fnames):
"""Open interpreter"""
for path in sorted(fnames):
self.sig_open_interpreter.emit(path) | Open interpreter |
def write_early_data(self, data: bytes) -> int:
"""Returns the number of (encrypted) bytes sent.
"""
if self._is_handshake_completed:
raise IOError('SSL Handshake was completed; cannot send early data.')
# Pass the cleartext data to the SSL engine
self._ssl.write_ear... | Returns the number of (encrypted) bytes sent. |
def getsize(store, path=None):
"""Compute size of stored items for a given path. If `store` provides a `getsize`
method, this will be called, otherwise will return -1."""
path = normalize_storage_path(path)
if hasattr(store, 'getsize'):
# pass through
return store.getsize(path)
elif ... | Compute size of stored items for a given path. If `store` provides a `getsize`
method, this will be called, otherwise will return -1. |
def param(f):
'''
The @param decorator, usable in an immutable class (see immutable), specifies that the following
function is actually a transformation on an input parameter; the parameter is required, and is
set to the value returned by the function decorated by the parameter; i.e., if you decorate t... | The @param decorator, usable in an immutable class (see immutable), specifies that the following
function is actually a transformation on an input parameter; the parameter is required, and is
set to the value returned by the function decorated by the parameter; i.e., if you decorate the
function abc with @... |
def submit_sample(self, filepath, filename, tags=['TheHive']):
"""
Uploads a new sample to VMRay api. Filename gets sent base64 encoded.
:param filepath: path to sample
:type filepath: str
:param filename: filename of the original file
:type filename: str
:param ... | Uploads a new sample to VMRay api. Filename gets sent base64 encoded.
:param filepath: path to sample
:type filepath: str
:param filename: filename of the original file
:type filename: str
:param tags: List of tags to apply to the sample
:type tags: list(str)
:re... |
def contains_key(self, key):
"""
Determines whether this multimap contains an entry with the key.
**Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations
of __hash__ and __eq__ defined in key's class.**
:param key: (obje... | Determines whether this multimap contains an entry with the key.
**Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations
of __hash__ and __eq__ defined in key's class.**
:param key: (object), the specified key.
:return: (bool), ... |
def chop(self, bits=1):
"""
Chops a BV into consecutive sub-slices. Obviously, the length of this BV must be a multiple of bits.
:returns: A list of smaller bitvectors, each ``bits`` in length. The first one will be the left-most (i.e.
most significant) bits.
"""
... | Chops a BV into consecutive sub-slices. Obviously, the length of this BV must be a multiple of bits.
:returns: A list of smaller bitvectors, each ``bits`` in length. The first one will be the left-most (i.e.
most significant) bits. |
def hook_point(self, hook_name):
"""Generic function to call modules methods if such method is avalaible
:param hook_name: function name to call
:type hook_name: str
:return:None
"""
self.my_daemon.hook_point(hook_name=hook_name, handle=self) | Generic function to call modules methods if such method is avalaible
:param hook_name: function name to call
:type hook_name: str
:return:None |
def to_date(value, default=None):
"""Tries to convert the passed in value to Zope's DateTime
:param value: The value to be converted to a valid DateTime
:type value: str, DateTime or datetime
:return: The DateTime representation of the value passed in or default
"""
if isinstance(value, DateTim... | Tries to convert the passed in value to Zope's DateTime
:param value: The value to be converted to a valid DateTime
:type value: str, DateTime or datetime
:return: The DateTime representation of the value passed in or default |
def _raw_sql(self, values):
"""Prepare SQL statement consisting of a sequence of WHEN .. THEN statements."""
if isinstance(self.model._meta.pk, CharField):
when_clauses = " ".join(
[self._when("'{}'".format(x), y) for (x, y) in values]
)
else:
... | Prepare SQL statement consisting of a sequence of WHEN .. THEN statements. |
def build_from_info(cls, info):
"""build a Term instance from a dict
Parameters
----------
cls : class
info : dict
contains all information needed to build the term
Return
------
Term instance
"""
info = deepcopy(info)
... | build a Term instance from a dict
Parameters
----------
cls : class
info : dict
contains all information needed to build the term
Return
------
Term instance |
def _compute_soil_linear_factor(cls, pga_rock, imt):
"""
Compute soil linear factor as explained in paragraph 'Functional
Form', page 1706.
"""
if imt.period >= 1:
return np.ones_like(pga_rock)
else:
sl = np.zeros_like(pga_rock)
pga_be... | Compute soil linear factor as explained in paragraph 'Functional
Form', page 1706. |
def find_root( self, rows ):
"""Attempt to find/create a reasonable root node from list/set of rows
rows -- key: PStatRow mapping
TODO: still need more robustness here, particularly in the case of
threaded programs. Should be tracing back each row to root, breaking
cycles by s... | Attempt to find/create a reasonable root node from list/set of rows
rows -- key: PStatRow mapping
TODO: still need more robustness here, particularly in the case of
threaded programs. Should be tracing back each row to root, breaking
cycles by sorting on cumulative time, and then coll... |
def genestats(args):
"""
%prog genestats gffile
Print summary stats, including:
- Number of genes
- Number of single-exon genes
- Number of multi-exon genes
- Number of distinct exons
- Number of genes with alternative transcript variants
- Number of predicted transcripts
- Mean... | %prog genestats gffile
Print summary stats, including:
- Number of genes
- Number of single-exon genes
- Number of multi-exon genes
- Number of distinct exons
- Number of genes with alternative transcript variants
- Number of predicted transcripts
- Mean number of distinct exons per gen... |
def check_perplexities(self, perplexities):
"""Check and correct/truncate perplexities.
If a perplexity is too large, it is corrected to the largest allowed
value. It is then inserted into the list of perplexities only if that
value doesn't already exist in the list.
"""
... | Check and correct/truncate perplexities.
If a perplexity is too large, it is corrected to the largest allowed
value. It is then inserted into the list of perplexities only if that
value doesn't already exist in the list. |
def train(self, x = None, y = None, training_frame = None, fold_column = None,
weights_column = None, validation_frame = None, leaderboard_frame = None, blending_frame = None):
"""
Begins an AutoML task, a background task that automatically builds a number of models
with various a... | Begins an AutoML task, a background task that automatically builds a number of models
with various algorithms and tracks their performance in a leaderboard. At any point
in the process you may use H2O's performance or prediction functions on the resulting
models.
:param x: A list of c... |
def start_new_log(self):
'''open a new dataflash log, reset state'''
filename = self.new_log_filepath()
self.block_cnt = 0
self.logfile = open(filename, 'w+b')
print("DFLogger: logging started (%s)" % (filename))
self.prev_cnt = 0
self.download = 0
self.p... | open a new dataflash log, reset state |
def readline(self):
"""Reads (and optionally parses) a single line."""
line = self.file.readline()
if self.grammar and line:
try:
return self.grammar.parseString(line).asDict()
except ParseException:
return self.readline()
e... | Reads (and optionally parses) a single line. |
def to_netflux(flux):
r"""Compute the netflux from the gross flux.
Parameters
----------
flux : (M, M) ndarray
Matrix of flux values between pairs of states.
Returns
-------
netflux : (M, M) ndarray
Matrix of netflux values between pairs of states.
Notes
-----
... | r"""Compute the netflux from the gross flux.
Parameters
----------
flux : (M, M) ndarray
Matrix of flux values between pairs of states.
Returns
-------
netflux : (M, M) ndarray
Matrix of netflux values between pairs of states.
Notes
-----
The netflux or effective c... |
def pick(self):
""" picks a value accoriding to the given density """
v = random.uniform(0, self.ub)
d = self.dist
c = self.vc - 1
s = self.vc
while True:
s = s / 2
if s == 0:
break
if v <= d[c][1]:
c -= ... | picks a value accoriding to the given density |
def find_signature_input_colocation_error(signature_name, inputs):
"""Returns error message for colocation of signature inputs, or None if ok."""
for input_name, tensor in inputs.items():
expected_colocation_groups = [tf.compat.as_bytes("loc:@" + tensor.op.name)]
if tensor.op.colocation_groups() != expected... | Returns error message for colocation of signature inputs, or None if ok. |
def correct_dmdt(d, dmind, dtind, blrange):
""" Dedisperses and resamples data *in place*.
Drops edges, since it assumes that data is read with overlapping chunks in time.
"""
data = numpyview(data_mem, 'complex64', datashape(d))
data_resamp = numpyview(data_resamp_mem, 'complex64', datashape(d))
... | Dedisperses and resamples data *in place*.
Drops edges, since it assumes that data is read with overlapping chunks in time. |
def process_edge_dijkstra(self, current, neighbor, pred, q, component):
'''
API: process_edge_dijkstra(self, current, neighbor, pred, q, component)
Description:
Used by search() method if the algo argument is 'Dijkstra'. Processes
edges along Dijkstra's algorithm. User does not n... | API: process_edge_dijkstra(self, current, neighbor, pred, q, component)
Description:
Used by search() method if the algo argument is 'Dijkstra'. Processes
edges along Dijkstra's algorithm. User does not need to call this
method directly.
Input:
current: Name of the cu... |
def generateExecutable(self, outpath='.', signed=False):
"""
Generates the executable for this builder in the output path.
:param outpath | <str>
"""
if not (self.runtime() or self.specfile()):
return True
if not self.distributionPath():
... | Generates the executable for this builder in the output path.
:param outpath | <str> |
def set_background_corpus(self, background):
'''
Parameters
----------
background
'''
if issubclass(type(background), TermDocMatrixWithoutCategories):
self._background_corpus = pd.DataFrame(background
.get_te... | Parameters
----------
background |
def get_generator(tweet):
"""
Get information about the application that generated the Tweet
Args:
tweet (Tweet): A Tweet object (or a dictionary)
Returns:
dict: keys are 'link' and 'name', the web link and the name
of the application
Example:
>>> from tweet_parser... | Get information about the application that generated the Tweet
Args:
tweet (Tweet): A Tweet object (or a dictionary)
Returns:
dict: keys are 'link' and 'name', the web link and the name
of the application
Example:
>>> from tweet_parser.getter_methods.tweet_generator import... |
def _leapfrog_integrator_one_step(
target_log_prob_fn,
independent_chain_ndims,
step_sizes,
current_momentum_parts,
current_state_parts,
current_target_log_prob,
current_target_log_prob_grad_parts,
state_gradients_are_stopped=False,
name=None):
"""Applies `num_leapfrog_steps` of th... | Applies `num_leapfrog_steps` of the leapfrog integrator.
Assumes a simple quadratic kinetic energy function: `0.5 ||momentum||**2`.
#### Examples:
##### Simple quadratic potential.
```python
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import tensorflow as tf
from tensorfl... |
def find_mutant_amino_acid_interval(
cdna_sequence,
cdna_first_codon_offset,
cdna_variant_start_offset,
cdna_variant_end_offset,
n_ref,
n_amino_acids):
"""
Parameters
----------
cdna_sequence : skbio.DNA or str
cDNA sequence found in RNAseq data
... | Parameters
----------
cdna_sequence : skbio.DNA or str
cDNA sequence found in RNAseq data
cdna_first_codon_offset : int
Offset into cDNA sequence to first complete codon, lets us skip
past UTR region and incomplete codons.
cdna_variant_start_offset : int
Interbase start... |
def on_message(self, websocket, msg):
'''When a new message arrives, it publishes to all listening clients.
'''
if msg:
lines = []
for li in msg.split('\n'):
li = li.strip()
if li:
lines.append(li)
msg = ' '.... | When a new message arrives, it publishes to all listening clients. |
def random_string(length, charset):
"""
Return a random string of the given length from the
given character set.
:param int length: The length of string to return
:param str charset: A string of characters to choose from
:returns: A random string
:rtype: str
"""
n = len(charset)
... | Return a random string of the given length from the
given character set.
:param int length: The length of string to return
:param str charset: A string of characters to choose from
:returns: A random string
:rtype: str |
def set_post_data(self):
"""
Need to set form data so that validation on all post data occurs and
places newly entered form data on the form object.
"""
self.form.data = self.post_data_dict
# Specifically adding list field keys to the form so they are included
... | Need to set form data so that validation on all post data occurs and
places newly entered form data on the form object. |
def create(**kwargs):
"""
Create and a return a specialized contract based on the given secType,
or a general Contract if secType is not given.
"""
secType = kwargs.get('secType', '')
cls = {
'': Contract,
'STK': Stock,
'OPT': Option,
... | Create and a return a specialized contract based on the given secType,
or a general Contract if secType is not given. |
def Flush(self):
"""Syncs this object with the data store, maintaining object validity."""
if self.locked and self.CheckLease() == 0:
self._RaiseLockError("Flush")
self._WriteAttributes()
self._SyncAttributes()
if self.parent:
self.parent.Flush() | Syncs this object with the data store, maintaining object validity. |
def onDragSelection(self, event):
"""
Set self.df_slice based on user's selection
"""
if self.grid.GetSelectionBlockTopLeft():
#top_left = self.grid.GetSelectionBlockTopLeft()
#bottom_right = self.grid.GetSelectionBlockBottomRight()
# awkward hack to f... | Set self.df_slice based on user's selection |
def salt_master(project, target, module, args=None, kwargs=None):
"""
Execute a `salt` command in the head node
"""
client = project.cluster.head.ssh_client
cmd = ['salt']
cmd.extend(generate_salt_cmd(target, module, args, kwargs))
cmd.append('--timeout=300')
cmd.append('--state-output=... | Execute a `salt` command in the head node |
def create_as_library(cls, url):
"""
Creates a single crawler as in library mode. Crawling will start immediately.
:param url:
:return:
"""
site = {
"crawler": "Download",
"url": url
}
cfg_file_path = os.path.dirname(__file__) + os.... | Creates a single crawler as in library mode. Crawling will start immediately.
:param url:
:return: |
def delete_page_property(self, page_id, page_property):
"""
Delete the page (content) property e.g. delete key of hash
:param page_id: content_id format
:param page_property: key of property
:return:
"""
url = 'rest/api/content/{page_id}/property/{page_property}'.... | Delete the page (content) property e.g. delete key of hash
:param page_id: content_id format
:param page_property: key of property
:return: |
def calculate_perf_100nsec_timer(previous, current, property_name):
"""
PERF_100NSEC_TIMER
https://technet.microsoft.com/en-us/library/cc728274(v=ws.10).aspx
"""
n0 = previous[property_name]
n1 = current[property_name]
d0 = previous["Timestamp_Sys100NS"]
d1 = current["Timestamp_Sys100NS... | PERF_100NSEC_TIMER
https://technet.microsoft.com/en-us/library/cc728274(v=ws.10).aspx |
def unmarshal(self, v):
"""
Convert the value from Strava API format to useful python representation.
If the value does not appear in the choices attribute we log an error rather
than raising an exception as this may be caused by a change to the API upstream
so we want to fail g... | Convert the value from Strava API format to useful python representation.
If the value does not appear in the choices attribute we log an error rather
than raising an exception as this may be caused by a change to the API upstream
so we want to fail gracefully. |
def unique_identifier(self):
"""
Get the unique identifier by looking through ``mods:identifier``
See `specs <https://ocr-d.github.io/mets#unique-id-for-the-document-processed>`_ for details.
"""
for t in IDENTIFIER_PRIORITY:
found = self._tree.getroot().find('.//mod... | Get the unique identifier by looking through ``mods:identifier``
See `specs <https://ocr-d.github.io/mets#unique-id-for-the-document-processed>`_ for details. |
def create_container_definition(container_name, image, port=80, cpu=1.0, memgb=1.5,
environment=None):
'''Makes a python dictionary of container properties.
Args:
container_name: The name of the container.
image (str): Container image string. E.g. nginx.
... | Makes a python dictionary of container properties.
Args:
container_name: The name of the container.
image (str): Container image string. E.g. nginx.
port (int): TCP port number. E.g. 8080.
cpu (float): Amount of CPU to allocate to container. E.g. 1.0.
memgb (float): Memory i... |
def main():
"""
NAME
plotxy_magic.py
DESCRIPTION
Makes simple X,Y plots
INPUT FORMAT
Any MagIC formatted file
SYNTAX
plotxy_magic.py [command line options]
OPTIONS
-h prints this help message
-f FILE to set file name on command rec
-c co... | NAME
plotxy_magic.py
DESCRIPTION
Makes simple X,Y plots
INPUT FORMAT
Any MagIC formatted file
SYNTAX
plotxy_magic.py [command line options]
OPTIONS
-h prints this help message
-f FILE to set file name on command rec
-c col1 col2 specify columns ... |
def store(self):
'''
Write content of the entire cache to disk
'''
if msgpack is None:
log.error('Cache cannot be stored on disk: msgpack is missing')
else:
# TODO Dir hashing?
try:
with salt.utils.files.fopen(self._path, 'wb+')... | Write content of the entire cache to disk |
def copy(self):
""" Return copy of self
Returns:
Identifier object
"""
tokens = ([t for t in self.tokens]
if isinstance(self.tokens, list) else self.tokens)
return Identifier(tokens, 0) | Return copy of self
Returns:
Identifier object |
def add_group_members(self, members):
"""Add a new group member to the groups list
:param members: member name
:type members: str
:return: None
"""
if not isinstance(members, list):
members = [members]
if not getattr(self, 'group_members', None):
... | Add a new group member to the groups list
:param members: member name
:type members: str
:return: None |
def _bubbleP(cls, T):
"""Using ancillary equation return the pressure of bubble point"""
c = cls._blend["bubble"]
Tj = cls._blend["Tj"]
Pj = cls._blend["Pj"]
Tita = 1-T/Tj
suma = 0
for i, n in zip(c["i"], c["n"]):
suma += n*Tita**(i/2.)
P = Pj... | Using ancillary equation return the pressure of bubble point |
def run(self, agent_host):
"""run the agent on the world"""
total_reward = 0
self.prev_s = None
self.prev_a = None
is_first_action = True
# main loop:
world_state = agent_host.getWorldState()
while world_state.is_mission_running... | run the agent on the world |
def mk_function(metamodel, s_sync):
'''
Create a python function from a BridgePoint function.
'''
action = s_sync.Action_Semantics_internal
label = s_sync.Name
return lambda **kwargs: interpret.run_function(metamodel, label,
action, kwargs) | Create a python function from a BridgePoint function. |
def pad_to_size(text, x, y):
"""
Adds whitespace to text to center it within a frame of the given
dimensions.
"""
input_lines = text.rstrip().split("\n")
longest_input_line = max(map(len, input_lines))
number_of_input_lines = len(input_lines)
x = max(x, longest_input_line)
y = max(y,... | Adds whitespace to text to center it within a frame of the given
dimensions. |
def get_breadcrumbs(self):
"""
Breadcrumb format: (('name', 'url'), ...) or None if not used.
"""
if not self.breadcrumbs:
return None
else:
allowed_breadcrumbs = []
for breadcrumb in self.breadcrumbs:
# check permission based ... | Breadcrumb format: (('name', 'url'), ...) or None if not used. |
def update(self):
"""
Handle update events on bokeh server.
"""
if not self._queue:
return
dim, widget_type, attr, old, new = self._queue[-1]
self._queue = []
dim_label = dim.pprint_label
label, widget = self.widgets[dim_label]
if wid... | Handle update events on bokeh server. |
def is_list_like(obj, allow_sets=True):
"""
Check if the object is list-like.
Objects that are considered list-like are for example Python
lists, tuples, sets, NumPy arrays, and Pandas Series.
Strings and datetime objects, however, are not considered list-like.
Parameters
----------
o... | Check if the object is list-like.
Objects that are considered list-like are for example Python
lists, tuples, sets, NumPy arrays, and Pandas Series.
Strings and datetime objects, however, are not considered list-like.
Parameters
----------
obj : The object to check
allow_sets : boolean, d... |
def _calculate_Hfr(self, T):
"""
Calculate the enthalpy flow rate of the stream at the specified
temperature.
:param T: Temperature. [°C]
:returns: Enthalpy flow rate. [kWh/h]
"""
if self.isCoal:
return self._calculate_Hfr_coal(T)
Hfr = 0.0... | Calculate the enthalpy flow rate of the stream at the specified
temperature.
:param T: Temperature. [°C]
:returns: Enthalpy flow rate. [kWh/h] |
def channels(self):
"""
List of channels of this slack team
"""
if not self._channels:
self._channels = self._call_api('channels.list')['channels']
return self._channels | List of channels of this slack team |
def _handle_get(self, request_data):
"""
An OCSP GET request contains the DER-in-base64 encoded OCSP request in the
HTTP request URL.
"""
der = base64.b64decode(request_data)
ocsp_request = self._parse_ocsp_request(der)
return self._build_http_response(ocsp_reques... | An OCSP GET request contains the DER-in-base64 encoded OCSP request in the
HTTP request URL. |
def setLength(self, personID, length):
"""setLength(string, double) -> None
Sets the length in m for the given person.
"""
self._connection._sendDoubleCmd(
tc.CMD_SET_PERSON_VARIABLE, tc.VAR_LENGTH, personID, length) | setLength(string, double) -> None
Sets the length in m for the given person. |
def aggregate(input, **params):
"""
Returns aggregate
:param input:
:param params:
:return:
"""
PARAM_CFG_EXTRACT = 'extract'
PARAM_CFG_SUBSTITUTE = 'substitute'
PARAM_CFG_AGGREGATE = 'aggregate'
AGGR_FIELD = 'field'
AGGR_FUNC = 'func'
extract_params = params.get(PARAM_C... | Returns aggregate
:param input:
:param params:
:return: |
def metapolicy(self, permitted):
"""
Sets metapolicy to ``permitted``. (only applicable to master
policy files). Acceptable values correspond to those listed in
Section 3(b)(i) of the crossdomain.xml specification, and are
also available as a set of constants defined in this modu... | Sets metapolicy to ``permitted``. (only applicable to master
policy files). Acceptable values correspond to those listed in
Section 3(b)(i) of the crossdomain.xml specification, and are
also available as a set of constants defined in this module.
By default, Flash assumes a value of ``m... |
async def connect(self) -> None:
"""Open a connection to the defined server."""
def protocol_factory() -> Protocol:
return Protocol(client=self)
_, protocol = await self.loop.create_connection(
protocol_factory,
host=self.host,
port=self.port,
... | Open a connection to the defined server. |
def bisect(func, a, b, xtol=1e-6, errorcontrol=True,
testkwargs=dict(), outside='extrapolate',
ascending=None,
disp=False):
"""Find root by bysection search.
If the function evaluation is noisy then use `errorcontrol=True` for adaptive
sampling of the function during the bi... | Find root by bysection search.
If the function evaluation is noisy then use `errorcontrol=True` for adaptive
sampling of the function during the bisection search.
Parameters
----------
func: callable
Function of which the root should be found. If `errorcontrol=True`
then the functi... |
def getAllSavedQueries(self, projectarea_id=None, projectarea_name=None,
creator=None, saved_query_name=None):
"""Get all saved queries created by somebody (optional)
in a certain project area (optional, either `projectarea_id`
or `projectarea_name` is needed if specif... | Get all saved queries created by somebody (optional)
in a certain project area (optional, either `projectarea_id`
or `projectarea_name` is needed if specified)
If `saved_query_name` is specified, only the saved queries match the
name will be fetched.
Note: only if `creator` is ... |
def pre_parse_and_validate_signavio(self, bpmn, filename):
"""
This is the Signavio specific editor hook for pre-parsing and
validation.
A subclass can override this method to provide additional parseing or
validation. It should call the parent method first.
:param bpmn... | This is the Signavio specific editor hook for pre-parsing and
validation.
A subclass can override this method to provide additional parseing or
validation. It should call the parent method first.
:param bpmn: an lxml tree of the bpmn content
:param filename: the source file na... |
def previous_row(self):
"""Move to previous row from currently selected row."""
row = self.currentIndex().row()
rows = self.source_model.rowCount()
if row == 0:
row = rows
self.selectRow(row - 1) | Move to previous row from currently selected row. |
def refresh_modules(self, module_string=None, exact=True):
"""
Update modules.
if module_string is None all modules are refreshed
if module_string then modules with the exact name or those starting
with the given string depending on exact parameter will be refreshed.
If a... | Update modules.
if module_string is None all modules are refreshed
if module_string then modules with the exact name or those starting
with the given string depending on exact parameter will be refreshed.
If a module is an i3status one then we refresh i3status.
To prevent abuse, ... |
def get_register_func(base_class, nickname):
"""Get registrator function.
Parameters
----------
base_class : type
base class for classes that will be reigstered
nickname : str
nickname of base_class for logging
Returns
-------
a registrator function
"""
if base_... | Get registrator function.
Parameters
----------
base_class : type
base class for classes that will be reigstered
nickname : str
nickname of base_class for logging
Returns
-------
a registrator function |
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(NetworkCollector, self).get_default_config()
config.update({
'path': 'network',
'interfaces': ['eth', 'bond', 'em', 'p1p', 'eno', 'enp', 'ens',
... | Returns the default collector settings |
def add_exception_handler(self, exception_handler):
# type: (AbstractExceptionHandler) -> None
"""Register input to the exception handlers list.
:param exception_handler: Exception Handler instance to be
registered.
:type exception_handler: AbstractExceptionHandler
:... | Register input to the exception handlers list.
:param exception_handler: Exception Handler instance to be
registered.
:type exception_handler: AbstractExceptionHandler
:return: None |
def _get_asset_urls(self, asset_id):
"""
Get list of asset urls and file names. This method may internally
use AssetRetriever to extract `asset` element types.
@param asset_id: Asset ID.
@type asset_id: str
@return List of dictionaries with asset file names and urls.
... | Get list of asset urls and file names. This method may internally
use AssetRetriever to extract `asset` element types.
@param asset_id: Asset ID.
@type asset_id: str
@return List of dictionaries with asset file names and urls.
@rtype [{
'name': '<filename.ext>'
... |
async def create_local_did(self, seed: str = None, loc_did: str = None, metadata: dict = None) -> DIDInfo:
"""
Create and store a new local DID for use in pairwise DID relations.
:param seed: seed from which to create (default random)
:param loc_did: local DID value (default None to let... | Create and store a new local DID for use in pairwise DID relations.
:param seed: seed from which to create (default random)
:param loc_did: local DID value (default None to let indy-sdk generate)
:param metadata: metadata to associate with the local DID
(operation always sets 'since... |
def service_group(self, service_name):
"""
Args:
service_name: the name of the service in the service registry
Returns:
the name of the group the service is in, or None of the service was not found
"""
for group in EFConfig.SERVICE_GROUPS:
if self.services(group).has_key(service_na... | Args:
service_name: the name of the service in the service registry
Returns:
the name of the group the service is in, or None of the service was not found |
def summarize(self):
""" G protein annotation summary in a text format
:return: A string summary of the annotation
:rtype: str
"""
data = [
['Sequence ID', self.seqrecord.id],
['G domain', ' '.join(self.gdomain_regions) if self.gdomain_regions else None],... | G protein annotation summary in a text format
:return: A string summary of the annotation
:rtype: str |
def decode(self, encoded):
""" Decodes an object.
Args:
object_ (object): Encoded object.
Returns:
object: Object decoded.
"""
if self.enforce_reversible:
self.enforce_reversible = False
if self.encode(self.decode(encoded)) != enc... | Decodes an object.
Args:
object_ (object): Encoded object.
Returns:
object: Object decoded. |
def fetch_pillar(self):
'''
In the event of a cache miss, we need to incur the overhead of caching
a new pillar.
'''
log.debug('Pillar cache getting external pillar with ext: %s', self.ext)
fresh_pillar = Pillar(self.opts,
self.grains,
... | In the event of a cache miss, we need to incur the overhead of caching
a new pillar. |
def stop_change(self):
"""Stop changing light level manually"""
self.logger.info("Dimmer %s stop_change", self.device_id)
self.hub.direct_command(self.device_id, '18', '00')
success = self.hub.check_success(self.device_id, '18', '00')
if success:
self.logger.info("Di... | Stop changing light level manually |
def load(stream, Loader=None):
"""
Parse the first YAML document in a stream
and produce the corresponding Python object.
"""
if Loader is None:
load_warning('load')
Loader = FullLoader
loader = Loader(stream)
try:
return loader.get_single_data()
finally:
... | Parse the first YAML document in a stream
and produce the corresponding Python object. |
def extract_tar (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a TAR archive with the tarfile Python module."""
try:
with tarfile.open(archive) as tfile:
tfile.extractall(path=outdir)
except Exception as err:
msg = "error extracting %s: %s" % (archive, er... | Extract a TAR archive with the tarfile Python module. |
def migrate_file(src_id, location_name, post_fixity_check=False):
"""Task to migrate a file instance to a new location.
.. note:: If something goes wrong during the content copy, the destination
file instance is removed.
:param src_id: The :class:`invenio_files_rest.models.FileInstance` ID.
:p... | Task to migrate a file instance to a new location.
.. note:: If something goes wrong during the content copy, the destination
file instance is removed.
:param src_id: The :class:`invenio_files_rest.models.FileInstance` ID.
:param location_name: Where to migrate the file.
:param post_fixity_che... |
def cli(ctx, ftdi_enable, ftdi_disable, serial_enable, serial_disable):
"""Manage FPGA boards drivers."""
exit_code = 0
if ftdi_enable: # pragma: no cover
exit_code = Drivers().ftdi_enable()
elif ftdi_disable: # pragma: no cover
exit_code = Drivers().ftdi_disable()
elif serial_... | Manage FPGA boards drivers. |
def _got_srv(self, addrs):
"""Handle SRV lookup result.
:Parameters:
- `addrs`: properly sorted list of (hostname, port) tuples
"""
with self.lock:
if not addrs:
self._dst_service = None
if self._dst_port:
self.... | Handle SRV lookup result.
:Parameters:
- `addrs`: properly sorted list of (hostname, port) tuples |
def min_ems(self, value: float) -> 'Size':
"""Set the minimum size in ems."""
raise_not_number(value)
self.minimum = '{}em'.format(value)
return self | Set the minimum size in ems. |
def recode(self, table: pd.DataFrame, validate=False) -> pd.DataFrame:
"""Pass the provided series obj through each recoder function sequentially and return the final result.
Args:
table (pd.DataFrame): A dataframe on which to apply recoding logic.
validate (bool): If ``True``, ... | Pass the provided series obj through each recoder function sequentially and return the final result.
Args:
table (pd.DataFrame): A dataframe on which to apply recoding logic.
validate (bool): If ``True``, recoded table must pass validation tests. |
def _compose_mro(cls, types): # noqa
"""Calculates the method resolution order for a given class *cls*.
Includes relevant abstract base classes (with their respective bases) from
the *types* iterable. Uses a modified C3 linearization algorithm.
"""
bases = set(cls.__mro__)
# Remove entries w... | Calculates the method resolution order for a given class *cls*.
Includes relevant abstract base classes (with their respective bases) from
the *types* iterable. Uses a modified C3 linearization algorithm. |
def burn(self):
"""
Process the template with the data and
config which has been set and return the resulting SVG.
Raises ValueError when no data set has
been added to the graph object.
"""
if not self.data:
raise ValueError("No data available")
if hasattr(self, 'calculations'):
self.calculation... | Process the template with the data and
config which has been set and return the resulting SVG.
Raises ValueError when no data set has
been added to the graph object. |
def VerifyStructure(self, parser_mediator, line):
"""Verifies if a line from a text file is in the expected format.
Args:
parser_mediator (ParserMediator): parser mediator.
line (str): line from a text file.
Returns:
bool: True if the line is in the expected format, False if not.
"""... | Verifies if a line from a text file is in the expected format.
Args:
parser_mediator (ParserMediator): parser mediator.
line (str): line from a text file.
Returns:
bool: True if the line is in the expected format, False if not. |
def get_relationships_by_query(self, relationship_query):
"""Gets a list of ``Relationships`` matching the given relationship query.
arg: relationship_query
(osid.relationship.RelationshipQuery): the relationship
query
return: (osid.relationship.RelationshipLi... | Gets a list of ``Relationships`` matching the given relationship query.
arg: relationship_query
(osid.relationship.RelationshipQuery): the relationship
query
return: (osid.relationship.RelationshipList) - the returned
``RelationshipList``
raise... |
def fit(self, matrix, epochs=5, no_threads=2, verbose=False):
"""
Estimate the word embeddings.
Parameters:
- scipy.sparse.coo_matrix matrix: coocurrence matrix
- int epochs: number of training epochs
- int no_threads: number of training threads
- bool verbose: p... | Estimate the word embeddings.
Parameters:
- scipy.sparse.coo_matrix matrix: coocurrence matrix
- int epochs: number of training epochs
- int no_threads: number of training threads
- bool verbose: print progress messages if True |
def get_messages(session, query, limit=10, offset=0):
"""
Get one or more messages
"""
query['limit'] = limit
query['offset'] = offset
# GET /api/messages/0.1/messages
response = make_get_request(session, 'messages', params_data=query)
json_data = response.json()
if response.status_... | Get one or more messages |
def __reset_crosshair(self):
"""
redraw the cross-hair on the horizontal slice plot
Parameters
----------
x: int
the x image coordinate
y: int
the y image coordinate
Returns
-------
"""
self.lhor.set_ydata(self.y_c... | redraw the cross-hair on the horizontal slice plot
Parameters
----------
x: int
the x image coordinate
y: int
the y image coordinate
Returns
------- |
def remove(self, value):
"""Remove an entry from the catalog """
ret = libxml2mod.xmlACatalogRemove(self._o, value)
return ret | Remove an entry from the catalog |
def get_dimension_type(self, dim):
"""Get the type of the requested dimension.
Type is determined by Dimension.type attribute or common
type of the dimension values, otherwise None.
Args:
dimension: Dimension to look up by name or by index
Returns:
Decl... | Get the type of the requested dimension.
Type is determined by Dimension.type attribute or common
type of the dimension values, otherwise None.
Args:
dimension: Dimension to look up by name or by index
Returns:
Declared type of values along the dimension |
def _validate_param(param): # pylint: disable=too-many-branches
""" Ensure the filter cast properly according to the operator """
detail = None
if param.oper not in goldman.config.QUERY_FILTERS:
detail = 'The query filter {} is not a supported ' \
'operator. Please change {} & re... | Ensure the filter cast properly according to the operator |
def get_power_status() -> SystemPowerStatus:
"""Retrieves the power status of the system.
The status indicates whether the system is running on AC or DC power,
whether the battery is currently charging, how much battery life remains,
and if battery saver is on or off.
:raises OSError: if the call ... | Retrieves the power status of the system.
The status indicates whether the system is running on AC or DC power,
whether the battery is currently charging, how much battery life remains,
and if battery saver is on or off.
:raises OSError: if the call to GetSystemPowerStatus fails
:return: the power... |
def poll(self):
"""
Check if the pod is still running.
Uses the same interface as subprocess.Popen.poll(): if the pod is
still running, returns None. If the pod has exited, return the
exit code if we can determine it, or 1 if it has exited but we
don't know how. These ... | Check if the pod is still running.
Uses the same interface as subprocess.Popen.poll(): if the pod is
still running, returns None. If the pod has exited, return the
exit code if we can determine it, or 1 if it has exited but we
don't know how. These are the return values JupyterHub exp... |
def _finish_progress(self):
"""
Mark the progressbar as finished.
:return: None
"""
if self._show_progressbar:
if self._progressbar is None:
self._initialize_progressbar()
if self._progressbar is not None:
self._progressbar... | Mark the progressbar as finished.
:return: None |
def validate(self):
"""Checks that at least required params exist"""
required = ['token', 'content']
valid_data = {
'exp_record': (['type', 'format'], 'record',
'Exporting record but content is not record'),
'imp_record': (['type', 'overwriteBehavior', 'da... | Checks that at least required params exist |
def encrypt(s, base64 = False):
"""
对称加密函数
"""
e = _cipher().encrypt(s)
return base64 and b64encode(e) or e | 对称加密函数 |
def get_parser(parser=None):
"""Get parser for mpu."""
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
if parser is None:
parser = ArgumentParser(description=__doc__,
formatter_class=ArgumentDefaultsHelpFormatter)
subparsers = parser.add_subpars... | Get parser for mpu. |
def setRepoData(self, searchString, category="", extension="", math=False, game=False, searchFiles=False):
"""Call this function with all the settings to use for future operations on a repository, must be called FIRST"""
self.searchString = searchString
self.category = category
self.math = math
self.game = ga... | Call this function with all the settings to use for future operations on a repository, must be called FIRST |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.