text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def wrap_flask_restful_resource(
fun: Callable, flask_restful_api: FlaskRestfulApi, injector: Injector
) -> Callable:
"""
This is needed because of how flask_restful views are registered originally.
:type flask_restful_api: :class:`flask_restful.Api`
"""
# The following fragment of code is copi... | 0.003848 |
def get_iso_packet_buffer_list(transfer_p):
"""
Python-specific helper extracting a list of iso packet buffers.
"""
transfer = transfer_p.contents
offset = 0
result = []
append = result.append
for iso_transfer in _get_iso_packet_list(transfer):
length = iso_transfer.length
... | 0.002375 |
def read_data(self, **kwargs):
"""
get the data from the service
:param kwargs: contain keyword args : trigger_id at least
:type kwargs: dict
:rtype: list
"""
now = arrow.utcnow().to(settings.TIME_ZONE)
my_toots = []
search = {}
... | 0.000803 |
def flush(self):
"""Flushes the current queue by by calling :func:`sender`'s :func:`send` method.
"""
local_sender = self.sender
if not local_sender:
return
while True:
# get at most send_buffer_size items and send them
data = []
wh... | 0.00519 |
def inline_query(self):
"""The query ``str`` for :tl:`KeyboardButtonSwitchInline` objects."""
if isinstance(self.button, types.KeyboardButtonSwitchInline):
return self.button.query | 0.009615 |
def posthoc_tukey_hsd(x, g, alpha=0.05):
'''Pairwise comparisons with TukeyHSD confidence intervals. This is a
convenience function to make statsmodels `pairwise_tukeyhsd` method more
applicable for further use.
Parameters
----------
x : array_like or pandas Series object, 1d
An array,... | 0.000527 |
def _parse_header_id(line):
"""
Pull the transcript or protein identifier from the header line
which starts with '>'
"""
if type(line) is not binary_type:
raise TypeError("Expected header line to be of type %s but got %s" % (
binary_type, type(line)))
if len(line) <= 1:
... | 0.001025 |
def enable_argscope_for_module(module, log_shape=True):
"""
Overwrite all functions of a given module to support argscope.
Note that this function monkey-patches the module and therefore could
have unexpected consequences.
It has been only tested to work well with ``tf.layers`` module.
Example:... | 0.001272 |
def create_hd_wallet(wallet_name, xpubkey, api_key, subchain_indices=[], coin_symbol='btc'):
'''
Create a new wallet from an extended pubkey (xpub... for BTC)
You can delete the wallet with the delete_wallet method below
'''
inferred_coin_symbol = coin_symbol_from_mkey(mkey=xpubkey)
if inferred... | 0.003472 |
def read(self, source_file, error_handling=ERROR_PASS):
"""
read(source_file, [error_handling])
This method parse subtitles contained in `source_file` and append them
to the current instance.
`source_file` -> Any iterable that yield unicode strings, like a file
open... | 0.003817 |
def on_timer(self, event):
'''Main Loop.'''
state = self.state
self.loopStartTime = time.time()
if state.close_event.wait(0.001):
self.timer.Stop()
self.Destroy()
return
# Check for resizing
self.checkReszie()
if self.r... | 0.008606 |
def json_encode(obj, serialize):
""" Handle encoding complex types. """
if hasattr(obj, 'to_dict'):
return obj.to_dict(serialize=serialize)
elif isinstance(obj, datetime):
return obj.date().isoformat()
elif isinstance(obj, date):
return obj.isoformat()
elif isinstance(obj, Pr... | 0.00207 |
def breadthdist(CIJ):
'''
The binary reachability matrix describes reachability between all pairs
of nodes. An entry (u,v)=1 means that there exists a path from node u
to node v; alternatively (u,v)=0.
The distance matrix contains lengths of shortest paths between all
pairs of nodes. An entry (... | 0.001033 |
def get_model(name):
"""
Convert a model's verbose name to the model class. This allows us to
use the models verbose name in steps.
"""
model = MODELS.get(name.lower(), None)
assert model, "Could not locate model by name '%s'" % name
return model | 0.00361 |
def show(self):
""" Display indented statistics. """
if not self._error and not self.stats:
return
self.header()
for stat in self.stats:
utils.item(stat, level=1, options=self.options) | 0.008333 |
def _at(self, idx):
"""Returns a view of the array sliced at `idx` in the first dim.
This is called through ``x[idx]``.
Parameters
----------
idx : int
index for slicing the `NDArray` in the first dim.
Returns
-------
NDArray
`NDA... | 0.00362 |
def depends_on(self, dependency):
"""
List of packages that depend on dependency
:param dependency: package name, e.g. 'vext' or 'Pillow'
"""
packages = self.package_info()
return [package for package in packages if dependency in package.get("requires", "")] | 0.009772 |
def _imread(self, file):
"""Proxy to skimage.io.imread with some fixes."""
# For now, we have to select the imageio plugin to read image from byte stream
# When ski-image v0.15 is released, imageio will be the default plugin, so this
# code can be simplified at that time. See issue repo... | 0.007802 |
def intersection(self, other):
""" Calculates the intersection of the two underlying bitarrays and returns
a new bloom filter object."""
if self.capacity != other.capacity or \
self.error_rate != other.error_rate:
raise ValueError("Intersecting filters requires both filte... | 0.00823 |
def get_app_name(self):
"""
Return the appname of the APK
This name is read from the AndroidManifest.xml
using the application android:label.
If no label exists, the android:label of the main activity is used.
If there is also no main activity label, an empty string is ... | 0.004218 |
def bfi(value, msb, lsb, field):
"""! @brief Change a bitfield value."""
mask = bitmask((msb, lsb))
value &= ~mask
value |= (field << lsb) & mask
return value | 0.005618 |
def add_host_to_dvs(host, username, password, vmknic_name, vmnic_name,
dvs_name, target_portgroup_name, uplink_portgroup_name,
protocol=None, port=None, host_names=None):
'''
Adds an ESXi host to a vSphere Distributed Virtual Switch and migrates
the desired adapters t... | 0.002208 |
def render_mail_template(subject_template, body_template, context):
"""
Renders both the subject and body templates in the given context.
Returns a tuple (subject, body) of the result.
"""
try:
subject = strip_spaces(render_to_string(subject_template, context))
body = render_to_strin... | 0.002519 |
def get_ip_prefixes_from_config(config, services, ip_version):
"""Build a set of IP prefixes found in service configuration files.
Arguments:
config (obg): A configparser object which holds our configuration.
services (list): A list of section names which are the name of the
service che... | 0.001484 |
def current_rev_reg_id(base_dir: str, cd_id: str) -> str:
"""
Return the current revocation registry identifier for
input credential definition identifier, in input directory.
Raise AbsentTails if no corresponding tails file, signifying no such revocation registry defined.
:par... | 0.008187 |
def custom_tokenizer(self) -> spacyTokenizer:
"""
Custom tokenizer
For future improvement, look at https://spacy.io/api/tokenizer, https://github.com/explosion/spaCy/issues/1494
"""
prefix_re = re.compile(r'''^[\[()\-.,@#$%^&*?|<~+_:;>!"']''')
infix_re = re.compile(r'''[\... | 0.01049 |
def crypto_config_from_cache(materials_provider, attribute_actions, table_info_cache, table_name):
"""Build a crypto config from the provided values, loading the table info from the provided cache.
:returns: crypto config and updated kwargs
:rtype: tuple(CryptoConfig, dict)
"""
table_info = table_i... | 0.007042 |
def run(self):
""" Thread loop. """
# construct WebCache object locally
thread_id, args, kwargs = self.execute_queue.get_nowait()
try:
cache_obj = WebCache(*args, **kwargs)
except Exception as e:
self.exception_queue[thread_id].put_nowait(e)
self.loop = False
self.execute_queue... | 0.013682 |
def close(
self):
"""close"""
self.debug_log('close - start')
self.shutdown()
logging.Handler.close(self)
self.debug_log('close - done') | 0.010638 |
def lifecycle(awsclient, env, tool, command, arguments):
"""Tool lifecycle which provides hooks into the different stages of the
command execution. See signals for hook details.
"""
log.debug('### init')
load_plugins()
context = get_context(awsclient, env, tool, command, arguments)
# every t... | 0.002164 |
def __on_close(self, ws):
"""Called when the websocket is closed"""
if self.status == "disconnected":
return # This can be double-called on disconnect
logging.debug("ConnectorDB:WS: Websocket closed")
# Turn off the ping timer
if self.pingtimer is not None:
... | 0.003643 |
def register_account():
"""
Agree to LE TOS
"""
LOGGER.info("Registering account...")
code, result = _send_signed_request(DEFAULT_CA + "/acme/new-reg", {
"resource": "new-reg",
"agreement": "https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf",
})
if code == 201... | 0.003527 |
def ray_shooting(self, theta_x, theta_y, kwargs_lens, k=None):
"""
ray-tracing (backwards light cone)
:param theta_x: angle in x-direction on the image
:param theta_y: angle in y-direction on the image
:param kwargs_lens:
:return: angles in the source plane
"""
... | 0.003297 |
def psd(self):
"""
A pyCBC FrequencySeries holding the appropriate PSD.
Return the PSD used in the metric calculation.
"""
if not self._psd:
errMsg = "The PSD has not been set in the metricParameters "
errMsg += "instance."
raise ValueError(err... | 0.005731 |
def hilbert_amplitude(ts):
"""Amplitude of the analytic signal, using the Hilbert transform"""
output = np.abs(signal.hilbert(signal.detrend(ts, axis=0), axis=0))
return Timeseries(output, ts.tspan, labels=ts.labels) | 0.004386 |
def simstate_encode(self, roll, pitch, yaw, xacc, yacc, zacc, xgyro, ygyro, zgyro, lat, lng):
'''
Status of simulation environment, if used
roll : Roll angle (rad) (float)
pitch : Pitch angle (rad) (float)
... | 0.006938 |
def iter_master_options(self, master_id=None):
'''
Iterate (in order) over your options for master
'''
masters = list(self._syndics.keys())
if self.opts['syndic_failover'] == 'random':
shuffle(masters)
if master_id not in self._syndics:
master_id =... | 0.00363 |
def url_is_from_any_domain(url, domains):
"""Return True if the url belongs to any of the given domains"""
host = parse_url(url).netloc.lower()
if host:
return any(((host == d.lower()) or (host.endswith('.%s' % d.lower())) for d in domains))
else:
return False | 0.006826 |
async def get_controller(self):
"""Return a Controller instance for the currently connected model.
:return Controller:
"""
from juju.controller import Controller
controller = Controller(jujudata=self._connector.jujudata)
kwargs = self.connection().connect_params()
... | 0.004808 |
def collstats(self, scale=1024, verbose=False):
"""
Run collection stats for collection.
see https://docs.mongodb.com/manual/reference/command/collStats/
:param scale: Scale at which to report sizes
:param verbose: used for extended report on legacy MMAPV1 storage engine
... | 0.005282 |
def add_ascii_block(self, block_length, data):
"""
add a block of ASCII BASIC source code lines.
>>> data = [
... 0xd,
... 0x31,0x30,0x20,0x50,0x52,0x49,0x4e,0x54,0x20,0x22,0x54,0x45,0x53,0x54,0x22,
... 0xd,
... 0x32,0x30,0x20,0x50,0x52,0x49,0x4e,0x54,0x20,0x22,0... | 0.006166 |
def thunkify(thread_name=None, daemon=True, default_func=None):
'''Make a function immediately return a function of no args which, when called,
waits for the result, which will start being processed in another thread.
Taken from https://wiki.python.org/moin/PythonDecoratorLibrary.
'''
def actual_dec... | 0.002924 |
def terminal_flicker_unix(code, field_width=3, space_width=3, height=1, clear=False, wait=0.05):
"""
Re-encodes a flicker code and prints it on a unix terminal.
:param code: Challenge value
:param field_width: Width of fields in characters (default: 3).
:param space_width: Width of spaces in charac... | 0.002941 |
def _get_value(self, entity):
"""Internal helper to get the value for this Property from an entity.
For a repeated Property this initializes the value to an empty
list if it is not set.
"""
if entity._projection:
if self._name not in entity._projection:
raise UnprojectedPropertyError(... | 0.004673 |
def getTransducer(self, chn):
"""
Returns the transducer of signal chn ("AgAgCl cup electrodes", etc.).
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
... | 0.003401 |
def set_uploaded(self, files_uploaded):
""" set_uploaded: records progress after uploading files
Args: files_uploaded ([str]): list of files that have been successfully uploaded
Returns: None
"""
self.files_uploaded = files_uploaded
self.__record_progress(Status.U... | 0.008982 |
def build_action(self, runnable, regime, action):
"""
Build event handler action code.
@param action: Event handler action object
@type action: lems.model.dynamics.Action
@return: Generated action code
@rtype: string
"""
if isinstance(action, StateAssig... | 0.00321 |
def erf(z):
"""Approximation to ERF.
:param z: Input array or scalar to perform erf on.
:type z: numpy.ndarray, float
:returns: The approximate error.
:rtype: numpy.ndarray, float
Note:
from:
http://www.cs.princeton.edu/introcs/21function/ErrorFunction.java.html
Implem... | 0.000631 |
def _mem(self):
"""Record Memory usage."""
value = int(psutil.virtual_memory().percent)
set_metric("memory", value, category=self.category)
gauge("memory", value) | 0.010309 |
def config(name, value):
'''
Set Traffic Server configuration variable values.
.. code-block:: yaml
proxy.config.proxy_name:
trafficserver.config:
- value: cdn.site.domain.tld
OR
traffic_server_setting:
trafficserver.config:
- name: pro... | 0.001242 |
def rotation_matrix_from_point(point, ret_inv=False):
"""Compute rotation matrix to go from [0,0,1] to `point`.
First, the matrix rotates to in the polar direction. Then,
a rotation about the y-axis is performed to match the
azimuthal angle in the x-z-plane.
This rotation matrix is required for th... | 0.000639 |
def _proxy_settings(self):
"""
Create/replace ~/.datacats/run/proxy-environment and return
entry for ro mount for containers
"""
if not ('https_proxy' in environ or 'HTTPS_PROXY' in environ
or 'http_proxy' in environ or 'HTTP_PROXY' in environ):
return... | 0.001247 |
def _try_convert_data(self, name, data, use_dtypes=True,
convert_dates=True):
""" try to parse a ndarray like into a column by inferring dtype """
# don't try to coerce, unless a force conversion
if use_dtypes:
if self.dtype is False:
return... | 0.003872 |
def qdii(self, min_volume=0):
"""以字典形式返回QDII数据
:param min_volume:最小交易量,单位万元
"""
# 添加当前的ctime
self.__qdii_url = self.__qdii_url.format(ctime=int(time.time()))
# 请求数据
rep = requests.get(self.__qdii_url)
# 获取返回的json字符串
fundjson = json.loads(rep.text)
... | 0.002809 |
def fromFile(self, fname):
"""Displays a spectrogram of an audio file. Supported formats see :func:`sparkle.tools.audiotools.audioread`
:param fname: file path of the audiofile to display
:type fname: str
:returns: float -- duration of audio recording (seconds)
"""
spec,... | 0.006742 |
def set_hostname(hostname):
'''
Set the hostname of the windows minion, requires a restart before this will
be updated.
.. versionadded:: 2016.3.0
Args:
hostname (str): The hostname to set
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. cod... | 0.001842 |
def wait(self):
"""
Starts all greenlets for concurrent processing.
Joins over all greenlets that are not servers.
"""
for greenlet in (self.greenlets + self.servers):
log.info("Starting {} greenlet...".format(greenlet))
greenlet.start()
gevent.jo... | 0.005865 |
def output(self, filename):
"""
Output the graph in filename
Args:
filename(string)
"""
if filename == '':
filename = 'contracts.dot'
if not filename.endswith('.dot'):
filename += ".dot"
info = 'Inheritance Graph: ' ... | 0.003623 |
def raw(self):
"""
Build query and passes to Elasticsearch, then returns the raw
format returned.
"""
qs = self.build_search()
es = self.get_es()
index = self.get_indexes()
doc_type = self.get_doctypes()
if doc_type and not index:
rai... | 0.002503 |
def fetch_import_f_restriction(self,):
"""Fetch whether importing a file is restricted
:returns: True, if import is restricted
:rtype: :class:`bool`
:raises: None
"""
inter = self.get_refobjinter()
restricted = self.status() is not None
return restricted ... | 0.007937 |
def vertical(x, ymin=0, ymax=1, color=None, width=None, dash=None, opacity=None):
"""Draws a vertical line from `ymin` to `ymax`.
Parameters
----------
xmin : int, optional
xmax : int, optional
color : str, optional
width : number, optional
Returns
-------
Chart
"""
li... | 0.004785 |
def register_handler(self, handler, event_name, args):
"""Registers an event handler.
One type of event can only have one event handler associated with it.
Args:
handler: The event handler function to be registered.
event_name: Name of the event the handler is for.
... | 0.001779 |
def notUnique(iterable, reportMax=INF):
"""Returns the elements in `iterable` that aren't unique; stops after it found
`reportMax` non-unique elements.
Examples:
>>> list(notUnique([1,1,2,2,3,3]))
[1, 2, 3]
>>> list(notUnique([1,1,2,2,3,3], 1))
[1]
"""
hash = {}
n=0
if repo... | 0.005 |
def rungtd1d(time: Union[datetime, str, np.ndarray],
altkm: np.ndarray,
glat: float, glon: float) -> xarray.Dataset:
"""
This is the "atomic" function looped by other functions
"""
time = todt64(time)
# %% get solar parameters for date
f107Ap = gi.getApF107(time, smooth... | 0.003521 |
def search(self, *conditions):
"""
Given a set of conditions, return all values that satisfy the
conditions for a given set of variables.
For example, suppose I wanted to find all of my friends who live in
Kansas:
.. code-block:: python
X = graph.v.X
... | 0.0008 |
def authenticate_ldap(self, username, password):
"""Get user by username and password and their permissions.
:param username: Username. String with a minimum 3 and maximum of 45 characters
:param password: User password. String with a minimum 3 and maximum of 45 characters
:return: Fol... | 0.005254 |
def _decode_addr_key(self, obj_dict):
"""
Callback function to handle the decoding of the 'Addr' field.
Serf msgpack 'Addr' as an IPv6 address, and the data needs to be unpack
using socket.inet_ntop().
See: https://github.com/KushalP/serfclient-py/issues/20
:param obj_... | 0.001618 |
def load_stock_quantity(self):
""" Loads quantities for all stocks """
info = StocksInfo(self.config)
for stock in self.model.stocks:
stock.quantity = info.load_stock_quantity(stock.symbol)
info.gc_book.close() | 0.007874 |
async def handleAll(self, deq: deque, limit=None) -> int:
"""
Handle all items in a deque. Can call asynchronous handlers.
:param deq: a deque of items to be handled by this router
:param limit: the number of items in the deque to the handled
:return: the number of items handled... | 0.003788 |
def albums(self, spotify_ids, market='US'):
"""Get a spotify album by its ID.
Parameters
----------
spotify_ids : List[str]
The spotify_ids to search by.
market : Optional[str]
An ISO 3166-1 alpha-2 country code.
"""
route = Route('GET', '... | 0.004167 |
def symmetrize_image(image):
"""
Use registration and reflection to make an image symmetric
ANTsR function: N/A
Arguments
---------
image : ANTsImage
image to make symmetric
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_r... | 0.003497 |
def add_special_arithmetic_methods(cls):
"""
Adds the full suite of special arithmetic methods (``__add__``,
``__sub__``, etc.) to the class.
Parameters
----------
cls : class
special methods will be defined and pinned to this class
"""
_, _, arith_method, comp_method, bool_meth... | 0.000514 |
def wait_for_providers(self):
""" Wait for any providers registered with the collector to have
unregistered.
Returns immediately if no providers were ever registered.
"""
if self._providers_registered:
_log.debug('waiting for providers to unregister %s', self)
... | 0.004684 |
def cal_dist_between_2_coord_frame_aligned_boxes(box1_pos, box1_size, box2_pos, box2_size):
""" Calculate Euclidean distance between two boxes those edges are parallel to the coordinate axis
The function decides condition based which corner to corner or edge to edge distance needs to be calculated.
:param... | 0.008215 |
def _endCodeIfNeeded(line, inCodeBlock):
"""Simple routine to append end code marker if needed."""
assert isinstance(line, str)
if inCodeBlock:
line = '# @endcode{0}{1}'.format(linesep, line.rstrip())
inCodeBlock = False
return line, inCodeBlock | 0.006645 |
def export_analytics_data_to_excel(data, output_file_name, result_info_key, identifier_keys):
"""Creates an Excel file containing data returned by the Analytics API
Args:
data: Analytics API data as a list of dicts
output_file_name: File name for output Excel file (use .xlsx extension).
""... | 0.006061 |
def calculate_weighted_avg(bonds):
"""
Returns the weighted average bond length given by
Hoppe's effective coordination number formula.
Args:
bonds (list): list of floats that are the
bond distances between a cation and its
peripheral ions
"""
minimum_bond = min(bonds)
... | 0.001825 |
def extract_wav(datafile, target=None):
""" Get LPCM 16bit audio stream from mediafile.
If `target` is a directory, create a .wav with the same basename as the input.
If target is empty, write to the directory of the source file. Otherwise, use it
directly as the target filename.
"... | 0.010965 |
def get_params(self, deep=False):
"""
returns a dict of all of the object's user-facing parameters
Parameters
----------
deep : boolean, default: False
when True, also gets non-user-facing paramters
Returns
-------
dict
"""
at... | 0.013413 |
def get_modis_tile_list(ds):
"""Helper function to identify MODIS tiles that intersect input geometry
modis_gird.py contains dictionary of tile boundaries (tile name and WKT polygon ring from bbox)
See: https://modis-land.gsfc.nasa.gov/MODLAND_grid.html
"""
from demcoreg import modis_grid
modi... | 0.003817 |
def exterior_almost_equals(self, other, max_distance=1e-6, points_per_edge=8):
"""
Estimate if this and other polygon's exterior are almost identical.
The two exteriors can have different numbers of points, but any point
randomly sampled on the exterior of one polygon should be close to... | 0.001243 |
def list_group_users(self, group_id, depth=1):
"""
Retrieves a list of all users that are members of a particular group.
:param group_id: The unique ID of the group.
:type group_id: ``str``
:param depth: The depth of the response data.
:type depth:... | 0.004193 |
def undecorate(cls, function):
'''
Remove validator decoration from a function.
The `function` argument is the function to be cleaned from
the validator decorator.
'''
if cls.is_function_validated(function):
return cls.get_function_validator(function).functi... | 0.005764 |
def get_variable_for_feature(self, feature_key, variable_key):
""" Get the variable with the given variable key for the given feature.
Args:
feature_key: The key of the feature for which we are getting the variable.
variable_key: The key of the variable we are getting.
Returns:
Variable ... | 0.010596 |
def delete(self, *args, **kwargs):
"""
Executes an HTTP DELETE.
:Parameters:
- `args`: Non-keyword arguments
- `kwargs`: Keyword arguments
"""
return self.session.delete(*args, **self.get_kwargs(**kwargs)) | 0.007463 |
def write_packages(self, diagram):
"""write a package diagram"""
# sorted to get predictable (hence testable) results
for i, obj in enumerate(sorted(diagram.modules(), key=lambda x: x.title)):
self.printer.emit_node(i, label=self.get_title(obj), shape="box")
obj.fig_id = ... | 0.005576 |
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the Credential struct to a stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStream
... | 0.001352 |
def search_alert_for_facet(self, facet, **kwargs): # noqa: E501
"""Lists the values of a specific facet over the customer's non-deleted alerts # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_r... | 0.001959 |
def inferred_var_seqs_plus_flanks(self, ref_seq, flank_length):
'''Returns start position of first flank sequence, plus a list of sequences -
the REF, plus one for each ALT.sequence. Order same as in ALT column'''
flank_start = max(0, self.POS - flank_length)
flank_end = min(len(ref_seq)... | 0.0078 |
def xslt_transformation(xml, template):
"""
Transform `xml` using XSLT `template`.
Args:
xml (str): Filename or XML string. Don't use ``\\n`` in case of
filename.
template (str): Filename or XML string. Don't use ``\\n`` in case of
filename.
R... | 0.001751 |
def __init(self):
"""loads the property data into the class"""
if self._portalId is None:
from .administration import Administration
portalSelf = Administration(url=self._securityHandler.org_url,
securityHandler=self._securityHandler,
... | 0.010772 |
def create(request):
"""
Handles post from the "Add room" form on the homepage, and
redirects to the new room.
"""
name = request.POST.get("name")
if name:
room, created = ChatRoom.objects.get_or_create(name=name)
return redirect(room)
return redirect(rooms) | 0.003311 |
def encode(encoding, data):
"""
Encodes the given data using the encoding that is specified
:param str encoding: encoding to use, should be one of the supported encoding
:param data: data to encode
:type data: str or bytes
:return: multibase encoded data
:rtype: bytes
:raises ValueError... | 0.004992 |
def get_function_definition_from_below_last_line(self):
"""Get func def when the cursor is located below the last def line."""
cursor = self.code_editor.textCursor()
func_text = ''
is_first_line = True
line_number = cursor.blockNumber() + 1
number_of_lines_of_functi... | 0.001735 |
def close(self):
"""Close the file."""
# ignore closing a closed file
if not self._is_open():
return
# for raw io, all writes are flushed immediately
if self.allow_update and not self.raw_io:
self.flush()
if self._filesystem.is_windows_fs and ... | 0.003044 |
def summarize_variables(variables=None):
"""Logs a summary of variable information.
This function groups Variables by dtype and prints out the number of Variables
and the total number of scalar values for each datatype, as well as the total
memory consumed.
For Variables of type tf.string, the memory usage ... | 0.005442 |
def complete_opt_display(self, text, *_):
""" Autocomplete for display option """
return [t + " " for t in DISPLAYS if t.startswith(text)] | 0.012987 |
def _read_csv_table(path):
"""Lee un CSV a una lista de diccionarios."""
with open(path, 'rb') as csvfile:
reader = csv.DictReader(csvfile)
table = list(reader)
return table | 0.004975 |
async def download(self, files: Sequence[Union[str, Path]],
dest: Union[str, Path] = '.',
show_progress: bool = False):
'''
Downloads the given list of files from the compute session.
:param files: The list of file paths in the compute session.
... | 0.001581 |
def get_topology_info(*args):
"""Synced API call to get topology information"""
instance = tornado.ioloop.IOLoop.instance()
try:
return instance.run_sync(lambda: API.get_topology_info(*args))
except Exception:
Log.debug(traceback.format_exc())
raise | 0.018587 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.