text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def spnoise(s, frc, smn=0.0, smx=1.0):
"""Return image with salt & pepper noise imposed on it.
Parameters
----------
s : ndarray
Input image
frc : float
Desired fraction of pixels corrupted by noise
smn : float, optional (default 0.0)
Lower value for noise (pepper)
smx : f... | 0.001689 |
def clean_errors(self):
"""Clean errors and unhighlight them in vim."""
self._vim.eval('clearmatches()')
self._errors = []
self._matches = []
# Reset Syntastic notes - TODO: bufdo?
self._vim.current.buffer.vars['ensime_notes'] = [] | 0.007168 |
def main():
'''Main routine.'''
# Load Azure app defaults
try:
with open('azurermconfig.json') as config_file:
config_data = json.load(config_file)
except FileNotFoundError:
sys.exit("Error: Expecting azurermonfig.json in current folder")
tenant_id = config_data['tenantI... | 0.00589 |
def build_k33_graph():
"""Makes a new K3,3 graph.
Ref: http://mathworld.wolfram.com/UtilityGraph.html"""
graph = UndirectedGraph()
# K3,3 has 6 nodes
for _ in range(1, 7):
graph.new_node()
# K3,3 has 9 edges
# --Edge: a
graph.new_edge(1, 4)
# --Edge: b
graph.new_edge... | 0.001585 |
def cached_route(self, url_rule, name=None, options=None, TTL=None):
'''A decorator to add a route to a view and also apply caching. The
url_rule, name and options arguments are the same arguments for the
route function. The TTL argument if given will passed along to the
caching decorato... | 0.003072 |
def Create(name,alias=None,location=None,session=None):
"""Creates a new anti-affinity policy within a given account.
https://t3n.zendesk.com/entries/45042770-Create-Anti-Affinity-Policy
*TODO* Currently returning 400 error:
clc.APIFailedResponse: Response code 400. . POST https://api.tier3.com/v2/antiAffinit... | 0.035665 |
def libvlc_set_user_agent(p_instance, name, http):
'''Sets the application name. LibVLC passes this as the user agent string
when a protocol requires it.
@param p_instance: LibVLC instance.
@param name: human-readable application name, e.g. "FooBar player 1.2.3".
@param http: HTTP User Agent, e.g. "... | 0.003175 |
def ec2_table(instances):
"""
Print nice looking table of information from list of instances
"""
t = prettytable.PrettyTable(['ID', 'State', 'Monitored', 'Image', 'Name', 'Type', 'SSH key', 'DNS'])
t.align = 'l'
for i in instances:
name = i.tags.get('Name', '')
t.add_row([i.id, i... | 0.007264 |
def find_kernel_specs(self):
"""Returns a dict mapping kernel names to resource directories."""
# let real installed kernels overwrite envs with the same name:
# this is the same order as the get_kernel_spec way, which also prefers
# kernels from the jupyter dir over env kernels.
... | 0.004049 |
def write_and_return(
command, ack, serial_connection, timeout=DEFAULT_WRITE_TIMEOUT):
'''Write a command and return the response'''
clear_buffer(serial_connection)
with serial_with_temp_timeout(
serial_connection, timeout) as device_connection:
response = _write_to_device_and_re... | 0.002653 |
def get_description():
"""Get long description from README."""
with open(path.join(here, 'README.rst'), 'r') as f:
data = f.read()
return data | 0.006173 |
def process_request_thread(self, request, client_address):
"""
Same as in BaseServer but as a thread.
In addition, exception handling is done here.
"""
from ..blockstackd import get_gc_thread
try:
self.finish_request(request, client_address)
except Ex... | 0.002865 |
def close(self):
"""Add docstring!"""
# Seek to the start of the buffer
self.seek(0)
while True:
# Copy bytes from the buffer until we reach the end of the JSON
brace_count = 0
quoted = False
json_string = ''
while True:
... | 0.000888 |
def changelist_view(self, request, extra_context=None):
"""Add advanced_filters form to changelist context"""
if extra_context is None:
extra_context = {}
response = self.adv_filters_handle(request,
extra_context=extra_context)
if re... | 0.004124 |
def handle_request(self, connection, msg):
"""Dispatch a request message to the appropriate method.
Parameters
----------
connection : ClientConnection object
The client connection the message was from.
msg : Message object
The request message to process.... | 0.001795 |
def _get_previous_mz(self, mzs):
'''given an mz array, return the mz_data (disk location)
if the mz array was not previously written, write to disk first'''
mzs = tuple(mzs) # must be hashable
if mzs in self.lru_cache:
return self.lru_cache[mzs]
# mz not recognized ... | 0.003155 |
def contrib_setup_py(name, description, additional_classifiers=None, **kwargs):
"""Creates the setup_py for a pants contrib plugin artifact.
:param str name: The name of the package; must start with 'pantsbuild.pants.contrib.'.
:param str description: A brief description of what the plugin provides.
:param lis... | 0.007621 |
def get_extana_led(self, cached=True):
"""Returns the current (R, G, B) colour of the SK8-ExtAna LED.
Args:
cached (bool): if True, returns the locally cached state of the LED (based
on the last call to :meth:`set_extana_led`). Otherwise query the device
for ... | 0.007165 |
def get_correct_answer(question, default=None, required=False,
answer=None, is_answer_correct=None):
u"""Ask user a question and confirm answer
Args:
question (str): Question to ask user
default (str): Default answer if no input from user
required (str): Requir... | 0.000751 |
def wp_draw_callback(self, points):
'''callback from drawing waypoints'''
if len(points) < 3:
return
from MAVProxy.modules.lib import mp_util
home = self.wploader.wp(0)
self.wploader.clear()
self.wploader.target_system = self.target_system
self.wploade... | 0.00561 |
def deref(self, ctx):
"""
Returns the value this reference is pointing to. This method uses 'ctx' to resolve the reference and return
the value this reference references.
If the call was already made, it returns a cached result.
It also makes sure there's no cyclic reference, and... | 0.005118 |
def resort_client_actions(portal):
"""Resorts client action views
"""
sorted_actions = [
"edit",
"contacts",
"view", # this redirects to analysisrequests
"analysisrequests",
"batches",
"samplepoints",
"profiles",
"templates",
"specs",
... | 0.003456 |
def import_project_sitetree_modules():
"""Imports sitetrees modules from packages (apps).
Returns a list of submodules.
:rtype: list
"""
from django.conf import settings as django_settings
submodules = []
for app in django_settings.INSTALLED_APPS:
module = import_app_sitetree_module... | 0.002404 |
def normalize(self, bias_range=1, poly_range=None, ignored_terms=None):
"""Normalizes the biases of the binary polynomial such that they fall in
the provided range(s).
If `poly_range` is provided, then `bias_range` will be treated as
the range for the linear biases and `poly_range` will... | 0.001449 |
def module_path(self, filepath):
"""given a filepath like /base/path/to/module.py this will convert it to
path.to.module so it can be imported"""
possible_modbits = re.split('[\\/]', filepath.strip('\\/'))
basename = possible_modbits[-1]
prefixes = possible_modbits[0:-1]
... | 0.007553 |
def get_instance(self, payload):
"""
Build an instance of MessageInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.chat.v2.service.channel.message.MessageInstance
:rtype: twilio.rest.chat.v2.service.channel.message.MessageInstance
"""
... | 0.003876 |
def resample(self,N):
"""Returns a random sampling.
"""
return rand.random(size=N)*(self.maxval - self.minval) + self.minval | 0.02027 |
def get_option_by_id(cls, option_id, **kwargs):
"""Find Option
Return single instance of Option by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_option_by_id(option_id, async=Tru... | 0.002328 |
def get_version():
""" Gets the current version of the package.
"""
version_py = os.path.join(os.path.dirname(__file__), 'deepgram', 'version.py')
with open(version_py, 'r') as fh:
for line in fh:
if line.startswith('__version__'):
return line.split('=')[-1].strip().replace('"', '')
raise ValueError('Fail... | 0.02439 |
def _prepare(self):
"""Pre-formats the multipart HTTP request to transmit the directory."""
names = []
added_directories = set()
def add_directory(short_path):
# Do not continue if this directory has already been added
if short_path in added_directories:
... | 0.000801 |
def load_graphml(filename, folder=None, node_type=int):
"""
Load a GraphML file from disk and convert the node/edge attributes to
correct data types.
Parameters
----------
filename : string
the name of the graphml file (including file extension)
folder : string
the folder co... | 0.002952 |
def dist_typo(
src, tar, metric='euclidean', cost=(1, 1, 0.5, 0.5), layout='QWERTY'
):
"""Return the normalized typo distance between two strings.
This is a wrapper for :py:meth:`Typo.dist`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target strin... | 0.000749 |
def deserialise(self, element_json: str) -> Element:
"""
Deserialises the given JSON into an element.
>>> json = '{"element": "string", "content": "Hello"'
>>> JSONDeserialiser().deserialise(json)
String(content='Hello')
"""
return self.deserialise_dict(json.loa... | 0.005935 |
def gauss_weighted_stats(x, yarray, x_new, fwhm):
"""
Calculate gaussian weigted moving mean, SD and SE.
Parameters
----------
x : array-like
The independent variable
yarray : (n,m) array
Where n = x.size, and m is the number of
dependent variables to smooth.
x_new :... | 0.000733 |
def delta_to_str(rd):
""" Convert a relativedelta to a human-readable string """
parts = []
if rd.days > 0:
parts.append("%d day%s" % (rd.days, plural(rd.days)))
clock_parts = []
if rd.hours > 0:
clock_parts.append("%02d" % rd.hours)
if rd.minutes > 0 or rd.hours > 0:
clo... | 0.001812 |
def _parse_errback(self, error):
"""
Parse an error from an XML-RPC call.
raises: ``IOError`` when the Twisted XML-RPC connection times out.
raises: ``KojiException`` if we got a response from the XML-RPC
server but it is not one of the ``xmlrpc.Fault``s that
... | 0.002016 |
def array_shift(a, n, fill="average"):
"""
This will return an array with all the elements shifted forward in index by n.
a is the array
n is the amount by which to shift (can be positive or negative)
fill="average" fill the new empty elements with the average of the array
fill="wrap" ... | 0.0139 |
def add(self, sensor):
"""Add a sensor, warning if it exists."""
if isinstance(sensor, (list, tuple)):
for sss in sensor:
self.add(sss)
return
if not isinstance(sensor, Sensor):
raise TypeError("pysma.Sensor expected")
if sensor.name ... | 0.003306 |
def sparse_is_desireable(lhs, rhs):
'''
Examines a pair of matrices and determines if the result of their multiplication should be sparse or not.
'''
return False
if len(lhs.shape) == 1:
return False
else:
lhs_rows, lhs_cols = lhs.shape
if len(rhs.shape) == 1:
rhs_ro... | 0.006944 |
def convert_transpose(node, **kwargs):
"""Map MXNet's transpose operator attributes to onnx's Transpose operator
and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
axes = attrs.get("axes", ())
if axes:
axes = tuple(map(int, re.findall(r'\d+', axes)))
... | 0.001471 |
def reference_cluster(envs, name):
"""
Return set of all env names referencing or
referenced by given name.
>>> cluster = sorted(reference_cluster([
... {'name': 'base', 'refs': []},
... {'name': 'test', 'refs': ['base']},
... {'name': 'local', 'refs': ['test']},
... ], 'tes... | 0.001037 |
def get_action(self, brain_info: BrainInfo) -> ActionInfo:
"""
Decides actions given observations information, and takes them in environment.
:param brain_info: A dictionary of brain names and BrainInfo from environment.
:return: an ActionInfo containing action, memories, values and an o... | 0.006831 |
def DEFINE_integer_list(self, name, default, help, constant=False):
"""A helper for defining lists of integer options."""
self.AddOption(
type_info.List(
name=name,
default=default,
description=help,
validator=type_info.Integer()),
constant=constan... | 0.003106 |
def get_3D_coordmap(img):
'''
Gets a 3D CoordinateMap from img.
Parameters
----------
img: nib.Nifti1Image or nipy Image
Returns
-------
nipy.core.reference.coordinate_map.CoordinateMap
'''
if isinstance(img, nib.Nifti1Image):
img = nifti2nipy(img)
if img.ndim == 4... | 0.002079 |
def transform(self, trans):
'''Return a copy of this neurite with a 3D transformation applied'''
clone = deepcopy(self)
for n in clone.iter_sections():
n.points[:, 0:3] = trans(n.points[:, 0:3])
return clone | 0.007937 |
def unmap_by_address(self, absolute_address):
"""
Removes a mapping based on its absolute address.
:param absolute_address: An absolute address
"""
desc = self._address_to_region_id[absolute_address]
del self._address_to_region_id[absolute_address]
del self._reg... | 0.005666 |
def write(self, outputfile='out.pdb', appended=False):
"""
Save the second PDB file aligned to the first.
If appended is True, both are saved as different chains.
"""
# FIXME some cases don't work.
matrix = self.get_matrix(**self.get_current_values())
out = open... | 0.002791 |
def write_collided_alias(collided_alias_dict):
"""
Write the collided aliases string into the collided alias file.
"""
# w+ creates the alias config file if it does not exist
open_mode = 'r+' if os.path.exists(GLOBAL_COLLIDED_ALIAS_PATH) else 'w+'
with open(GLOBAL_COLLIDE... | 0.008299 |
def _wrap_in_place(func): # noqa: D202
"""Take a function that doesn't return the graph and returns the graph."""
@wraps(func)
def wrapper(graph, *args, **kwargs):
"""Apply the enclosed function and returns the graph."""
func(graph, *args, **kwargs)
return g... | 0.008621 |
def is_text(self):
""" Tells if this message is a text message.
Returns:
bool. Success
"""
return self.type in [
self._TYPE_PASTE,
self._TYPE_TEXT,
self._TYPE_TWEET
] | 0.007843 |
def remove(self, parameters):
"""
Remove one or more parameters from this subscription.
:param parameters: Parameter(s) to be removed
:type parameters: Union[str, str[]]
"""
# Verify that we already know our assigned subscription_id
assert self.subscription_id !... | 0.003344 |
def _from_cfg(self, cfg):
"""
Initialize CFBlanket from a CFG instance.
:param cfg: A CFG instance.
:return: None
"""
# Let's first add all functions first
for func in cfg.kb.functions.values():
self.add_function(func)
self._mark_unknowns... | 0.006211 |
def remove_page_boundary_lines(docbody):
"""Try to locate page breaks, headers and footers within a document body,
and remove the array cells at which they are found.
@param docbody: (list) of strings, each string being a line in the
document's body.
@return: (list) of strings. The docu... | 0.000702 |
def repository_get(name, local=False, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Get existing repository details.
name
Repository name
local
Retrieve only local information, default is false
CLI example::
salt myminion elasticsearch.repository_get testr... | 0.002833 |
def call_command(name, *args, **options):
"""
Calls the given command, with the given options and args/kwargs.
This is the primary API you should use for calling specific commands.
Some examples:
call_command('syncdb')
call_command('shell', plain=True)
call_command('sqlall', 'm... | 0.001745 |
def strip_minidom_whitespace(node):
"""Strips all whitespace from a minidom XML node and its children
This operation is made in-place."""
for child in node.childNodes:
if child.nodeType == Node.TEXT_NODE:
if child.nodeValue:
child.nodeValue = child.nodeValue.strip()
... | 0.002445 |
def contains(self, element):
"""
Ensures :attr:`subject` contains *other*.
"""
self._run(unittest_case.assertIn, (element, self._subject))
return ChainInspector(self._subject) | 0.009302 |
def Liu_Winterton(m, x, D, rhol, rhog, mul, kl, Cpl, MW, P, Pc, Te):
r'''Calculates heat transfer coefficient for film boiling of saturated
fluid in any orientation of flow. Correlation
is as developed in [1]_, also reviewed in [2]_ and [3]_.
Excess wall temperature is required to use this correla... | 0.006772 |
def plots_html_page():
"""Generate general statistics
Output is an html page, rendered to 'plots_html_page.html' in the output directory.
"""
# page template
template = jenv.get_template("plots_html_page.html")
# container for template context
context = dict()
# a database client/sess... | 0.00252 |
def gtd7(Input, flags, output):
'''The standard model subroutine (GTD7) always computes the
‘‘thermospheric’’ mass density by explicitly summing the masses of
the species in equilibrium at the thermospheric temperature T(z).
'''
mn3 = 5
zn3 = [32.5,20.0,15.0,10.0,0.0]
mn2 = 4
zn2 = [72.... | 0.034918 |
def get_payments(self):
"""Get all your payments.
Returns:
list of dicts: payments
For each payout in the list, a dict contains the following items:
* nmrAmount (`decimal.Decimal`)
* usdAmount (`decimal.Decimal`)
* tournament (`s... | 0.001929 |
def getStrikes(self, contract_identifier, smin=None, smax=None):
""" return strikes of contract / "multi" contract's contracts """
strikes = []
contracts = self.contractDetails(contract_identifier)["contracts"]
if contracts[0].m_secType not in ("FOP", "OPT"):
return []
... | 0.002257 |
def _get_xmlparser(xmlclass=XmlObject, validate=False, resolver=None):
"""Initialize an instance of :class:`lxml.etree.XMLParser` with appropriate
settings for validation. If validation is requested and the specified
instance of :class:`XmlObject` has an XSD_SCHEMA defined, that will be used.
Otherwise... | 0.002927 |
def get_between_times(self, t1, t2, target=None):
"""
Query for OPUS data between times t1 and t2.
Parameters
----------
t1, t2 : datetime.datetime, strings
Start and end time for the query. If type is datetime, will be
converted to isoformat string. If t... | 0.001669 |
def _state_error(self, reason):
"""
The connection attempt resulted in an error.
Attempt a reconnect with a back-off algorithm.
"""
log.err(reason)
def matchException(failure):
for errorState, backOff in self.backOffs.iteritems():
if 'errorTy... | 0.003484 |
def remove_data_flows_with_data_port_id(self, data_port_id):
"""Remove all data flows whose from_key or to_key equals the passed data_port_id
:param data_port_id: the id of a data_port of which all data_flows should be removed, the id can be a input or
output data port id
... | 0.007368 |
def process_response(self, request, response):
"""
Logs memory data after processing response.
"""
if self._is_enabled():
log_prefix = self._log_prefix(u"After", request)
new_memory_data = self._memory_data(log_prefix)
log_prefix = self._log_prefix(u"... | 0.008 |
def start(io_loop=None, check_time=2):
"""Begins watching source files for changes.
.. versionchanged:: 4.1
The ``io_loop`` argument is deprecated.
"""
io_loop = io_loop or asyncio.get_event_loop()
if io_loop in _io_loops:
return
_io_loops[io_loop] = True
if len(_io_loops) >... | 0.002817 |
def _parse(self):
"""read in a file and return a MOPFile object."""
with open(self.filename, 'r') as fobj:
lines = fobj.read().split('\n')
# Create a header object with content at start of file
self.header = MOPHeader(self.subfmt).parser(lines)
# Create a data attri... | 0.004739 |
def getCheck(self, checkid):
"""Returns a detailed description of a specified check."""
check = PingdomCheck(self, {'id': checkid})
check.getDetails()
return check | 0.010204 |
def _find_blocks(self, converted_table, worksheet, flags, units,
block_meta=None, start_pos=None, end_pos=None):
'''
A block is considered any region where we have the following structure:
text | text or number | ... | text of number
text | number | ... | nu... | 0.004034 |
def create_sample_input_files(template_filename,
database_filename,
config_filename):
"""Create sample template email and database."""
print("Creating sample template email {}".format(template_filename))
if os.path.exists(template_filename):
... | 0.000354 |
def _parse_rgn_segment(cls, fptr):
"""Parse the RGN segment.
Parameters
----------
fptr : file
Open file object.
Returns
-------
RGNSegment
The current RGN segment.
"""
offset = fptr.tell() - 2
read_buffer = fptr.... | 0.002778 |
def render_field(field, **kwargs):
"""
Render a field to a Bootstrap layout
"""
renderer_cls = get_field_renderer(**kwargs)
return renderer_cls(field, **kwargs).render() | 0.005291 |
def get_channel_access(channel=14, read_mode='non_volatile', **kwargs):
'''
:param kwargs:api_host='127.0.0.1' api_user='admin' api_pass='example' api_port=623
:param channel: number [1:7]
:param read_mode:
- non_volatile = get non-volatile Channel Access
- volatile = get present... | 0.002216 |
def getElementsByClassName(self, className, root='root'):
'''
getElementsByClassName - Searches and returns all elements containing a given class name.
@param className <str> - A one-word class name
@param root <AdvancedTag/'root'> - Search starting at... | 0.005562 |
def _stream_data_chunked(self, environ, block_size):
"""Get the data from a chunked transfer."""
# Chunked Transfer Coding
# http://www.servlets.com/rfcs/rfc2616-sec3.html#sec3.6.1
if "Darwin" in environ.get("HTTP_USER_AGENT", "") and environ.get(
"HTTP_X_EXPECTED_ENTITY_LEN... | 0.001189 |
def get_preference(self, pref_name):
""" Gets a single named preference
:returns: the value, typed to str/bool/int/float regarding its content.
"""
resp = self.request_single('GetPrefs', {'pref': {'name': pref_name}})
return utils.auto_type(resp['_content']) | 0.006689 |
async def _buffer_body(self, reader):
"""
Buffers the body of the request
"""
remaining = int(self.headers.get('Content-Length', 0))
if remaining > 0:
try:
self.data = await reader.readexactly(remaining)
except asyncio.IncompleteReadError:
... | 0.005682 |
def exception(self, event=None, *args, **kw):
"""
Process event and call :meth:`logging.Logger.error` with the result,
after setting ``exc_info`` to `True`.
"""
if not self._logger.isEnabledFor(logging.ERROR):
return
kw = self._add_base_info(kw)
kw['l... | 0.004695 |
def onpress(self, event):
"""
Reacts to key commands
:param event: a keyboard event
:return: if 'c' is pressed, clear all region patches
"""
if event.key == 'c': # clears all the contours
for patch in self.region_patches:
patch.remove()
... | 0.004219 |
def list(self, prefix='', delimiter='', filter_function=None, max_results=1, previous_key=''):
'''
a method to list keys in the google drive collection
:param prefix: string with prefix value to filter results
:param delimiter: string with value which results must not cont... | 0.007793 |
def _readSingleInstanceElement(self, instanceElement, makeGlyphs=True, makeKerning=True, makeInfo=True):
""" Read a single instance element.
If we have glyph specifications, only make those.
Otherwise make all available glyphs.
"""
# get the data from the instanceElement ... | 0.004191 |
def object_download(self, bucket, key, start_offset=0, byte_count=None):
"""Reads the contents of an object as text.
Args:
bucket: the name of the bucket containing the object.
key: the key of the object to be read.
start_offset: the start offset of bytes to read.
byte_count: the number... | 0.006024 |
def is_valid_index(self, code):
"""
returns: True | Flase , based on whether code is valid
"""
index_list = self.get_index_list()
return True if code.upper() in index_list else False | 0.009009 |
def clear_stale_pids(pids, pid_dir='/tmp', prefix='', multi=False):
'check for and remove any pids which have no corresponding process'
if isinstance(pids, (int, float, long)):
pids = [pids]
pids = str2list(pids, map_=unicode)
procs = map(unicode, os.listdir('/proc'))
running = [pid for pid ... | 0.000898 |
def get(self, subscription_id=None, stream=None, historics_id=None,
page=None, per_page=None, order_by=None, order_dir=None,
include_finished=None):
""" Show details of the Subscriptions belonging to this user.
Uses API documented at http://dev.datasift.com/docs/api/rest-api... | 0.003863 |
def from_axis_angle_and_translation(axis, angle, angle_in_radians=False,
translation_vec=(0, 0, 0)):
"""
Generates a SymmOp for a rotation about a given axis plus translation.
Args:
axis: The axis of rotation in cartesian space. For example,
... | 0.001794 |
def generate_jobs_pending_widget():
"""Generates a jobs_pending progress bar widget.
"""
pbar = widgets.IntProgress(
value=0,
min=0,
max=50,
description='',
orientation='horizontal', layout=widgets.Layout(max_width='180px'))
pbar.style.bar_color = '#71cddd'
p... | 0.000922 |
def get_uri(self):
"""
override DbApiHook get_uri method for get_sqlalchemy_engine()
"""
conn_config = self._get_conn_params()
uri = 'snowflake://{user}:{password}@{account}/{database}/'
uri += '{schema}?warehouse={warehouse}&role={role}'
return uri.format(**conn_... | 0.006116 |
def add(self, key, value):
# type: (Hashable, Any) -> None
"""
Adds a new value for the key.
:param key: the key for the value.
:param value: the value to add.
"""
dict.setdefault(self, key, []).append(value) | 0.011278 |
def sagemaker_timestamp():
"""Return a timestamp with millisecond precision."""
moment = time.time()
moment_ms = repr(moment).split('.')[1][:3]
return time.strftime("%Y-%m-%d-%H-%M-%S-{}".format(moment_ms), time.gmtime(moment)) | 0.00823 |
def _compress_url(link):
"""Convert a reddit URL into the short-hand used by usernotes.
Arguments:
link: a link to a comment, submission, or message (str)
Returns a String of the shorthand URL
"""
comment_re = re.compile(r'/comments/([A-Za-z\d]{2,})(?:/[^\s]+/([A-Za... | 0.003623 |
def blockstack_backup_restore(working_dir, block_number):
"""
Restore the database from a backup in the backups/ directory.
If block_number is None, then use the latest backup.
NOT THREAD SAFE
Return True on success
Raise an exception on error
"""
db = BlockstackDB.get_readwrite_instan... | 0.003745 |
def browse(package, homepage):
"""Browse to a package's PyPI or project homepage."""
p = Package(package)
try:
if homepage:
secho(u'Opening homepage for "{0}"...'.format(package), bold=True)
url = p.home_page
else:
secho(u'Opening PyPI page for "{0}"...'.f... | 0.002179 |
def parsehttpdate(string_):
"""
Parses an HTTP date into a datetime object.
>>> parsehttpdate('Thu, 01 Jan 1970 01:01:01 GMT')
datetime.datetime(1970, 1, 1, 1, 1, 1)
"""
try:
t = time.strptime(string_, "%a, %d %b %Y %H:%M:%S %Z")
except ValueError:
return None
re... | 0.002857 |
def get_repo_teams(repo_name, profile='github'):
'''
Return teams belonging to a repository.
.. versionadded:: 2017.7.0
repo_name
The name of the repository from which to retrieve teams.
profile
The name of the profile configuration to use. Defaults to ``github``.
CLI Example... | 0.001494 |
def dump(c, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the community object as dictionary.
:param c: Community to be dumped.
:type c: `invenio.modules.communities.models.Community`
:returns: Community serialized to dictionary.
:rtype: dict
"""
return dict(id=c.id,
... | 0.000987 |
def set_pixels(self, pixels):
"""
Set the image data.
Will not work if the new image has a different shape than the current image.
Parameters
----------
pixels : numpy.ndarray
New image data
Returns
-------
None
"""
if... | 0.007576 |
def pwm(host, seq, m1, m2, m3, m4):
"""
Sends control values directly to the engines, overriding control loops.
Parameters:
seq -- sequence number
m1 -- Integer: front left command
m2 -- Integer: front right command
m3 -- Integer: back right command
m4 -- Integer: back left command
... | 0.002732 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.