text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def block_cat(self, Y0, Y1):
r"""Concatenate components corresponding to :math:`\mathbf{y}_0`
and :math:`\mathbf{y}_1` to form :math:`\mathbf{y}\;\;`.
"""
return np.concatenate((Y0, Y1), axis=self.blkaxis) | 0.008403 |
def calc_geo_branches_in_polygon(mv_grid, polygon, mode, proj):
""" Calculate geographical branches in polygon.
For a given `mv_grid` all branches (edges in the graph of the grid) are
tested if they are in the given `polygon`. You can choose different modes
and projections for this operation.
Para... | 0.001336 |
def create_status_callback(self, callback=None):
"""
Creates a callback for the rlbot status, uses default function if callback is none.
:param callback:
:return:
"""
if callback is None:
return self.callback_func
def safe_wrapper(id, rlbotstatsus):
... | 0.006993 |
def snapshot_name(topo_name):
"""
Get the snapshot name
:param str topo_name: topology file location. The name is taken from the
directory containing the topology file using the
following format: topology_NAME_snapshot_DATE_TIME
:return: snapshot name... | 0.004027 |
def _ensure_api_keys(task_desc, failure_ret=None):
"""Wrap Elsevier methods which directly use the API keys.
Ensure that the keys are retrieved from the environment or config file when
first called, and store global scope. Subsequently use globally stashed
results and check for required ids.
"""
... | 0.001653 |
def from_byte_array(cls, bytes_):
"""Decodes a run-length encoded ByteArray and returns a Bitmap.
The ByteArray decompresses to a sequence of 32-bit values, which are
stored as a byte string. (The specific encoding depends on Form.depth.)
"""
runs = cls._length_run_coding.parse(b... | 0.00431 |
def notch_fir(self, f1, f2, order, beta=5.0, remove_corrupted=True):
""" notch filter the time series using an FIR filtered generated from
the ideal response passed through a time-domain kaiser
window (beta = 5.0)
The suppression of the notch filter is related to the bandwidth and
... | 0.002566 |
def delimited(items, character='|'):
"""Returns a character delimited version of the provided list as a Python string"""
return '|'.join(items) if type(items) in (list, tuple, set) else items | 0.01005 |
def hash_pair(first: Keccak256, second: Optional[Keccak256]) -> Keccak256:
""" Computes the keccak hash of the elements ordered topologically.
Since a merkle proof will not include all the elements, but only the path
starting from the leaves up to the root, the order of the elements is not
known by the... | 0.001479 |
def config(client, event, channel, nick, rest):
"Change the running config, something like a=b or a+=b or a-=b"
pattern = re.compile(r'(?P<key>\w+)\s*(?P<op>[+-]?=)\s*(?P<value>.*)$')
match = pattern.match(rest)
if not match:
return "Command not recognized"
res = match.groupdict()
key = res['key']
op = res['op... | 0.028881 |
def grant_token(self):
"""
获取 Access Token。
:return: 返回的 JSON 数据包
"""
return self.get(
url="https://api.weixin.qq.com/cgi-bin/token",
params={
"grant_type": "client_credential",
"appid": self.appid,
"secret"... | 0.005556 |
def saveSilent(self):
"""
Saves the record, but does not emit the saved signal. This method
is useful when chaining together multiple saves. Check the
saveSignalBlocked value to know if it was muted to know if any
saves occurred.
:return <bool>
... | 0.008889 |
def deserialize_class(serilalized_cls):
""" Deserialize Python class """
module_name, cls_name = serilalized_cls.split(':')
module = importlib.import_module(module_name)
return getattr(module, cls_name) | 0.004587 |
def save(self, record_key, record_data, overwrite=True, secret_key=''):
'''
a method to create a record in the collection folder
:param record_key: string with name to assign to record (see NOTES below)
:param record_data: byte data for record body
:param overwrite:... | 0.005568 |
def shift_ordering_up(cls, parent_id, position, db_session=None, *args, **kwargs):
"""
Shifts ordering to "open a gap" for node insertion,
begins the shift from given position
:param parent_id:
:param position:
:param db_session:
:return:
"""
db_s... | 0.006006 |
def set_nested_attribute(obj, attribute, value):
"""
Sets the value of the given (possibly dotted) attribute for the given
object to the given value.
:raises AttributeError: If any of the parents on the nested attribute's
name path are `None`.
"""
parent, attr = resolve_nested_attribute(o... | 0.002 |
def search(df, match, columns=['Proteins','Protein names','Gene names']):
"""
Search for a given string in a set of columns in a processed ``DataFrame``.
Returns a filtered ``DataFrame`` where `match` is contained in one of the `columns`.
:param df: Pandas ``DataFrame``
:param match: ``str`` to se... | 0.010638 |
def write_properties(self, properties, file_datetime):
"""
Write properties to the ndata file specified by reference.
:param reference: the reference to which to write
:param properties: the dict to write to the file
:param file_datetime: the datetime for the fil... | 0.005719 |
def get_single_external_tool_accounts(self, account_id, external_tool_id):
"""
Get a single external tool.
Returns the specified external tool.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["... | 0.004872 |
def parseUri(stream, uri=None):
"""Read an XML document from a URI, and return a :mod:`lxml.etree`
document."""
return etree.parse(stream, parser=_get_xmlparser(), base_url=uri) | 0.005291 |
def manacher(s):
"""Longest palindrome in a string by Manacher
:param s: string
:requires: s is not empty
:returns: i,j such that s[i:j] is the longest palindrome in s
:complexity: O(len(s))
"""
assert set.isdisjoint({'$', '^', '#'}, s) # Forbidden letters
if s == "":
return (0... | 0.001036 |
def from_string(cls, key, key_id=None):
"""Construct a RSASigner from a private key in PEM format.
Args:
key (Union[bytes, str]): Private key in PEM format.
key_id (str): An optional key id used to identify the private key.
Returns:
google.auth.crypt._crypto... | 0.002309 |
def get_configuration(self, scaling_group):
"""
Returns the scaling group's configuration in a dictionary.
"""
uri = "/%s/%s/config" % (self.uri_base, utils.get_id(scaling_group))
resp, resp_body = self.api.method_get(uri)
return resp_body.get("groupConfiguration") | 0.00639 |
def query_foursquare(point, max_distance, client_id, client_secret):
""" Queries Squarespace API for a location
Args:
point (:obj:`Point`): Point location to query
max_distance (float): Search radius, in meters
client_id (str): Valid Foursquare client id
client_secret (str): Val... | 0.001924 |
def pruning(self, X, y, cost_mat):
""" Function that prune the decision tree.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
y_true : array indicator matrix
Ground truth (correct) labels.
cost_mat : a... | 0.00358 |
def mpim_open(self, *, users: List[str], **kwargs) -> SlackResponse:
"""This method opens a multiparty direct message.
Args:
users (list): A lists of user ids. The ordering of the users
is preserved whenever a MPIM group is returned.
e.g. ['W1234567890', 'U23... | 0.004425 |
def clipboard_get(self):
""" Get text from the clipboard.
"""
from IPython.lib.clipboard import (
osx_clipboard_get, tkinter_clipboard_get,
win32_clipboard_get
)
if sys.platform == 'win32':
chain = [win32_clipboard_get, tkinter_clipboard_get]
elif sys.platform == 'darwin'... | 0.001773 |
def update(self, friendly_name=values.unset):
"""
Update the SigningKeyInstance
:param unicode friendly_name: The friendly_name
:returns: Updated SigningKeyInstance
:rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyInstance
"""
data = values.of({'Frien... | 0.003067 |
def _inf_or_operator_handler_factory(c_start, is_delegate=True):
"""Generates handler co-routines for values that may be `+inf` or `-inf`.
Args:
c_start (int): The ordinal of the character that starts this token (either `+` or `-`).
is_delegate (bool): True if a different handler began processi... | 0.003678 |
def forward_backward(self, x):
"""Perform forward and backward computation for a batch of src seq and dst seq"""
(src_seq, tgt_seq, src_valid_length, tgt_valid_length), batch_size = x
with mx.autograd.record():
out, _ = self._model(src_seq, tgt_seq[:, :-1],
... | 0.006339 |
def check_between(v_min, v_max, **params):
"""Checks parameters are in a specified range
Parameters
----------
v_min : float, minimum allowed value (inclusive)
v_max : float, maximum allowed value (inclusive)
params : object
Named arguments, parameters to be checked
Raises
-... | 0.001686 |
def find_rrset(self, name, rdtype, covers=dns.rdatatype.NONE):
"""Look for rdata with the specified name and type in the zone,
and return an RRset encapsulating it.
The I{name}, I{rdtype}, and I{covers} parameters may be
strings, in which case they will be converted to their proper
... | 0.001185 |
def group_pop(name, app, **kwargs):
"""
Remove application from the specified routing group.
"""
ctx = Context(**kwargs)
ctx.execute_action('group:app:remove', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
'app': app,
}) | 0.003401 |
def setup_a_alpha_and_derivatives(self, i, T=None):
r'''Sets `a`, `omega`, and `Tc` for a specific component before the
pure-species EOS's `a_alpha_and_derivatives` method is called. Both are
called by `GCEOSMIX.a_alpha_and_derivatives` for every component.'''
self.a, self.Tc, self.ome... | 0.013661 |
def paginate_announcements_list(request, context, items):
"""
***TODO*** Migrate to django Paginator (see lostitems)
"""
# pagination
if "start" in request.GET:
try:
start_num = int(request.GET.get("start"))
except ValueError:
start_num = 0
else:
... | 0.001139 |
def getInstance(self):
"""
Returns the singleton instance. Upon its first call, it creates a
new instance of the decorated class and calls its `__init__` method.
On all subsequent calls, the already created instance is returned.
"""
try:
return self._instance... | 0.00463 |
def _broadcast_compat_variables(*variables):
"""Create broadcast compatible variables, with the same dimensions.
Unlike the result of broadcast_variables(), some variables may have
dimensions of size 1 instead of the the size of the broadcast dimension.
"""
dims = tuple(_unified_dims(variables))
... | 0.002375 |
def _process_patch_operation(cls, operation, obj, state):
"""
Args:
operation (dict): one patch operation in RFC 6902 format.
obj (object): an instance which is needed to be patched.
state (dict): inter-operations state storage
Returns:
processing... | 0.006349 |
def predicates(self) -> Dict[str, URIRef]:
"""
Return the tag names and corresponding URI's for all properties that can be associated with subject
:return: Map from tag name (JSON object identifier) to corresponding URI
"""
rval = dict()
for parent in self._o.objects(self... | 0.008013 |
def randomToggle(self, randomize):
"""Sets the reorder function on this StimulusModel to a randomizer
or none, alternately"""
if randomize:
self._stim.setReorderFunc(order_function('random'), 'random')
else:
self._stim.reorder = None | 0.00692 |
def generate(env):
"""Add Builders and construction variables for gcc to an Environment."""
if 'CC' not in env:
env['CC'] = env.Detect(compilers) or compilers[0]
cc.generate(env)
if env['PLATFORM'] in ['cygwin', 'win32']:
env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS')
else:
... | 0.00198 |
def get_output_list_from_task(task, placeholder_dict):
"""
Purpose: Parse a Task object to extract the files to be staged as the output.
Details: The extracted data is then converted into the appropriate RP directive depending on whether the data
is to be copied/downloaded.
:arguments:
:ta... | 0.001741 |
def next_style(self):
"""
Sibling CT_Style element identified by the value of `w:name/@w:val`
or |None| if no value is present or no style with that style id
is found.
"""
next = self.next
if next is None:
return None
styles = self.getparent()
... | 0.00554 |
def depolarizing_operators(p):
"""
Return the phase damping Kraus operators
"""
k0 = np.sqrt(1.0 - p) * I
k1 = np.sqrt(p / 3.0) * X
k2 = np.sqrt(p / 3.0) * Y
k3 = np.sqrt(p / 3.0) * Z
return k0, k1, k2, k3 | 0.004219 |
def _parse_contract_headers(self, table):
"""
Parse the years on the contract.
The years are listed as the headers on the contract. The first header
contains 'Team' which specifies the player's current team and should
not be included in the years.
Parameters
---... | 0.00289 |
def clean_existing(self, value):
"""Clean the data and return an existing document with its fields
updated based on the cleaned values.
"""
existing_pk = value[self.pk_field]
try:
obj = self.fetch_existing(existing_pk)
except ReferenceNotFoundError:
... | 0.002398 |
def _propagate_options(self, change):
"Set the values and labels, and select the first option if we aren't initializing"
options = self._options_full
self.set_trait('_options_labels', tuple(i[0] for i in options))
self._options_values = tuple(i[1] for i in options)
if self._initi... | 0.006105 |
def _handle_browse(self, relpath, params):
"""Handle requests to browse the filesystem under the build root."""
abspath = os.path.normpath(os.path.join(self._root, relpath))
if not abspath.startswith(self._root):
raise ValueError # Prevent using .. to get files from anywhere other than root.
if o... | 0.010989 |
def parse_extras(self):
# type: () -> None
"""
Parse extras from *self.line* and set them on the current object
:returns: Nothing
:rtype: None
"""
extras = None
if "@" in self.line or self.is_vcs or self.is_url:
line = "{0}".format(self.line)
... | 0.003137 |
def custom_parser(cards: list, parser: Optional[Callable[[list], Optional[list]]]=None) -> Optional[list]:
'''parser for CUSTOM [1] issue mode,
please provide your custom parser as argument'''
if not parser:
return cards
else:
return parser(cards) | 0.014235 |
def _annotate_objects(self):
"""
Extract meta-data describing the stored objects.
"""
self.metadata = []
sizer = Asizer()
sizes = sizer.asizesof(*self.objects)
self.total_size = sizer.total
for obj, sz in zip(self.objects, sizes):
md = _MetaObj... | 0.004658 |
def start(self):
"""
Starts the timer from zero
"""
self.startTime = time.time()
self.configure(text='{0:<d} s'.format(0))
self.update() | 0.01087 |
def _srm(self, data):
"""Expectation-Maximization algorithm for fitting the probabilistic SRM.
Parameters
----------
data : list of 2D arrays, element i has shape=[voxels_i, samples]
Each element in the list contains the fMRI data of one subject.
Returns
-... | 0.000636 |
def loadSignalFromWav(inputSignalFile, calibrationRealWorldValue=None, calibrationSignalFile=None, start=None,
end=None) -> Signal:
""" reads a wav file into a Signal and scales the input so that the sample are expressed in real world values
(as defined by the calibration signal).
:par... | 0.005786 |
def finalise_same_chip_constraints(substitutions, placements):
"""Given a set of placements containing the supplied
:py:class:`MergedVertex`, remove the merged vertices replacing them with
their constituent vertices (changing the placements inplace).
"""
for merged_vertex in reversed(substitutions):... | 0.002227 |
def initialize_zones(self):
"""initialize receiver zones"""
zone_list = self.location_info.get('zone_list', {'main': True})
for zone_id in zone_list:
if zone_list[zone_id]: # Location setup is valid
self.zones[zone_id] = Zone(self, zone_id=zone_id)
else:... | 0.004673 |
def gdalbuildvrt(src, dst, options=None, void=True):
"""
a simple wrapper for :osgeo:func:`gdal.BuildVRT`
Parameters
----------
src: str, list, :osgeo:class:`ogr.DataSource` or :osgeo:class:`gdal.Dataset`
the input data set(s)
dst: str
the output data set
options: dict
... | 0.005814 |
def create_attribute_model(self, initial_value=None):
# type: (Any) -> AttributeModel
"""Make an AttributeModel instance of the correct type for this Meta
Args:
initial_value: The initial value the Attribute should take
Returns:
AttributeModel: The created attri... | 0.006834 |
def readLongString(self):
"""
Read UTF8 string.
"""
l = self.stream.read_ulong()
bytes = self.stream.read(l)
return self.context.getStringForBytes(bytes) | 0.014778 |
def _kmp_search_all(self, pInput_sequence, pPattern):
"""use KMP algorithm to search all occurrence in the input_sequence of the pattern. both arguments are integer arrays. return a list of the positions of the occurences if found; otherwise, []."""
r = []
input_sequence,... | 0.007472 |
def delete_model(self, model):
"""Ran when a model is being deleted."""
for field in model._meta.local_fields:
if not isinstance(field, HStoreField):
continue
self.remove_field(model, field) | 0.008065 |
def get_create_parameter(model, param):
"""Return parameter with given name, creating it if needed.
If unique is false and the parameter exists, the value is not changed; if
it does not exist, it will be created. If unique is true then upon conflict
a number is added to the end of the parameter name.
... | 0.001029 |
def average_data(counts, observable):
"""Compute the mean value of an diagonal observable.
Takes in a diagonal observable in dictionary, list or matrix format and then
calculates the sum_i value(i) P(i) where value(i) is the value of the
observable for state i.
Args:
counts (dict): a dict ... | 0.003015 |
def _wall_post(session, owner_id, message=None, attachments=None, from_group=True):
"""
https://vk.com/dev/wall.post
attachments: "photo100172_166443618,photo-1_265827614"
"""
response = session.fetch("wall.post", owner_id=owner_id, message=message, attachments=attachments, from_... | 0.01108 |
def tokenize(readline):
"""
The tokenize() generator requires one argument, readline, which
must be a callable object which provides the same interface as the
readline() method of built-in file objects. Each call to the function
should return one line of input as bytes. Alternatively, readline
... | 0.000734 |
def split_filename(name):
"""
Splits the filename into three parts: the name part, the hash part, and the
extension. Like with the extension, the hash part starts with a dot.
"""
parts = hashed_filename_re.match(name).groupdict()
return (parts['name'] or '', parts['hash'] or '', parts['ext'] or... | 0.003086 |
def docs(ctx, output='html', rebuild=False, show=True, verbose=True):
"""Build the docs and show them in default web browser."""
sphinx_build = ctx.run(
'sphinx-build -b {output} {all} {verbose} docs docs/_build'.format(
output=output,
all='-a -E' if rebuild else '',
... | 0.001548 |
def main(argv=None):
"""to install and/or test from the command line use::
python cma.py [options | func dim sig0 [optkey optval][optkey optval]...]
with options being
``--test`` (or ``-t``) to run the doctest, ``--test -v`` to get (much) verbosity.
``install`` to install cma.py (uses setup ... | 0.003508 |
def _build_underlying_workflows(enabled_regions, json_spec, args):
"""
Creates a workflow in a temporary project for each enabled region.
Returns a tuple of dictionaries: workflow IDs by region and project IDs by region.
The caller is responsible for destroying the projects if this method returns proper... | 0.005214 |
def drawRoundRect(self, x, y, w, h, r, color=None, aa=False):
"""
Draw a rounded rectangle with top-left corner at (x, y), width w,
height h, and corner radius r
:param aa: if True, use Bresenham's algorithm for line drawing;
otherwise use Xiaolin Wu's algorithm
"""
... | 0.005236 |
def monkey_patch(cls):
"""Monkey path zbarlight C extension on Read The Docs"""
on_read_the_docs = os.environ.get('READTHEDOCS', False)
if on_read_the_docs:
sys.modules['zbarlight._zbarlight'] = cls | 0.008547 |
def directionaldiff(f, x0, vec, **options):
"""
Return directional derivative of a function of n variables
Parameters
----------
fun: callable
analytical function to differentiate.
x0: array
vector location at which to differentiate fun. If x0 is an nxm array,
then fun i... | 0.000662 |
def _truncate_wildcard_from_date(date_value):
"""Truncate wildcard from date parts.
Returns:
(str) The truncated date.
Raises:
ValueError, on either unsupported date separator (currently only ' ' and '-' are supported), or if there's a
wildcard in the year.
Notes:
Eith... | 0.004425 |
def resources(self, type_=None, title=None, **kwargs):
"""Get all resources of this node or all resources of the specified
type. Additional arguments may also be specified that will be passed
to the query function.
"""
if type_ is None:
resources = self.__api.resource... | 0.00235 |
def init_config(self, app):
"""Initialize configuration."""
for k in dir(config):
if k.startswith('OAUTHCLIENT_'):
app.config.setdefault(k, getattr(config, k))
@app.before_first_request
def override_template_configuration():
"""Override template c... | 0.00224 |
def width(self, add_quiet_zone=False):
"""Return the barcodes width in modules for a given data and character set combination.
:param add_quiet_zone: Whether quiet zone should be included in the width.
:return: Width of barcode in modules, which for images translates to pixels.
"""
... | 0.011682 |
def apply_constraints(phash, size, nonalphanumeric):
"""
Fiddle with the password a bit after hashing it so that it will
get through most website filters. We require one upper and lower
case, one digit, and we look at the user's password to determine
if there should be at least one alphanumeric or n... | 0.001355 |
def modify_column(self, table, name, new_name=None, data_type=None, null=None, default=None):
"""Modify an existing column."""
existing_def = self.get_schema_dict(table)[name]
# Set column name
new_name = new_name if new_name is not None else name
# Set data type
if not... | 0.007439 |
def find_your_legislator(request):
'''
Context:
- request
- lat
- long
- located
- legislators
Templates:
- billy/web/public/find_your_legislator_table.html
'''
# check if lat/lon are set
# if leg_search is set, they most likely don't have ECMASc... | 0.000561 |
def _read_hypocentre_from_ndk_string(self, linestring):
"""
Reads the hypocentre data from the ndk string to return an
instance of the GCMTHypocentre class
"""
hypo = GCMTHypocentre()
hypo.source = linestring[0:4]
hypo.date = _read_date_from_string(linestring[5:15... | 0.002516 |
def generateSingleNodeRST(self, node):
'''
Creates the reStructuredText document for the leaf like node object.
It is **assumed** that the specified ``node.kind`` is in
:data:`~exhale.utils.LEAF_LIKE_KINDS`. File, directory, and namespace nodes are
treated separately.
... | 0.003559 |
async def exists(self, path):
"""
:py:func:`asyncio.coroutine`
Check path for existence.
:param path: path to check
:type path: :py:class:`str` or :py:class:`pathlib.PurePosixPath`
:rtype: :py:class:`bool`
"""
try:
await self.stat(path)
... | 0.004149 |
def debug_async(self, conn_id, cmd_name, cmd_args, progress_callback, callback):
"""Asynchronously complete a named debug command.
The command name and arguments are passed to the underlying device adapter
and interpreted there. If the command is long running, progress_callback
may be ... | 0.007594 |
def get_short_plot_name(self, goobj):
"""Shorten some GO names so plots are smaller."""
name = goobj.name
if self._keep_this(name):
return self.replace_greek(name)
name = name.replace("cellular response to chemical stimulus",
"cellular rsp. to chem... | 0.003394 |
def decode(self, bytes, raw=False):
"""decode(bytearray, raw=False) -> value
Decodes the given bytearray containing the elapsed time in
seconds since the GPS epoch and returns the corresponding
Python :class:`datetime`.
If the optional parameter ``raw`` is ``True``, the integra... | 0.00409 |
def GetMountPoint(self, path=None):
"""Walk back from the path to find the mount point.
Args:
path: a Unicode string containing the path or None. If path is None the
value in self.path is used.
Returns:
path string of the mount point
"""
path = os.path.abspath(
client_u... | 0.004357 |
def _screaming_snake_case(cls, text):
"""
Transform text to SCREAMING_SNAKE_CASE
:param text:
:return:
"""
if text.isupper():
return text
result = ''
for pos, symbol in enumerate(text):
if symbol.isupper() and pos > 0:
... | 0.004684 |
def set_conversion(self, idx):
"""
Adds the conversion to the format.
:param idx: The ending index of the conversion name.
"""
# First, determine the name
if self.conv_begin:
name = self.format[self.conv_begin:idx]
else:
name = self.forma... | 0.002491 |
def do_text(self, subcmd, opts, message):
"""${cmd_name}: get the best text part of the specified message
${cmd_usage}
"""
client = MdClient(self.maildir, filesystem=self.filesystem)
client.gettext(message, self.stdout) | 0.007692 |
def lead(expr, offset, default=None, sort=None, ascending=True):
"""
Get value in the row ``offset`` rows after to the current row.
:param offset: the offset value
:param default: default value for the function, when there are no rows satisfying the offset
:param expr: expression for calculation
... | 0.00354 |
def parse_topo_loc(cl_args):
""" parse topology location """
try:
topo_loc = cl_args['cluster/[role]/[env]'].split('/')
topo_name = cl_args['topology-name']
topo_loc.append(topo_name)
if len(topo_loc) != 4:
raise
return topo_loc
except Exception:
Log.error('Invalid topology location'... | 0.015106 |
def print_callback(msg):
"""Print callback, prints message to stdout as JSON in one line."""
json.dump(msg, stdout)
stdout.write('\n')
stdout.flush() | 0.006061 |
def main():
"""main."""
parser = create_parser()
args = parser.parse_args()
if hasattr(args, 'handler'):
args.handler(args)
else:
parser.print_help() | 0.005376 |
def _issuer(self, entityid=None):
""" Return an Issuer instance """
if entityid:
if isinstance(entityid, Issuer):
return entityid
else:
return Issuer(text=entityid, format=NAMEID_FORMAT_ENTITY)
else:
return Issuer(text=self.conf... | 0.005168 |
def NamedDict(name, fields, description=None, type_attributes=DEFAULT_TYPE_ATTRIBUTES):
'''
A :py:class:`Dict` with a name allowing it to be referenced by that name.
'''
check_user_facing_fields_dict(fields, 'NamedDict named "{}"'.format(name))
class _NamedDict(_ConfigComposite):
def __init... | 0.003413 |
def create_package_node(self, package):
"""
Return a Node representing the package.
Files must have been added to the graph before this method is called.
"""
package_node = BNode()
type_triple = (package_node, RDF.type, self.spdx_namespace.Package)
self.graph.add(... | 0.004492 |
def down(force):
"""
destroys an existing cluster
"""
try:
cloud_config = CloudConfig()
cloud_controller = CloudController(cloud_config)
cloud_controller.down(force)
except CloudComposeException as ex:
print(ex) | 0.003802 |
def items_for_tree_result(cl, result, form):
"""
Generates the actual list of data.
"""
first = True
pk = cl.lookup_opts.pk.attname
for field_name in cl.list_display:
row_class = ''
try:
f, attr, value = lookup_field(field_name, result, cl.model_admin)
except ... | 0.002256 |
def cast_out(self, klass):
"""Interpret the content as a particular class."""
if _debug: SequenceOfAny._debug("cast_out %r", klass)
# make sure it is a list
if not issubclass(klass, List):
raise DecodingError("%r is not a list" % (klass,))
# build a helper
h... | 0.004862 |
def getSampleFrequencies(self):
"""
Returns samplefrequencies of all signals.
Parameters
----------
None
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> all(f.getSampleFrequencies()==200.0)
True
... | 0.004 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.