text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def detectUbuntuTablet(self):
"""Return detection of an Ubuntu Mobile OS tablet
Detects a tablet running the Ubuntu Mobile OS.
"""
if UAgentInfo.deviceUbuntu in self.__userAgent \
and UAgentInfo.deviceTablet in self.__userAgent:
return True
return False | 0.006289 |
def get_text(self, index=None):
"""
Gets text from a given index. If index=None, returns the current value
self.get_text(self.get_value())
"""
if index==None:
return self.get_text(self.get_value())
else:
return str(self._widget.itemText(index)) | 0.012658 |
def get_outputs_from_cm(index, cm):
"""Return indices of the outputs of node with the given index."""
return tuple(i for i in range(cm.shape[0]) if cm[index][i]) | 0.005917 |
def cycle(self):
"""
Request one batch of events from Skype, calling :meth:`onEvent` with each event in turn.
Subclasses may override this method to alter loop functionality.
"""
try:
events = self.getEvents()
except requests.ConnectionError:
retu... | 0.006818 |
def _partition_group(self, group):
"""
Args:
group (list): A group of states
Return:
tuple: A set of two groups
"""
for (group1, group2, distinguish_string) in self.bookeeping:
if group & group1 != set() and not group.issubset(group1):
... | 0.002805 |
async def service_info(self, name):
"""Pull descriptive info of a service by name.
Information returned includes the service's user friendly
name and whether it was preregistered or added dynamically.
Returns:
dict: A dictionary of service information with the following key... | 0.004149 |
def _misalign_split(self,alns):
"""Requires alignment strings have been set so for each exon we have
query, target and query_quality
_has_quality will specify whether or not the quality is meaningful
"""
total = []
z = 0
for x in alns:
z += 1
exon_num = z
if self._ali... | 0.037566 |
def p_function_call_variable(p):
'function_call : variable_without_objects LPAREN function_call_parameter_list RPAREN'
p[0] = ast.FunctionCall(p[1], p[3], lineno=p.lineno(2)) | 0.010989 |
def get_pages(url):
"""
Return the 'pages' from the starting url
Technically, look for the 'next 50' link, yield and download it, repeat
"""
while True:
yield url
doc = html.parse(url).find("body")
links = [a for a in doc.findall(".//a") if a.text and a.text.startswith("next... | 0.004843 |
def create_SpikeGeneratorGroup(self,time_label=0,index_label=1,reorder_indices=False,index_offset=True):
"""
Creates a brian 2 create_SpikeGeneratorGroup object that contains the spikes in this container.
time_label: Name or number of the label that contains the spike times (def... | 0.011041 |
def remove_alert_tag(self, id, tag_value, **kwargs): # noqa: E501
"""Remove a tag from a specific alert # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove... | 0.002075 |
def get_installed_extension(name,
user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
runas=None):
'''
Get info about an instal... | 0.001316 |
def _get_max_subplot_ids(fig):
"""
Given an input figure, return a dict containing the max subplot number
for each subplot type in the figure
Parameters
----------
fig: dict
A plotly figure dict
Returns
-------
dict
A dict from subplot type strings to integers indic... | 0.000814 |
def handle_emphasis(self, start, tag_style, parent_style):
"""handles various text emphases"""
tag_emphasis = google_text_emphasis(tag_style)
parent_emphasis = google_text_emphasis(parent_style)
# handle Google's text emphasis
strikethrough = 'line-through' in tag_emphasis and ... | 0.00317 |
def from_xdr(cls, xdr):
"""Create an :class:`Asset` object from its base64 encoded XDR
representation.
:param bytes xdr: The base64 encoded XDR Asset object.
:return: A new :class:`Asset` object from its encoded XDR
representation.
"""
xdr_decoded = base64.... | 0.003914 |
def _send(self, packet):
"""Add packet to send queue."""
fut = self.loop.create_future()
self.waiters.append((fut, packet))
if self.waiters and self.in_transaction is False:
self.protocol.send_packet()
return fut | 0.007576 |
def raise_msg_to_str(msg):
"""msg is a return arg from a raise. Join with new lines"""
if not is_string_like(msg):
msg = '\n'.join(map(str, msg))
return msg | 0.00565 |
def _default_ns_prefix(nsmap):
"""
XML doc may have several prefix:namespace_url pairs, can also specify
a namespace_url as default, tags in that namespace don't need a prefix
NOTE:
we rely on default namespace also present in prefixed form, I'm not sure if
this is an XML certainty or a quirk of... | 0.000877 |
def parse_raxml(handle):
"""Parse RAxML's summary output.
*handle* should be an open file handle containing the RAxML
output. It is parsed and a dictionary returned.
"""
s = ''.join(handle.readlines())
result = {}
try_set_fields(result, r'(?P<program>RAxML version [0-9.]+)', s)
try_set... | 0.0006 |
def line_plot(df, xypairs, mode, layout={}, config=_BASE_CONFIG):
""" basic line plot
dataframe to json for a line plot
Args:
df (pandas.DataFrame): input dataframe
xypairs (list): list of tuples containing column names
mode (str): plotly... | 0.001919 |
def last_event(request, slug):
"Displays a list of all services and their current status."
try:
service = Service.objects.get(slug=slug)
except Service.DoesNotExist:
return HttpResponseRedirect(reverse('overseer:index'))
try:
evt = service.event_set.order_by('-date_crea... | 0.008811 |
def close_others(self):
"""
Closes every editors tabs except the current one.
"""
current_widget = self.currentWidget()
self._try_close_dirty_tabs(exept=current_widget)
i = 0
while self.count() > 1:
widget = self.widget(i)
if widget != curr... | 0.004938 |
def consume_length_prefix(rlp, start):
"""Read a length prefix from an RLP string.
:param rlp: the rlp byte string to read from
:param start: the position at which to start reading
:returns: a tuple ``(prefix, type, length, end)``, where ``type`` is either ``str``
or ``list`` depending on... | 0.003168 |
def edges(self, nodes=None):
"""Iterator for node values.
Yield:
node: the node.
"""
for source_node, dest_node, edge_data in self._multi_graph.edges(nodes, data=True):
yield source_node, dest_node, edge_data | 0.011321 |
def connected_grid_lines(network, busids):
""" Get grid lines connected to given buses.
Parameters
----------
network : :class:`pypsa.Network
Overall container of PyPSA
busids : list
List containing bus-ids.
Returns
-------
:class:`pandas.DataFrame
PyPSA lines.... | 0.002237 |
def get_file_listing_sha(listing_paths: Iterable) -> str:
"""Return sha256 string for group of FTP listings."""
return sha256(''.join(sorted(listing_paths)).encode('utf-8')).hexdigest() | 0.005155 |
def s2dctmat(nfilt,ncep,freqstep):
"""Return the 'legacy' not-quite-DCT matrix used by Sphinx"""
melcos = numpy.empty((ncep, nfilt), 'double')
for i in range(0,ncep):
freq = numpy.pi * float(i) / nfilt
melcos[i] = numpy.cos(freq * numpy.arange(0.5, float(nfilt)+0.5, 1.0, 'double'))
melco... | 0.019231 |
def clear(name):
'''
Clear the namespace from the register
USAGE:
.. code-block:: yaml
clearns:
reg.clear:
- name: myregister
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': True}
if name in __reg__:
_... | 0.002817 |
def Size(self):
"""
Get the total size in bytes of the object.
Returns:
int: size.
"""
# Items should be an array of type CoinState, not of ints!
corrected_items = list(map(lambda i: CoinState(i), self.Items))
return super(UnspentCoinState, self).Size... | 0.008523 |
def get_end_time_str(self):
"""
:return:
|attr_end_datetime| as a |str| formatted with
|attr_end_time_format|.
Return |NaT| if invalid datetime or format.
:rtype: str
:Sample Code:
.. code:: python
from datetimerange impor... | 0.003348 |
def chunked(records, single=True):
""" Memory and performance friendly method to iterate over a potentially
large number of records. Yields either a whole chunk or a single record
at the time. Don't nest calls to this method. """
if version_info[0] > 10:
invalidate = records.env.cache.invalidate... | 0.00119 |
def remove_by_threshold(self, threshold=5):
""" Remove all words at, or below, the provided threshold
Args:
threshold (int): The threshold at which a word is to be \
removed """
keys = [x for x in self._dictionary.keys()]
for key in keys:
... | 0.004608 |
def render_pep440_pre(pieces):
"""TAG[.post.devDISTANCE] -- No -dirty.
Exceptions:
1: no tags. 0.post.devDISTANCE
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"]:
rendered += ".post.dev%d" % pieces["distance"]
else:
# exce... | 0.002481 |
def backup(mongo_username, mongo_password, local_backup_directory_path, database=None,
attached_directory_path=None, custom_prefix="backup",
mongo_backup_directory_path="/tmp/mongo_dump",
s3_bucket=None, s3_access_key_id=None, s3_secret_key=None,
purge_local=None, purge_a... | 0.007787 |
def opensignals_hierarchy(root=None, update=False, clone=False):
"""
Function that generates the OpenSignalsTools Notebooks File Hierarchy programatically.
----------
Parameters
----------
root : None or str
The file path where the OpenSignalsTools Environment will be stored.
updat... | 0.003916 |
def send_update_port_statuses(self, context, port_ids, status):
"""Call the pluging to update the port status which updates the DB.
:param context: contains user information
:param port_ids: list of ids of the ports associated with the status
:param status: value of the status for the g... | 0.003766 |
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.con... | 0.002976 |
def _init_logging(anteater_log):
""" Setup root logger for package """
LOG.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - '
'%(levelname)s - %(message)s')
ch.setFormatter(formatter)
ch.setLevel(loggi... | 0.001323 |
def path_complete(self, text: str, line: str, begidx: int, endidx: int,
path_filter: Optional[Callable[[str], bool]] = None) -> List[str]:
"""Performs completion of local file system paths
:param text: the string prefix we are attempting to match (all returned matches must begin w... | 0.00248 |
def show_keyword_help(cur, arg):
"""
Call the built-in "show <command>", to display help for an SQL keyword.
:param cur: cursor
:param arg: string
:return: list
"""
keyword = arg.strip('"').strip("'")
query = "help '{0}'".format(keyword)
log.debug(query)
cur.execute(query)
if... | 0.001821 |
def sedfile(fpath, regexpr, repl, force=False, verbose=True, veryverbose=False):
"""
Executes sed on a specific file
Args:
fpath (str): file path string
regexpr (str):
repl (str):
force (bool): (default = False)
verbose (bool): verbosity flag(default = True)
... | 0.001762 |
def get_left_ngrams(mention, window=3, attrib="words", n_min=1, n_max=1, lower=True):
"""Get the ngrams within a window to the *left* from the sentence Context.
For higher-arity Candidates, defaults to the *first* argument.
:param mention: The Mention to evaluate. If a candidate is given, default
... | 0.002962 |
def density(self, r, rho0, Rs):
"""
computes the density
:param x:
:param y:
:param rho0:
:param a:
:param s:
:return:
"""
rho = rho0 / (r/Rs * (1 + (r/Rs))**3)
return rho | 0.007722 |
def read_file_offset(self, id, offset, limit, path="/"):
""" Read contents of a file in an allocation directory.
https://www.nomadproject.io/docs/http/client-fs-cat.html
arguments:
- id: (str) allocation_id required
- offset: (int) required
- li... | 0.002717 |
def _loadable_get_(name, self):
"Used to lazily-evaluate & memoize an attribute."
func = getattr(self._attr_func_, name)
ret = func()
setattr(self._attr_data_, name, ret)
setattr(
type(self),
name,
property(
functools.partial(s... | 0.004695 |
def overlap(self, other):
"""Determine whether this range overlaps with another."""
if self._start < other.end and self._end > other.start:
return True
return False | 0.01 |
def _api_create(cls, api_key=djstripe_settings.STRIPE_SECRET_KEY, **kwargs):
"""
Call the stripe API's create operation for this model.
:param api_key: The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.
:type api_key: string
"""
return cls.stripe_class.create(api_key=api... | 0.026866 |
def calculate_boundingbox(lng, lat, miles):
"""
Given a latitude, longitude and a distance in miles, calculate
the co-ordinates of the bounding box 2*miles on long each side with the
given co-ordinates at the center.
"""
latChange = change_in_latitude(miles)
latSouth = lat - latChange
l... | 0.001988 |
def build_fred(self):
'''Build a flat recurrent encoder-decoder dialogue model'''
encoder = Encoder(data=self.data, config=self.model_config)
decoder = Decoder(data=self.data, config=self.model_config, encoder=encoder)
return EncoderDecoder(config=self.model_config, encoder=encoder, de... | 0.011976 |
def validate_is_callable_or_none(option, value):
"""Validates that 'value' is a callable."""
if value is None:
return value
if not callable(value):
raise ValueError("%s must be a callable" % (option,))
return value | 0.004065 |
def drop_dims(self, drop_dims):
"""Drop dimensions and associated variables from this dataset.
Parameters
----------
drop_dims : str or list
Dimension or dimensions to drop.
Returns
-------
obj : Dataset
The dataset without the given dime... | 0.00182 |
def close_trackbacks(self, request, queryset):
"""
Close the trackbacks for selected entries.
"""
queryset.update(trackback_enabled=False)
self.message_user(
request, _('Trackbacks are now closed for selected entries.')) | 0.007353 |
def serialize_query(func):
""" Ensure any SQLExpression instances are serialized"""
@functools.wraps(func)
def wrapper(self, query, *args, **kwargs):
if hasattr(query, 'serialize'):
query = query.serialize()
assert isinstance(query, basestring), 'Expected... | 0.004149 |
def columns(self, **kw):
"""Creates a results set of column names in specified tables by
executing the ODBC SQLColumns function. Each row fetched has the
following columns.
:param table: the table tname
:param catalog: the catalog name
:param schema: the schmea name
... | 0.004264 |
def document_delete(index, doc_type, id, hosts=None, profile=None):
'''
Delete a document from an index
index
Index name where the document resides
doc_type
Type of the document
id
Document identifier
CLI example::
salt myminion elasticsearch.document_delete te... | 0.003953 |
def _set_slave_enabled(self, dpid, port, enabled):
"""set whether a slave i/f at some port of some datapath is
enable or not."""
slave = self._get_slave(dpid, port)
if slave:
slave['enabled'] = enabled | 0.008163 |
def read_header(self):
"""
Reads VPK file header from the file
"""
with fopen(self.vpk_path, 'rb') as f:
(self.signature,
self.version,
self.tree_length
) = struct.unpack("3I", f.read(3*4))
# original format - headerless
... | 0.002259 |
def match(self, path):
"""Return route handler with arguments if path matches this route.
Arguments:
path (str): Request path
Returns:
tuple or None: A tuple of three items:
1. Route handler (callable)
2. Positional arguments (list)
3. K... | 0.003356 |
def workflow_remove_tags(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /workflow-xxxx/removeTags API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Tags#API-method%3A-%2Fclass-xxxx%2FremoveTags
"""
return DXHTTPRequest('/%s/removeTags' % o... | 0.010526 |
def extendMarkdown(self, md, md_globals):
""" Add an instance of FigcaptionProcessor to BlockParser. """
# def_list = 'def_list' in md.registeredExtensions
md.parser.blockprocessors.add(
'figcaption', FigcaptionProcessor(md.parser), '<ulist') | 0.007168 |
def execution(execution: Dict[str, Any], filler: Dict[str, Any]) -> Dict[str, Any]:
"""
For VM tests, specify the code that is being run as well as the current state of
the EVM. State tests don't support this object. The parameter is a dictionary specifying some
or all of the following keys:
+-----... | 0.004783 |
def convert_schema(raml_schema, mime_type):
""" Restructure `raml_schema` to a dictionary that has 'properties'
as well as other schema keys/values.
The resulting dictionary looks like this::
{
"properties": {
"field1": {
"required": boolean,
"type":... | 0.000945 |
def update_layers_warper(service):
"""
Update layers for a Warper service.
Sample endpoint: http://warp.worldmap.harvard.edu/maps
"""
params = {'field': 'title', 'query': '', 'show_warped': '1', 'format': 'json'}
headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
re... | 0.001821 |
def read_header(fd, endian):
"""Read and return the matrix header."""
flag_class, nzmax = read_elements(fd, endian, ['miUINT32'])
header = {
'mclass': flag_class & 0x0FF,
'is_logical': (flag_class >> 9 & 1) == 1,
'is_global': (flag_class >> 10 & 1) == 1,
'is_complex': (flag_c... | 0.001497 |
def copyto(self, other):
"""Copies the value of this array to another array.
If ``other`` is a ``NDArray`` or ``RowSparseNDArray`` object, then ``other.shape``
and ``self.shape`` should be the same. This function copies the value from
``self`` to ``other``.
If ``other`` is a co... | 0.005874 |
def flatten(iterable):
"""
flatten(sequence) -> list
Returns a single, flat list which contains all elements retrieved
from the sequence and all recursively contained sub-sequences
(iterables).
:param sequence: any object that implements iterable protocol (see: :ref:`typeiter`)
:return: li... | 0.002591 |
def get_html(url,
headers=None,
timeout=None,
errors="strict",
wait_time=None,
driver=None,
zillow_only=False,
cache_only=False,
zillow_first=False,
cache_first=False,
random=False,
... | 0.000506 |
def _checkReplyTo(self, value):
'''WS-Address From
value -- From server returned in wsa:To
'''
if value != self._replyTo:
raise WSActionException, 'wrong WS-Address ReplyTo(%s), expecting %s'%(value,self._replyTo) | 0.023256 |
def install(self, plugin, name=None, **opts):
"""Install plugin to the application."""
source = plugin
if isinstance(plugin, str):
module, _, attr = plugin.partition(':')
module = import_module(module)
plugin = getattr(module, attr or 'Plugin', None)
... | 0.003295 |
def digest(self, data=None):
"""
Finalizes digest operation and return digest value
Optionally hashes more data before finalizing
"""
if self.digest_finalized:
return self.digest_out.raw[:self.digest_size]
if data is not None:
self.update(data)
... | 0.002845 |
def number_to_lower_endian(n, base):
"""Helper function: convert a number to a list of digits in the given base."""
if n < base:
return [n]
return [n % base] + number_to_lower_endian(n // base, base) | 0.023923 |
def _missing_required_parameters(rqset, **kwargs):
"""Helper function to do operation on sets.
Checks for any missing required parameters.
Returns non-empty or empty list. With empty
list being False.
::returns list
"""
key_set = set(list(iterkeys(kwargs)))
required_minus_received = rq... | 0.002387 |
def _create_storage_directories():
"""Create various storage directories, if those do not exist."""
# Create configuration directory
if not os.path.exists(common.CONFIG_DIR):
os.makedirs(common.CONFIG_DIR)
# Create data directory (for log file)
if not os.path.exists(c... | 0.003914 |
def focusInEvent(self, event):
"""
Updates the focus in state for this edit.
:param event | <QFocusEvent>
"""
super(XLineEdit, self).focusInEvent(event)
self._focusedIn = True | 0.015748 |
def include_file_cb(include_path, line_ranges, symbol):
"""
Banana banana
"""
lang = ''
if include_path.endswith((".md", ".markdown")):
lang = 'markdown'
else:
split = os.path.splitext(include_path)
if len(split) == 2:
e... | 0.002299 |
def _get_intra_event_phi(self, C, mag, rjb, vs30, num_sites):
"""
Returns the intra-event standard deviation (phi), dependent on
magnitude, distance and vs30
"""
base_vals = np.zeros(num_sites)
# Magnitude Dependent phi (Equation 17)
if mag <= 4.5:
bas... | 0.001645 |
def vm_present(name, vmconfig, config=None):
'''
Ensure vm is present on the computenode
name : string
hostname of vm
vmconfig : dict
options to set for the vm
config : dict
fine grain control over vm_present
.. note::
The following configuration properties can... | 0.003902 |
def arrays(self):
""" Returns symbol instances corresponding to arrays
of the current scope.
"""
return [x for x in self[self.current_scope].values() if x.class_ == CLASS.array] | 0.014354 |
def _save_results(options, module, core_results, fit_results):
"""
Save results of analysis as tables and figures
Parameters
----------
options : dict
Option names and values for analysis
module : str
Module that contained function used to generate core_results
core_results ... | 0.001471 |
def grok_for_node(element, default_vars):
"""Properly parses a For loop element"""
if isinstance(element.iter, jinja2.nodes.Filter):
if element.iter.name == 'default' \
and element.iter.node.name not in default_vars:
default_vars.append(element.iter.node.name)
default_var... | 0.002618 |
def new(self):
# type: () -> None
'''
Create a new Rock Ridge Child Link record.
Parameters:
None.
Returns:
Nothing.
'''
if self._initialized:
raise pycdlibexception.PyCdlibInternalError('CL record already initialized!')
sel... | 0.00995 |
def get_execution_state(cluster, environ, topology, role=None):
'''
Get the execution state of a topology in a cluster
:param cluster:
:param environ:
:param topology:
:param role:
:return:
'''
params = dict(cluster=cluster, environ=environ, topology=topology)
if role is not None:
params['role']... | 0.014493 |
def _make_dir(self, client_kwargs):
"""
Make a directory.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_oss_error():
bucket = self._get_bucket(client_kwargs)
# Object
if 'key' in client_kwargs:
ret... | 0.004329 |
def requestOpenOrders(self, all_clients=False):
"""
Request open orders - loads up orders that wasn't created using this session
"""
if all_clients:
self.ibConn.reqAllOpenOrders()
self.ibConn.reqOpenOrders() | 0.011583 |
def bind_device_to_gateway(
self,
parent,
gateway_id,
device_id,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Associates the device with the gateway.
Example:
... | 0.003336 |
def sync_policies(self, vault_client):
"""Synchronizes policies only"""
p_resources = [x for x in self.resources()
if isinstance(x, Policy)]
for resource in p_resources:
resource.sync(vault_client)
return [x for x in self.resources()
if... | 0.005764 |
def successfuly_encodes(msg, raise_err=False):
"""
boolean response if a message contains correct information to serialize
:param msg: <proto object>
:param raise_err: <bool>
:return: <bool>
"""
result = True
try:
msg.SerializeToString()
except EncodeError as encode_error:
... | 0.002427 |
def print_with_header(header, message, color, indent=0):
"""
Use one of the functions below for printing, not this one.
"""
print()
padding = ' ' * indent
print(padding + color + BOLD + header + ENDC + color + message + ENDC) | 0.004016 |
def __field_callback(self, field, event, *args, **kwargs):
# type: (str, str, *Any, **Any) -> Any
"""
Calls the registered method in the component for the given field event
:param field: A field name
:param event: An event (IPOPO_CALLBACK_VALIDATE, ...)
:return: The call... | 0.002901 |
def _get_node_key(self, node_dict_item):
"""Return a tuple of sorted sources and targets given a node dict."""
s = tuple(sorted(node_dict_item['sources']))
t = tuple(sorted(node_dict_item['targets']))
return (s, t) | 0.00813 |
def get_name_from_abbrev(abbrev, case_sensitive=False):
"""
Given a country code abbreviation, get the full name from the table.
abbrev: (str) Country code to retrieve the full name of.
case_sensitive: (bool) When True, enforce case sensitivity.
"""
if case_sensitive:
country_code = abb... | 0.001869 |
def org_find_members(org_id=None, level=None, describe=False):
"""
:param org_id: ID of the organization
:type org_id: string
:param level: The membership level in the org that each member in the result set must have (one of "MEMBER" or
"ADMIN")
:type level: string
:param describe: Wheth... | 0.005964 |
def gp_rdiff(version, nomed, noxerr, diffRel, divdNdy):
"""example for ratio or difference plots using QM12 data (see gp_panel)
- uses uncertainties package for easier error propagation and rebinning
- stat. error for medium = 0!
- stat. error for cocktail ~ 0!
- statistical error bar on data stays the same ... | 0.023741 |
def create_jwt_token(secret, client_id):
"""
Create JWT token for GOV.UK Notify
Tokens have standard header:
{
"typ": "JWT",
"alg": "HS256"
}
Claims consist of:
iss: identifier for the client
iat: issued at in epoch seconds (UTC)
:param secret: Application signing ... | 0.001357 |
def dyld_find(name, executable_path=None, env=None):
"""
Find a library or framework using dyld semantics
"""
name = _ensure_utf8(name)
executable_path = _ensure_utf8(executable_path)
for path in dyld_image_suffix_search(chain(
dyld_override_search(name, env),
dyl... | 0.003597 |
def from_text(text):
"""Convert text into an opcode.
@param text: the textual opcode
@type text: string
@raises UnknownOpcode: the opcode is unknown
@rtype: int
"""
if text.isdigit():
value = int(text)
if value >= 0 and value <= 15:
return value
value = _by_... | 0.002445 |
def _restore_port_binding(self,
switch_ip, pvlan_ids,
port, native_vlan):
"""Restores a set of vlans for a given port."""
intf_type, nexus_port = nexus_help.split_interface_name(port)
# If native_vlan is configured, this is isolated sin... | 0.002712 |
def _conditions(self, full_path, environ):
"""Return a tuple of etag, last_modified by mtime from stat."""
mtime = stat(full_path).st_mtime
return str(mtime), rfc822.formatdate(mtime) | 0.009662 |
def download(link, outdir='.', chunk_size=4096):
'''
This is the Main function, which downloads a given link
and saves on outdir (default = current directory)
'''
url = None
fh = None
eta = 'unknown '
bytes_so_far = 0
filename = filename_from_url(link) or "."
cj = cjar.CookieJar(... | 0.000541 |
def restart(self, container, instances=None, map_name=None, **kwargs):
"""
Restarts instances for a container configuration.
:param container: Container name.
:type container: unicode | str
:param instances: Instance names to stop. If not specified, will restart all instances as... | 0.006116 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.