code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def update_pos(pos_dict, start_key, nbr=2):
"Update the `pos_dict` by moving all positions after `start_key` by `nbr`."
for key,idx in pos_dict.items():
if str.lower(key) >= str.lower(start_key): pos_dict[key] += nbr
return pos_dict | Update the `pos_dict` by moving all positions after `start_key` by `nbr`. |
def to_phy(self):
"""Convert this to the standard :class:`pyparser.capture.common.PhyInfo`
class.
"""
kwargs = {}
for attr in ['signal', 'noise', 'freq_mhz', 'fcs_error', 'rate', 'mcs',
'len', 'caplen', 'epoch_ts', 'end_epoch_ts']:
kwargs[attr] = ... | Convert this to the standard :class:`pyparser.capture.common.PhyInfo`
class. |
def emit(self, event):
"""Notifies all listeners to this channel that an event has occurred.
Parameters
----------
event : Event
The event to be emitted.
"""
if hasattr(event, 'time'):
event.step_size = self.manager.step_size()
event.t... | Notifies all listeners to this channel that an event has occurred.
Parameters
----------
event : Event
The event to be emitted. |
def change_range(self, min_port=1025, max_port=2000, port_sequence=None):
"""change Pool port range"""
self.__init_range(min_port, max_port, port_sequence) | change Pool port range |
def make_app(global_conf, **app_conf):
"""Create a WSGI application and return it
``global_conf``
The inherited configuration for this application. Normally from
the [DEFAULT] section of the Paste ini file.
``app_conf``
The application's local configuration. Normally specified in
... | Create a WSGI application and return it
``global_conf``
The inherited configuration for this application. Normally from
the [DEFAULT] section of the Paste ini file.
``app_conf``
The application's local configuration. Normally specified in
the [app:<name>] section of the Paste i... |
def parse_delimited_table(table_lines,
delim=None,
max_splits=-1,
strip=True,
header_delim='same as delimiter',
heading_ignore=None,
header_substitute=None,
... | Parses table-like text. Uses the first (non-ignored) row as the list of
column names, which cannot contain the delimiter. Fields cannot contain
the delimiter but can be blank if a printable delimiter is used.
Arguments:
table_lines (list): List of strings with the first line containing
... |
def set_params(self, arg_params, aux_params, allow_missing=False, force_init=True,
allow_extra=False):
"""Assigns parameter and aux state values.
Parameters
----------
arg_params : dict
Dictionary of name to `NDArray`.
aux_params : dict
... | Assigns parameter and aux state values.
Parameters
----------
arg_params : dict
Dictionary of name to `NDArray`.
aux_params : dict
Dictionary of name to `NDArray`.
allow_missing : bool
If ``True``, params could contain missing values, and the ... |
def add_line(self, line, source, *lineno):
"""Append one line of generated reST to the output."""
if 'conference_scheduler.scheduler' in source:
module = 'scheduler'
else:
module = 'resources'
rst[module].append(line)
self.directive.result.append(self.indent + line, source, *lineno) | Append one line of generated reST to the output. |
def taxTree(taxdict):
"""Return taxonomic Newick tree"""
# the taxonomic dictionary holds the lineage of each ident in
# the same order as the taxonomy
# use hierarchy to construct a taxonomic tree
for rank in taxdict.taxonomy:
current_level = float(taxdict.taxonomy.index(rank))
# g... | Return taxonomic Newick tree |
def funk(p, x, y):
"""
Function misfit evaluation for best-fit tanh curve
f(x[:]) = alpha*tanh(beta*x[:])
alpha = params[0]
beta = params[1]
funk(params) = sqrt(sum((y[:] - f(x[:]))**2)/len(y[:]))
Output is RMS misfit
x=xx[0][:]
y=xx[1][:]q
"""
alpha=p[0]
beta... | Function misfit evaluation for best-fit tanh curve
f(x[:]) = alpha*tanh(beta*x[:])
alpha = params[0]
beta = params[1]
funk(params) = sqrt(sum((y[:] - f(x[:]))**2)/len(y[:]))
Output is RMS misfit
x=xx[0][:]
y=xx[1][:]q |
def configure(self, config):
"""
Configure Monitor, pull list of what to monitor, initialize threads
"""
self.config = config
self.update_monitors()
# initialize thread pools
for profile in ('worker', 'result'):
for _ in range(config['threads'][profil... | Configure Monitor, pull list of what to monitor, initialize threads |
async def ping(self, data: Optional[bytes] = None) -> Awaitable[None]:
"""
This coroutine sends a ping.
It returns a :class:`~asyncio.Future` which will be completed when the
corresponding pong is received and which you may ignore if you don't
want to wait.
A ping may s... | This coroutine sends a ping.
It returns a :class:`~asyncio.Future` which will be completed when the
corresponding pong is received and which you may ignore if you don't
want to wait.
A ping may serve as a keepalive or as a check that the remote endpoint
received all messages up... |
def output_after_run_set(self, runSet, cputime=None, walltime=None, energy={}):
"""
The method output_after_run_set() stores the times of a run set in XML.
@params cputime, walltime: accumulated times of the run set
"""
self.add_values_to_run_set_xml(runSet, cputime, walltime, e... | The method output_after_run_set() stores the times of a run set in XML.
@params cputime, walltime: accumulated times of the run set |
def _update_armed_ready_status(self, message=None):
"""
Uses the provided message to update the armed state
and ready state at once as they can change in the same
message and we want both events to have the same states.
:param message: message to use to update
:type messa... | Uses the provided message to update the armed state
and ready state at once as they can change in the same
message and we want both events to have the same states.
:param message: message to use to update
:type message: :py:class:`~alarmdecoder.messages.Message` |
def write(label, plist, scope=USER):
'''
Writes the given property list to the appropriate file on disk and returns
the absolute filename.
:param plist: dict
:param label: string
:param scope: oneOf(USER, USER_ADMIN, DAEMON_ADMIN, USER_OS, DAEMON_OS)
'''
fname = compute_filename(label, ... | Writes the given property list to the appropriate file on disk and returns
the absolute filename.
:param plist: dict
:param label: string
:param scope: oneOf(USER, USER_ADMIN, DAEMON_ADMIN, USER_OS, DAEMON_OS) |
def start(self):
'''
Start the worker process.
'''
# metrics
napalm_logs_device_messages_received = Counter(
'napalm_logs_device_messages_received',
"Count of messages received by the device process",
['device_os']
)
napalm_logs... | Start the worker process. |
def _recoverable(self, method, *args, **kwargs):
"""Wraps a method to recover the stream and retry on error.
If a retryable error occurs while making the call, then the stream will
be re-opened and the method will be retried. This happens indefinitely
so long as the error is a retryable... | Wraps a method to recover the stream and retry on error.
If a retryable error occurs while making the call, then the stream will
be re-opened and the method will be retried. This happens indefinitely
so long as the error is a retryable one. If an error occurs while
re-opening the stream... |
def send_rpc_async(self, conn_id, address, rpc_id, payload, timeout, callback):
"""Asynchronously send an RPC to this IOTile device
Args:
conn_id (int): A unique identifier that will refer to this connection
address (int): the address of the tile that we wish to send the RPC to
... | Asynchronously send an RPC to this IOTile device
Args:
conn_id (int): A unique identifier that will refer to this connection
address (int): the address of the tile that we wish to send the RPC to
rpc_id (int): the 16-bit id of the RPC we want to call
payload (byt... |
def send(self, request: Request) -> None:
"""
Dispatches a request. Expects one and one only target handler
:param request: The request to dispatch
:return: None, will throw a ConfigurationException if more than one handler factor is registered for the command
"""
handle... | Dispatches a request. Expects one and one only target handler
:param request: The request to dispatch
:return: None, will throw a ConfigurationException if more than one handler factor is registered for the command |
def get_stats(self, obj, stat_name):
""" Send CLI command that returns list of integer counters.
:param obj: requested object.
:param stat_name: statistics command name.
:return: list of counters.
:rtype: list(int)
"""
return [int(v) for v in self.send_command_re... | Send CLI command that returns list of integer counters.
:param obj: requested object.
:param stat_name: statistics command name.
:return: list of counters.
:rtype: list(int) |
def download(self, localdir, max_retry):
""" Download a track in local directory. """
local_file = self.gen_localdir(localdir) + self.gen_filename()
if self.track_exists(localdir):
print("Track {0} already downloaded, skipping!".format(
self.get("id")))
r... | Download a track in local directory. |
def GetStatus(self,directory,files=None,service=None):
""" Scans through all files in direcotory,
opens DB (if any), and returns dictionary (where filename is key)
of files and their status
- Returns dictionary where filename is key
- Status can be:
- ? : Not tracked... | Scans through all files in direcotory,
opens DB (if any), and returns dictionary (where filename is key)
of files and their status
- Returns dictionary where filename is key
- Status can be:
- ? : Not tracked
- S : Synched, in DB and on FLICKR
- A : A... |
def _buffer_list_equal(a, b):
"""Compare two lists of buffers for equality.
Used to decide whether two sequences of buffers (memoryviews,
bytearrays, or python 3 bytes) differ, such that a sync is needed.
Returns True if equal, False if unequal
"""
if len(a) != len(b):
return False
... | Compare two lists of buffers for equality.
Used to decide whether two sequences of buffers (memoryviews,
bytearrays, or python 3 bytes) differ, such that a sync is needed.
Returns True if equal, False if unequal |
def matrix_undirected_weighted(user, interaction=None):
"""
Returns an undirected, weighted matrix for call, text and call duration
where an edge exists if the relationship is reciprocated.
"""
matrix = _interaction_matrix(user, interaction=interaction)
result = [[0 for _ in range(len(matrix))] ... | Returns an undirected, weighted matrix for call, text and call duration
where an edge exists if the relationship is reciprocated. |
def orthonorm_check(a, tol=_DEF.ORTHONORM_TOL, report=False):
"""Checks orthonormality of the column vectors of a matrix.
If a one-dimensional |nparray| is passed to `a`, it is treated as a single
column vector, rather than a row matrix of length-one column vectors.
The matrix `a` does not need to be ... | Checks orthonormality of the column vectors of a matrix.
If a one-dimensional |nparray| is passed to `a`, it is treated as a single
column vector, rather than a row matrix of length-one column vectors.
The matrix `a` does not need to be square, though it must have at least
as many rows as columns, sin... |
def distances_from_parent(self, leaves=True, internal=True, unlabeled=False):
'''Generator over the node-to-parent distances of this ``Tree``; (node,distance) tuples
Args:
``terminal`` (``bool``): ``True`` to include leaves, otherwise ``False``
``internal`` (``bool``): ``True``... | Generator over the node-to-parent distances of this ``Tree``; (node,distance) tuples
Args:
``terminal`` (``bool``): ``True`` to include leaves, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``
``unlabeled`` (``bool``): ``... |
def _GetSignatureScanner(cls, specification_store):
"""Initializes a signature scanner based on a specification store.
Args:
specification_store (FormatSpecificationStore): specification store.
Returns:
pysigscan.scanner: signature scanner.
"""
signature_scanner = pysigscan.scanner()
... | Initializes a signature scanner based on a specification store.
Args:
specification_store (FormatSpecificationStore): specification store.
Returns:
pysigscan.scanner: signature scanner. |
def subscribeAsync(self, topic, QoS, ackCallback=None, messageCallback=None):
"""
**Description**
Subscribe to the desired topic and register a message callback with SUBACK callback.
**Syntax**
.. code:: python
# Subscribe to "myTopic" with QoS0, custom SUBACK callb... | **Description**
Subscribe to the desired topic and register a message callback with SUBACK callback.
**Syntax**
.. code:: python
# Subscribe to "myTopic" with QoS0, custom SUBACK callback and a message callback
myAWSIoTMQTTClient.subscribe("myTopic", 0, ackCallback=mySuba... |
def cleanup(self):
'''Terminate this client if it has not already terminated.'''
if self.state == ClientState.WAITING_FOR_RESULT:
# There is an ongoing call to execute()
# Not sure what to do here
logger.warn('cleanup() called while state is WAITING_FOR_RESULT: ignori... | Terminate this client if it has not already terminated. |
def predict_compound_pairs(reaction, compound_formula, solver, epsilon=1e-5,
alt_elements=None, weight_func=default_weight):
"""Predict compound pairs of reaction using MapMaker.
Yields all solutions as dictionaries with compound pairs as keys and
formula objects as values.
... | Predict compound pairs of reaction using MapMaker.
Yields all solutions as dictionaries with compound pairs as keys and
formula objects as values.
Args:
reaction: :class:`psamm.reaction.Reaction` object.
compound_formula: Dictionary mapping compound IDs to formulas. Formulas
mu... |
def _create_placeholders(self, n_features, n_classes):
"""Create the TensorFlow placeholders for the model.
:param n_features: number of features of the first layer
:param n_classes: number of classes
:return: self
"""
self.input_data = tf.placeholder(
tf.flo... | Create the TensorFlow placeholders for the model.
:param n_features: number of features of the first layer
:param n_classes: number of classes
:return: self |
def get_lyrics_letssingit(song_name):
'''
Scrapes the lyrics of a song since spotify does not provide lyrics
takes song title as arguement
'''
lyrics = ""
url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \
quote(song_name.encode('utf-8'))
html =... | Scrapes the lyrics of a song since spotify does not provide lyrics
takes song title as arguement |
def is_ancestor_of_book(self, id_, book_id):
"""Tests if an ``Id`` is an ancestor of a book.
arg: id (osid.id.Id): an ``Id``
arg: book_id (osid.id.Id): the ``Id`` of a book
return: (boolean) - ``tru`` e if this ``id`` is an ancestor of
``book_id,`` ``false`` other... | Tests if an ``Id`` is an ancestor of a book.
arg: id (osid.id.Id): an ``Id``
arg: book_id (osid.id.Id): the ``Id`` of a book
return: (boolean) - ``tru`` e if this ``id`` is an ancestor of
``book_id,`` ``false`` otherwise
raise: NotFound - ``book_id`` is not found... |
def ConsultarTiposComprobante(self, sep="||"):
"Retorna un listado de tipos de comprobantes con código y descripción"
ret = self.client.consultarTiposComprobante(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.C... | Retorna un listado de tipos de comprobantes con código y descripción |
def run_strelka_full(job, tumor_bam, normal_bam, univ_options, strelka_options):
"""
Run strelka on the DNA bams.
:param dict tumor_bam: Dict of bam and bai for tumor DNA-Seq
:param dict normal_bam: Dict of bam and bai for normal DNA-Seq
:param dict univ_options: Dict of universal options used by a... | Run strelka on the DNA bams.
:param dict tumor_bam: Dict of bam and bai for tumor DNA-Seq
:param dict normal_bam: Dict of bam and bai for normal DNA-Seq
:param dict univ_options: Dict of universal options used by almost all tools
:param dict strelka_options: Options specific to strelka
:return: Dic... |
def _full_to_yearly_ts(self, arr, dt):
"""Average the full timeseries within each year."""
time_defined = self.def_time and not ('av' in self.dtype_in_time)
if time_defined:
arr = utils.times.yearly_average(arr, dt)
return arr | Average the full timeseries within each year. |
def reduce(self, func, dim=None, axis=None,
keep_attrs=None, shortcut=True, **kwargs):
"""Reduce the items in this group by applying `func` along some
dimension(s).
Parameters
----------
func : function
Function which can be called in the form
... | Reduce the items in this group by applying `func` along some
dimension(s).
Parameters
----------
func : function
Function which can be called in the form
`func(x, axis=axis, **kwargs)` to return the result of collapsing
an np.ndarray over an integer v... |
def parse_ssois_return(ssois_return, object_name, imagetype, camera_filter='r.MP9601',
telescope_instrument='CFHT/MegaCam'):
"""
Parse through objects in ssois query and filter out images of desired filter, type, exposure time, and instrument
"""
assert camera_filter in ['r.MP960... | Parse through objects in ssois query and filter out images of desired filter, type, exposure time, and instrument |
def sign(wheelfile, replace=False, get_keyring=get_keyring):
"""Sign a wheel"""
warn_signatures()
WheelKeys, keyring = get_keyring()
ed25519ll = signatures.get_ed25519ll()
wf = WheelFile(wheelfile, append=True)
wk = WheelKeys().load()
name = wf.parsed_filename.group('name')
sign_with ... | Sign a wheel |
def to_pydatetime(self):
"""
Converts datetimeoffset object into Python's datetime.datetime object
@return: time zone aware datetime.datetime
"""
dt = datetime.datetime.combine(self._date.to_pydate(), self._time.to_pytime())
from .tz import FixedOffsetTimezone
ret... | Converts datetimeoffset object into Python's datetime.datetime object
@return: time zone aware datetime.datetime |
def _parse_raw_bytes(raw_bytes):
"""Convert a string of hexadecimal values to decimal values parameters
Example: '0x2E 0xF1 0x80 0x28 0x00 0x1A 0x01 0x00' is converted to:
46, 241, [128, 40, 0, 26, 1, 0]
:param raw_bytes: string of hexadecimal values
:returns: 3 decimal values
"""
... | Convert a string of hexadecimal values to decimal values parameters
Example: '0x2E 0xF1 0x80 0x28 0x00 0x1A 0x01 0x00' is converted to:
46, 241, [128, 40, 0, 26, 1, 0]
:param raw_bytes: string of hexadecimal values
:returns: 3 decimal values |
def get_new_profile(self):
"""
A profile object will be returned with the configuration based on this template. Specify the profile name and
server hardware to assign. If template has any fiber channel connection (which is specified as bootable) but no
boot target was defined, that conne... | A profile object will be returned with the configuration based on this template. Specify the profile name and
server hardware to assign. If template has any fiber channel connection (which is specified as bootable) but no
boot target was defined, that connection will be instantiated as a non-bootable co... |
def get_instance_id(self, instance):
" Returns instance pk even if multiple instances were passed to RichTextField. "
if type(instance) in [list, tuple]:
core_signals.request_finished.connect(receiver=RichTextField.reset_instance_counter_listener)
if RichTextField.__inst_counter ... | Returns instance pk even if multiple instances were passed to RichTextField. |
def get_whitespace(txt):
"""
Returns a list containing the whitespace to the left and
right of a string as its two elements
"""
# if the entire parameter is whitespace
rall = re.search(r'^([\s])+$', txt)
if rall:
tmp = txt.split('\n', 1)
if len(tmp) == 2:
return ... | Returns a list containing the whitespace to the left and
right of a string as its two elements |
def datetimeXPos(self, dtime):
"""
Returns the x-position for the inputed date time.
:return <float>
"""
gantt = self.ganttWidget()
scale = gantt.timescale()
# calculate the distance for a minute
if scale == gantt.Timescale.... | Returns the x-position for the inputed date time.
:return <float> |
def get_scratch_path(self, local_file):
"""Construct and return a path in the scratch area from a local file.
"""
(local_dirname, local_basename) = self.split_local_path(local_file)
return self.construct_scratch_path(local_dirname, local_basename) | Construct and return a path in the scratch area from a local file. |
def RgbToRyb(hue):
'''Maps a hue on the RGB color wheel to Itten's RYB wheel.
Parameters:
:hue:
The hue on the RGB color wheel [0...360]
Returns:
An approximation of the corresponding hue on Itten's RYB wheel.
>>> Color.RgbToRyb(15)
26.0
'''
d = hue % 15
i = int(h... | Maps a hue on the RGB color wheel to Itten's RYB wheel.
Parameters:
:hue:
The hue on the RGB color wheel [0...360]
Returns:
An approximation of the corresponding hue on Itten's RYB wheel.
>>> Color.RgbToRyb(15)
26.0 |
def out_of_bag_samples(self):
"""
Returns the out-of-bag samples list, inside a wrapper to keep track
of modifications.
"""
#TODO:replace with more a generic pass-through wrapper?
class O(object):
def __init__(self, tree):
self.tree = tree
... | Returns the out-of-bag samples list, inside a wrapper to keep track
of modifications. |
def generate_token(self, *args, **kwargs):
""" generates a pseudo random code using os.urandom and binascii.hexlify """
# determine the length based on min_length and max_length
length = random.randint(self.min_length, self.max_length)
# generate the token using os.urandom and hexlify
... | generates a pseudo random code using os.urandom and binascii.hexlify |
def Q(name):
"""
Quote a variable name
A way to 'quote' variable names, especially ones that do not otherwise
meet Python's variable name rules.
Parameters
----------
name : str
Name of variable
Returns
-------
value : object
Value of variable
Examples
... | Quote a variable name
A way to 'quote' variable names, especially ones that do not otherwise
meet Python's variable name rules.
Parameters
----------
name : str
Name of variable
Returns
-------
value : object
Value of variable
Examples
--------
>>> import ... |
def do_attr_any(self, element, decl, pseudo):
"""Implement generic attribute setting."""
step = self.state[self.state['current_step']]
actions = step['actions']
strval = self.eval_string_value(element, decl.value)
actions.append(('attrib', (decl.name[5:], strval))) | Implement generic attribute setting. |
def from_structure(structure):
"""Return contact data from a 3D structure (in pdb format).
"""
try:
from Bio import PDB
if isinstance(structure, str):
p = PDB.PDBParser()
structure = p.get_structure('S', structure)
if isinstance(structure, PDB.Structure.Struc... | Return contact data from a 3D structure (in pdb format). |
def _data_graph_add_edge(self, src, dst, **edge_labels):
"""
Add an edge in the data dependence graph.
:param ProgramVariable src: Source node.
:param ProgramVariable dst: Destination node.
:param edge_labels: All labels associated with the edge.
:return: None
""... | Add an edge in the data dependence graph.
:param ProgramVariable src: Source node.
:param ProgramVariable dst: Destination node.
:param edge_labels: All labels associated with the edge.
:return: None |
def square(m, eff_max,c,m0,sigma,m1=21):
"""
eff_max: Maximum of the efficiency function (peak efficiency)
c: shape of the drop-off in the efficiency at bright end
m0: transition to tappering at faint magnitudes
sigma: width of the transition in efficeincy
m1: magnitude at which peak efficeincy... | eff_max: Maximum of the efficiency function (peak efficiency)
c: shape of the drop-off in the efficiency at bright end
m0: transition to tappering at faint magnitudes
sigma: width of the transition in efficeincy
m1: magnitude at which peak efficeincy occurs
square(m) = (eff_max-c*(m-21)**2)/(1+exp... |
def firwin_kaiser_lpf(f_pass, f_stop, d_stop, fs = 1.0, N_bump=0):
"""
Design an FIR lowpass filter using the sinc() kernel and
a Kaiser window. The filter order is determined based on
f_pass Hz, f_stop Hz, and the desired stopband attenuation
d_stop in dB, all relative to a sampling rate of f... | Design an FIR lowpass filter using the sinc() kernel and
a Kaiser window. The filter order is determined based on
f_pass Hz, f_stop Hz, and the desired stopband attenuation
d_stop in dB, all relative to a sampling rate of fs Hz.
Note: the passband ripple cannot be set independent of the
stopba... |
def paintEvent(self, event):
"""
Overloads the paint event to support rendering of hints if there are
no items in the tree.
:param event | <QPaintEvent>
"""
super(XListWidget, self).paintEvent(event)
if not self.visibleCount() and s... | Overloads the paint event to support rendering of hints if there are
no items in the tree.
:param event | <QPaintEvent> |
def _get(self, id):
"Return keys and value for karma id"
VALUE_SQL = "SELECT karmavalue from karma_values where karmaid = ?"
KEYS_SQL = "SELECT karmakey from karma_keys where karmaid = ?"
value = self.db.execute(VALUE_SQL, [id]).fetchall()[0][0]
keys_cur = self.db.execute(KEYS_SQL, [id]).fetchall()
keys = s... | Return keys and value for karma id |
def configure_args(self, arguments):
"""
Create configuration has from command line arguments
:type arguments: :py:class:`argparse.Namespace`
:params arguments: arguments produced by :py:meth:`Cli.parse_args()`
"""
module, key, config_path = self.check_file_paths(argume... | Create configuration has from command line arguments
:type arguments: :py:class:`argparse.Namespace`
:params arguments: arguments produced by :py:meth:`Cli.parse_args()` |
def sam_to_fastq(sam):
'''Given a pysam alignment, returns the sequence a Fastq object.
Reverse complements as required and add suffix /1 or /2 as appropriate from the flag'''
name = sam.qname
if sam.is_read1:
name += '/1'
elif sam.is_read2:
name += '/2'
else:
raise Er... | Given a pysam alignment, returns the sequence a Fastq object.
Reverse complements as required and add suffix /1 or /2 as appropriate from the flag |
def find_omega_min(omega_levelu, Neu, Nl, xiu):
r"""Find the smallest transition frequency for each field.
>>> Ne = 6
>>> Nl = 2
>>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0]
>>> xi = np.zeros((Nl, Ne, Ne))
>>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]]
>>> for l in ra... | r"""Find the smallest transition frequency for each field.
>>> Ne = 6
>>> Nl = 2
>>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0]
>>> xi = np.zeros((Nl, Ne, Ne))
>>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]]
>>> for l in range(Nl):
... for pair in coup[l]:
... ... |
def draw(self, data):
"""Display decoded characters at the current cursor position and
advances the cursor if :data:`~pyte.modes.DECAWM` is set.
:param str data: text to display.
.. versionchanged:: 0.5.0
Character width is taken into account. Specifically, zero-width
... | Display decoded characters at the current cursor position and
advances the cursor if :data:`~pyte.modes.DECAWM` is set.
:param str data: text to display.
.. versionchanged:: 0.5.0
Character width is taken into account. Specifically, zero-width
and unprintable characters ... |
def save(self, target=None):
"""
Save this package to target, which should be a filename or open
file stream. If target is not supplied, and this package has a
filename attribute (such as when this package was created from
an existing file), it will be used.
"""
target = target or getattr(self, 'filename'... | Save this package to target, which should be a filename or open
file stream. If target is not supplied, and this package has a
filename attribute (such as when this package was created from
an existing file), it will be used. |
def set_frequency(self, pin, frequency_hz):
"""Set frequency (in Hz) of PWM output on specified pin."""
if pin not in self.pwm:
raise ValueError('Pin {0} is not configured as a PWM. Make sure to first call start for the pin.'.format(pin))
self.pwm[pin].ChangeFrequency(frequency_hz) | Set frequency (in Hz) of PWM output on specified pin. |
def finish_user(self, subid):
'''finish user will remove a user's token, making the user entry not
accesible if running in headless model'''
p = self.revoke_token(subid)
p.token = "finished"
self.session.commit()
return p | finish user will remove a user's token, making the user entry not
accesible if running in headless model |
def _short_color_list(self):
"""Color list is too long. Discard variations with numbers."""
return [c for c in colors.get_colors() if not re.search(r'\d', c)] | Color list is too long. Discard variations with numbers. |
def show_vcs_output_vcs_nodes_vcs_node_info_node_is_principal(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_vcs = ET.Element("show_vcs")
config = show_vcs
output = ET.SubElement(show_vcs, "output")
vcs_nodes = ET.SubElement(output,... | Auto Generated Code |
def com_adobe_fonts_check_name_empty_records(ttFont):
"""Check name table for empty records."""
failed = False
for name_record in ttFont['name'].names:
name_string = name_record.toUnicode().strip()
if len(name_string) == 0:
failed = True
name_key = tuple([name_record.... | Check name table for empty records. |
def delete_scoped_package_version_from_recycle_bin(self, feed_id, package_scope, unscoped_package_name, package_version):
"""DeleteScopedPackageVersionFromRecycleBin.
[Preview API] Delete a package version with an npm scope from the recycle bin.
:param str feed_id: Name or ID of the feed.
... | DeleteScopedPackageVersionFromRecycleBin.
[Preview API] Delete a package version with an npm scope from the recycle bin.
:param str feed_id: Name or ID of the feed.
:param str package_scope: Scope of the package (the 'scope' part of @scope/name).
:param str unscoped_package_name: Name of... |
def find_local_uuid(tw, keys, issue, legacy_matching=False):
""" For a given issue issue, find its local UUID.
Assembles a list of task IDs existing in taskwarrior
matching the supplied issue (`issue`) on the combination of any
set of supplied unique identifiers (`keys`) or, optionally,
the task's ... | For a given issue issue, find its local UUID.
Assembles a list of task IDs existing in taskwarrior
matching the supplied issue (`issue`) on the combination of any
set of supplied unique identifiers (`keys`) or, optionally,
the task's description field (should `legacy_matching` be `True`).
:params:... |
def _run_wes(args):
"""Run CWL using a Workflow Execution Service (WES) endpoint
"""
main_file, json_file, project_name = _get_main_and_json(args.directory)
main_file = _pack_cwl(main_file)
if args.host and "stratus" in args.host:
_run_wes_stratus(args, main_file, json_file)
else:
... | Run CWL using a Workflow Execution Service (WES) endpoint |
def _check_dir_meta(name,
user,
group,
mode,
follow_symlinks=False):
'''
Check the changes in directory metadata
'''
try:
stats = __salt__['file.stats'](name, None, follow_symlinks)
except CommandExecutionError:
... | Check the changes in directory metadata |
def render_template(template_name, info, out_path=None):
"""Render a template using the variables in info.
You can optionally render to a file by passing out_path.
Args:
template_name (str): The name of the template to load. This must
be a file in config/templates inside this package
... | Render a template using the variables in info.
You can optionally render to a file by passing out_path.
Args:
template_name (str): The name of the template to load. This must
be a file in config/templates inside this package
out_path (str): An optional path of where to save the ou... |
def get(self, attach, *args, **kwargs):
"""
:param attach: if True, return file as an attachment.
"""
response = self.make_response(*args, **kwargs) # type: Response
response.content_type = self.get_content_type(*args, **kwargs)
if attach:
filename = self.ge... | :param attach: if True, return file as an attachment. |
def read_info_file(data_dir, info_file):
"""Return a Tensor containing the list of labels
Read the file and keep only the ID of the 3D point.
"""
labels = []
with open(os.path.join(data_dir, info_file), 'r') as f:
labels = [int(line.split()[0]) for line in f]
return torch.LongTensor(l... | Return a Tensor containing the list of labels
Read the file and keep only the ID of the 3D point. |
def load_character_images(self, verbose=True):
"""
Generator to load all images in the dataset. Yields (image, character) pairs until all images have been loaded.
:return: (Pillow.Image.Image, string) tuples
"""
for dataset in self.character_sets:
assert self.get_data... | Generator to load all images in the dataset. Yields (image, character) pairs until all images have been loaded.
:return: (Pillow.Image.Image, string) tuples |
def description(self, force_refresh=False):
"""Call ``DescribeHyperParameterTuningJob`` for the hyperparameter tuning job.
Args:
force_refresh (bool): Set to True to fetch the latest data from SageMaker API.
Returns:
dict: The Amazon SageMaker response for ``DescribeHyp... | Call ``DescribeHyperParameterTuningJob`` for the hyperparameter tuning job.
Args:
force_refresh (bool): Set to True to fetch the latest data from SageMaker API.
Returns:
dict: The Amazon SageMaker response for ``DescribeHyperParameterTuningJob``. |
def _bcrypt_load_key(key_object, key_info, container, curve_name):
"""
Loads a certificate, public key or private key into a Certificate,
PublicKey or PrivateKey object via CNG
:param key_object:
An asn1crypto.x509.Certificate, asn1crypto.keys.PublicKeyInfo or
asn1crypto.keys.PrivateKey... | Loads a certificate, public key or private key into a Certificate,
PublicKey or PrivateKey object via CNG
:param key_object:
An asn1crypto.x509.Certificate, asn1crypto.keys.PublicKeyInfo or
asn1crypto.keys.PrivateKeyInfo object
:param key_info:
An asn1crypto.keys.PublicKeyInfo or a... |
def prepare_data(data: Data) -> Tuple[int, bytes]:
"""
Convert a string or byte-like object to an opcode and a bytes-like object.
This function is designed for data frames.
If ``data`` is a :class:`str`, return ``OP_TEXT`` and a :class:`bytes`
object encoding ``data`` in UTF-8.
If ``data`` is... | Convert a string or byte-like object to an opcode and a bytes-like object.
This function is designed for data frames.
If ``data`` is a :class:`str`, return ``OP_TEXT`` and a :class:`bytes`
object encoding ``data`` in UTF-8.
If ``data`` is a bytes-like object, return ``OP_BINARY`` and a bytes-like
... |
def send_ignore(self, bytes=None):
"""
Send a junk packet across the encrypted link. This is sometimes used
to add "noise" to a connection to confuse would-be attackers. It can
also be used as a keep-alive for long lived connections traversing
firewalls.
@param bytes: ... | Send a junk packet across the encrypted link. This is sometimes used
to add "noise" to a connection to confuse would-be attackers. It can
also be used as a keep-alive for long lived connections traversing
firewalls.
@param bytes: the number of random bytes to send in the payload of th... |
def send_attachment(self, recipient_id, attachment_type, attachment_path,
notification_type=NotificationType.regular):
"""Send an attachment to the specified recipient using local path.
Input:
recipient_id: recipient id to send to
attachment_type: type of ... | Send an attachment to the specified recipient using local path.
Input:
recipient_id: recipient id to send to
attachment_type: type of attachment (image, video, audio, file)
attachment_path: Path of attachment
Output:
Response from API as <dict> |
def instance_contains(container, item):
"""Search into instance attributes, properties and return values of no-args methods."""
return item in (member for _, member in inspect.getmembers(container)) | Search into instance attributes, properties and return values of no-args methods. |
def _list_and_update(self):
"""
Update current list of resources by doing a full fetch.
Overwrites all current resource info.
"""
initial_resources = getattr(self.api, self.list_method_name)(
self.namespace,
label_selector=self.label_selector,
... | Update current list of resources by doing a full fetch.
Overwrites all current resource info. |
def delete_resource_scenario(scenario_id, resource_attr_id, quiet=False, **kwargs):
"""
Remove the data associated with a resource in a scenario.
"""
_check_can_edit_scenario(scenario_id, kwargs['user_id'])
_delete_resourcescenario(scenario_id, resource_attr_id, suppress_error=quiet) | Remove the data associated with a resource in a scenario. |
def create_constraints(self, courses):
"""Internal use. Creates all constraints in the problem instance for the given
courses.
"""
for i, course1 in enumerate(courses):
for j, course2 in enumerate(courses):
if i <= j:
continue
... | Internal use. Creates all constraints in the problem instance for the given
courses. |
def ekf_ext_encode(self, timestamp, Windspeed, WindDir, WindZ, Airspeed, beta, alpha):
'''
Extended EKF state estimates for ASLUAVs
timestamp : Time since system start [us] (uint64_t)
Windspeed : Magnitude of wind velocity ... | Extended EKF state estimates for ASLUAVs
timestamp : Time since system start [us] (uint64_t)
Windspeed : Magnitude of wind velocity (in lateral inertial plane) [m/s] (float)
WindDir : Wind heading angle from North [rad] (... |
def gamma(phi1,phi2,theta1,theta2):
"""
calculate third rotation angle
inputs are angles from 2 pulsars
returns the angle.
"""
if phi1 == phi2 and theta1 == theta2:
gamma = 0
else:
gamma = atan( sin(theta2)*sin(phi2-phi1) / \
(cos(theta1)*sin(t... | calculate third rotation angle
inputs are angles from 2 pulsars
returns the angle. |
def list_queues(self):
"""
Run the ``list_queues`` command (for the default vhost) and return a
list of tuples describing the queues.
:return:
A list of 2-element tuples. The first element is the queue name,
the second is the current queue size.
"""
... | Run the ``list_queues`` command (for the default vhost) and return a
list of tuples describing the queues.
:return:
A list of 2-element tuples. The first element is the queue name,
the second is the current queue size. |
def _read_group_field(self, group, levels, field_type, field_size,
decrypted_content):
"""This method handles the different fields of a group"""
if field_type == 0x0000:
# Ignored (commentar block)
pass
elif field_type == 0x0001:
g... | This method handles the different fields of a group |
def map_2d_array_to_masked_1d_array_from_array_2d_and_mask(mask, array_2d):
"""For a 2D array and mask, map the values of all unmasked pixels to a 1D array.
The pixel coordinate origin is at the top left corner of the 2D array and goes right-wards and downwards, such
that for an array of shape (3,3) where ... | For a 2D array and mask, map the values of all unmasked pixels to a 1D array.
The pixel coordinate origin is at the top left corner of the 2D array and goes right-wards and downwards, such
that for an array of shape (3,3) where all pixels are unmasked:
- pixel [0,0] of the 2D array will correspond to inde... |
def X(self):
""" Creates design matrix of variables to use in GP regression
Returns
----------
The design matrix
"""
if self.ar == 1:
return np.array([self.data_full[(self.max_lag-1):-1]])
else:
for i in range(0,self.ar):
... | Creates design matrix of variables to use in GP regression
Returns
----------
The design matrix |
def len_header(filename):
""" Return the length of the blimpy header, in bytes
Args:
filename (str): name of file to open
Returns:
idx_end (int): length of header, in bytes
"""
with open(filename, 'rb') as f:
header_sub_count = 0
eoh_found = False
while not... | Return the length of the blimpy header, in bytes
Args:
filename (str): name of file to open
Returns:
idx_end (int): length of header, in bytes |
def _update_interface(self, other_interface):
"""
Update the physical interface base settings with another interface.
Only set updated if a value has changed. You must also call `update`
on the interface if modifications are made. This is called from other
interfaces (i.e. Physic... | Update the physical interface base settings with another interface.
Only set updated if a value has changed. You must also call `update`
on the interface if modifications are made. This is called from other
interfaces (i.e. PhysicalInterface, ClusterPhysicalInterface, etc) to
update the ... |
def encode_texts(self, texts, unknown_token="<UNK>", verbose=1, **kwargs):
"""Encodes the given texts using internal vocabulary with optionally applied encoding options. See
``apply_encoding_options` to set various options.
Args:
texts: The list of text items to encode.
... | Encodes the given texts using internal vocabulary with optionally applied encoding options. See
``apply_encoding_options` to set various options.
Args:
texts: The list of text items to encode.
unknown_token: The token to replace words that out of vocabulary. If none, those words... |
def get_extra_managed_storage_volume_paths(self, start=0, count=-1, filter='', sort=''):
"""
Gets the list of extra managed storage volume paths.
Args:
start:
The first item to return, using 0-based indexing.
If not specified, the default is 0 - start... | Gets the list of extra managed storage volume paths.
Args:
start:
The first item to return, using 0-based indexing.
If not specified, the default is 0 - start with the first available item.
count:
The number of resources to return. A count... |
def show_buff(self, pos):
"""
Return the display of the instruction
:rtype: string
"""
buff = self.get_name() + " "
for i in range(0, len(self.data)):
buff += "\\x%02x" % self.data[i]
return buff | Return the display of the instruction
:rtype: string |
def isfinite(self):
"Test whether the predicted values are finite"
if self._multiple_outputs:
if self.hy_test is not None:
r = [(hy.isfinite() and (hyt is None or hyt.isfinite()))
for hy, hyt in zip(self.hy, self.hy_test)]
else:
... | Test whether the predicted values are finite |
def _checksum(self, packet):
'''calculate the XOR checksum of a packet in string format'''
xorsum = 0
for s in packet:
xorsum ^= ord(s)
return xorsum | calculate the XOR checksum of a packet in string format |
def get(self, key, fallback=None):
"""secure getter for header values that allows specifying a `fallback`
return string (defaults to None). This returns the first matching value
and doesn't raise KeyErrors"""
if key in self.headers:
value = self.headers[key][0]
else:
... | secure getter for header values that allows specifying a `fallback`
return string (defaults to None). This returns the first matching value
and doesn't raise KeyErrors |
def explode_groups(self, eps, return_emap=False):
"""
Explode the mesh element groups by `eps`, i.e. split group
interface nodes and shrink each group towards its centre by
`eps`.
Parameters
----------
eps : float in `[0.0, 1.0]`
The group shrinking f... | Explode the mesh element groups by `eps`, i.e. split group
interface nodes and shrink each group towards its centre by
`eps`.
Parameters
----------
eps : float in `[0.0, 1.0]`
The group shrinking factor.
return_emap : bool, optional
If True, also ... |
def confirm(tag):
"""
Prompts user before proceeding
"""
click.echo()
if click.confirm('Do you want to create the tag {tag}?'.format(
tag=click.style(str(tag), fg='yellow')),
default=True, abort=True):
git.create_tag(tag)
if click.confirm(
'Do you want to pus... | Prompts user before proceeding |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.