_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q275400 | reorder_resolved_levels | test | def reorder_resolved_levels(storage, debug):
"""L1 and L2 rules"""
# Applies L1.
should_reset = True
chars = storage['chars']
for _ch in chars[::-1]:
# L1. On each line, reset the embedding level of the following
# characters to the paragraph embedding level:
if _ch['orig'] in ('B', 'S'):
# 1. Segment separators,
# 2. Paragraph separators,
_ch['level'] = storage['base_level']
should_reset = True
elif should_reset and _ch['orig'] in ('BN', 'WS'):
# 3. Any sequence of whitespace characters preceding a segment
# separator or paragraph separator
# 4. Any sequence of white space characters at the end of the
# line.
_ch['level'] = storage['base_level']
else:
should_reset = False
max_len = len(chars)
# L2 should be per line
# Calculates highest level and loweset odd level on the fly.
line_start = line_end = 0
highest_level = 0
lowest_odd_level = EXPLICIT_LEVEL_LIMIT
for idx in range(max_len):
_ch = chars[idx]
# calc the levels
char_level = _ch['level']
if char_level > highest_level:
highest_level = char_level
if char_level % 2 and char_level < lowest_odd_level:
lowest_odd_level = char_level
if _ch['orig'] == 'B' or idx == max_len - 1:
line_end = idx
# omit line breaks
if _ch['orig'] == 'B':
line_end -= 1
reverse_contiguous_sequence(chars, line_start, line_end,
highest_level, lowest_odd_level)
# reset for next line run
line_start = idx+1
highest_level = 0
lowest_odd_level = EXPLICIT_LEVEL_LIMIT
if debug:
debug_storage(storage) | python | {
"resource": ""
} |
q275401 | CollectMayaCurrentFile.process | test | def process(self, context):
import os
from maya import cmds
"""Inject the current working file"""
current_file = cmds.file(sceneName=True, query=True)
# Maya returns forward-slashes by default
normalised = os.path.normpath(current_file)
context.set_data('currentFile', value=normalised)
# For backwards compatibility
context.set_data('current_file', value=normalised) | python | {
"resource": ""
} |
q275402 | convert | test | def convert(lines):
"""Convert compiled .ui file from PySide2 to Qt.py
Arguments:
lines (list): Each line of of .ui file
Usage:
>> with open("myui.py") as f:
.. lines = convert(f.readlines())
"""
def parse(line):
line = line.replace("from PySide2 import", "from Qt import")
line = line.replace("QtWidgets.QApplication.translate",
"Qt.QtCompat.translate")
return line
parsed = list()
for line in lines:
line = parse(line)
parsed.append(line)
return parsed | python | {
"resource": ""
} |
q275403 | _add | test | def _add(object, name, value):
"""Append to self, accessible via Qt.QtCompat"""
self.__added__.append(name)
setattr(object, name, value) | python | {
"resource": ""
} |
q275404 | cli | test | def cli(args):
"""Qt.py command-line interface"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--convert",
help="Path to compiled Python module, e.g. my_ui.py")
parser.add_argument("--compile",
help="Accept raw .ui file and compile with native "
"PySide2 compiler.")
parser.add_argument("--stdout",
help="Write to stdout instead of file",
action="store_true")
parser.add_argument("--stdin",
help="Read from stdin instead of file",
action="store_true")
args = parser.parse_args(args)
if args.stdout:
raise NotImplementedError("--stdout")
if args.stdin:
raise NotImplementedError("--stdin")
if args.compile:
raise NotImplementedError("--compile")
if args.convert:
sys.stdout.write("#\n"
"# WARNING: --convert is an ALPHA feature.\n#\n"
"# See https://github.com/mottosso/Qt.py/pull/132\n"
"# for details.\n"
"#\n")
#
# ------> Read
#
with open(args.convert) as f:
lines = convert(f.readlines())
backup = "%s_backup%s" % os.path.splitext(args.convert)
sys.stdout.write("Creating \"%s\"..\n" % backup)
shutil.copy(args.convert, backup)
#
# <------ Write
#
with open(args.convert, "w") as f:
f.write("".join(lines))
sys.stdout.write("Successfully converted \"%s\"\n" % args.convert) | python | {
"resource": ""
} |
q275405 | _maintain_backwards_compatibility | test | def _maintain_backwards_compatibility(binding):
"""Add members found in prior versions up till the next major release
These members are to be considered deprecated. When a new major
release is made, these members are removed.
"""
for member in ("__binding__",
"__binding_version__",
"__qt_version__",
"__added__",
"__remapped__",
"__modified__",
"convert",
"load_ui",
"translate"):
setattr(binding, member, getattr(self, member))
self.__added__.append(member)
setattr(binding, "__wrapper_version__", self.__version__)
self.__added__.append("__wrapper_version__") | python | {
"resource": ""
} |
q275406 | show | test | def show():
"""Try showing the most desirable GUI
This function cycles through the currently registered
graphical user interfaces, if any, and presents it to
the user.
"""
parent = next(
o for o in QtWidgets.QApplication.instance().topLevelWidgets()
if o.objectName() == "MayaWindow"
)
gui = _discover_gui()
if gui is None:
_show_no_gui()
else:
return gui(parent) | python | {
"resource": ""
} |
q275407 | _discover_gui | test | def _discover_gui():
"""Return the most desirable of the currently registered GUIs"""
# Prefer last registered
guis = reversed(pyblish.api.registered_guis())
for gui in guis:
try:
gui = __import__(gui).show
except (ImportError, AttributeError):
continue
else:
return gui | python | {
"resource": ""
} |
q275408 | deregister_host | test | def deregister_host():
"""Register supported hosts"""
pyblish.api.deregister_host("mayabatch")
pyblish.api.deregister_host("mayapy")
pyblish.api.deregister_host("maya") | python | {
"resource": ""
} |
q275409 | add_to_filemenu | test | def add_to_filemenu():
"""Add Pyblish to file-menu
.. note:: We're going a bit hacky here, probably due to my lack
of understanding for `evalDeferred` or `executeDeferred`,
so if you can think of a better solution, feel free to edit.
"""
if hasattr(cmds, 'about') and not cmds.about(batch=True):
# As Maya builds its menus dynamically upon being accessed,
# we force its build here prior to adding our entry using it's
# native mel function call.
mel.eval("evalDeferred buildFileMenu")
# Serialise function into string
script = inspect.getsource(_add_to_filemenu)
script += "\n_add_to_filemenu()"
# If cmds doesn't have any members, we're most likely in an
# uninitialized batch-mode. It it does exists, ensure we
# really aren't in batch mode.
cmds.evalDeferred(script) | python | {
"resource": ""
} |
q275410 | maintained_selection | test | def maintained_selection():
"""Maintain selection during context
Example:
>>> with maintained_selection():
... # Modify selection
... cmds.select('node', replace=True)
>>> # Selection restored
"""
previous_selection = cmds.ls(selection=True)
try:
yield
finally:
if previous_selection:
cmds.select(previous_selection,
replace=True,
noExpand=True)
else:
cmds.select(deselect=True,
noExpand=True) | python | {
"resource": ""
} |
q275411 | maintained_time | test | def maintained_time():
"""Maintain current time during context
Example:
>>> with maintained_time():
... cmds.playblast()
>>> # Time restored
"""
ct = cmds.currentTime(query=True)
try:
yield
finally:
cmds.currentTime(ct, edit=True) | python | {
"resource": ""
} |
q275412 | _show_no_gui | test | def _show_no_gui():
"""Popup with information about how to register a new GUI
In the event of no GUI being registered or available,
this information dialog will appear to guide the user
through how to get set up with one.
"""
messagebox = QtWidgets.QMessageBox()
messagebox.setIcon(messagebox.Warning)
messagebox.setWindowIcon(QtGui.QIcon(os.path.join(
os.path.dirname(pyblish.__file__),
"icons",
"logo-32x32.svg"))
)
spacer = QtWidgets.QWidget()
spacer.setMinimumSize(400, 0)
spacer.setSizePolicy(QtWidgets.QSizePolicy.Minimum,
QtWidgets.QSizePolicy.Expanding)
layout = messagebox.layout()
layout.addWidget(spacer, layout.rowCount(), 0, 1, layout.columnCount())
messagebox.setWindowTitle("Uh oh")
text = "No registered GUI found.\n\n"
if not pyblish.api.registered_guis():
text += (
"In order to show you a GUI, one must first be registered. "
"\n"
"Pyblish supports one or more graphical user interfaces "
"to be registered at once, the next acting as a fallback to "
"the previous."
"\n"
"\n"
"For example, to use Pyblish Lite, first install it:"
"\n"
"\n"
"$ pip install pyblish-lite"
"\n"
"\n"
"Then register it, like so:"
"\n"
"\n"
">>> import pyblish.api\n"
">>> pyblish.api.register_gui(\"pyblish_lite\")"
"\n"
"\n"
"The next time you try running this, Lite will appear."
"\n"
"See http://api.pyblish.com/register_gui.html for "
"more information."
)
else:
text += (
"None of the registered graphical user interfaces "
"could be found."
"\n"
"These interfaces are currently registered:"
"\n"
"%s" % "\n".join(pyblish.api.registered_guis())
)
messagebox.setText(text)
messagebox.setStandardButtons(messagebox.Ok)
messagebox.exec_() | python | {
"resource": ""
} |
q275413 | Field.setup_types | test | def setup_types(self):
"""
The Message object has a circular reference on itself, thus we have to allow
Type referencing by name. Here we lookup any Types referenced by name and
replace with the real class.
"""
def load(t):
from TelegramBotAPI.types.type import Type
if isinstance(t, str):
return Type._type(t)
assert issubclass(t, Type)
return t
self.types = [load(t) for t in self.types] | python | {
"resource": ""
} |
q275414 | Line.get_cumulative_data | test | def get_cumulative_data(self):
"""Get the data as it will be charted. The first set will be
the actual first data set. The second will be the sum of the
first and the second, etc."""
sets = map(itemgetter('data'), self.data)
if not sets:
return
sum = sets.pop(0)
yield sum
while sets:
sum = map(add, sets.pop(0))
yield sum | python | {
"resource": ""
} |
q275415 | Plot.get_single_axis_values | test | def get_single_axis_values(self, axis, dataset):
"""
Return all the values for a single axis of the data.
"""
data_index = getattr(self, '%s_data_index' % axis)
return [p[data_index] for p in dataset['data']] | python | {
"resource": ""
} |
q275416 | Plot.__draw_constant_line | test | def __draw_constant_line(self, value_label_style):
"Draw a constant line on the y-axis with the label"
value, label, style = value_label_style
start = self.transform_output_coordinates((0, value))[1]
stop = self.graph_width
path = etree.SubElement(self.graph, 'path', {
'd': 'M 0 %(start)s h%(stop)s' % locals(),
'class': 'constantLine'})
if style:
path.set('style', style)
text = etree.SubElement(self.graph, 'text', {
'x': str(2),
'y': str(start - 2),
'class': 'constantLine'})
text.text = label | python | {
"resource": ""
} |
q275417 | Plot.load_transform_parameters | test | def load_transform_parameters(self):
"Cache the parameters necessary to transform x & y coordinates"
x_min, x_max, x_div = self.x_range()
y_min, y_max, y_div = self.y_range()
x_step = (float(self.graph_width) - self.font_size * 2) / \
(x_max - x_min)
y_step = (float(self.graph_height) - self.font_size * 2) / \
(y_max - y_min)
self.__transform_parameters = dict(locals())
del self.__transform_parameters['self'] | python | {
"resource": ""
} |
q275418 | reverse_mapping | test | def reverse_mapping(mapping):
"""
For every key, value pair, return the mapping for the
equivalent value, key pair
>>> reverse_mapping({'a': 'b'}) == {'b': 'a'}
True
"""
keys, values = zip(*mapping.items())
return dict(zip(values, keys)) | python | {
"resource": ""
} |
q275419 | float_range | test | def float_range(start=0, stop=None, step=1):
"""
Much like the built-in function range, but accepts floats
>>> tuple(float_range(0, 9, 1.5))
(0.0, 1.5, 3.0, 4.5, 6.0, 7.5)
"""
start = float(start)
while start < stop:
yield start
start += step | python | {
"resource": ""
} |
q275420 | Pie.add_data | test | def add_data(self, data_descriptor):
"""
Add a data set to the graph
>>> graph.add_data({data:[1,2,3,4]}) # doctest: +SKIP
Note that a 'title' key is ignored.
Multiple calls to add_data will sum the elements, and the pie will
display the aggregated data. e.g.
>>> graph.add_data({data:[1,2,3,4]}) # doctest: +SKIP
>>> graph.add_data({data:[2,3,5,7]}) # doctest: +SKIP
is the same as:
>>> graph.add_data({data:[3,5,8,11]}) # doctest: +SKIP
If data is added of with differing lengths, the corresponding
values will be assumed to be zero.
>>> graph.add_data({data:[1,2,3,4]}) # doctest: +SKIP
>>> graph.add_data({data:[5,7]}) # doctest: +SKIP
is the same as:
>>> graph.add_data({data:[5,7]}) # doctest: +SKIP
>>> graph.add_data({data:[1,2,3,4]}) # doctest: +SKIP
and
>>> graph.add_data({data:[6,9,3,4]}) # doctest: +SKIP
"""
pairs = itertools.zip_longest(self.data, data_descriptor['data'])
self.data = list(itertools.starmap(robust_add, pairs)) | python | {
"resource": ""
} |
q275421 | Pie.add_defs | test | def add_defs(self, defs):
"Add svg definitions"
etree.SubElement(
defs,
'filter',
id='dropshadow',
width='1.2',
height='1.2',
)
etree.SubElement(
defs,
'feGaussianBlur',
stdDeviation='4',
result='blur',
) | python | {
"resource": ""
} |
q275422 | Graph.add_data | test | def add_data(self, conf):
"""
Add data to the graph object. May be called several times to add
additional data sets.
conf should be a dictionary including 'data' and 'title' keys
"""
self.validate_data(conf)
self.process_data(conf)
self.data.append(conf) | python | {
"resource": ""
} |
q275423 | Graph.burn | test | def burn(self):
"""
Process the template with the data and
config which has been set and return the resulting SVG.
Raises ValueError when no data set has
been added to the graph object.
"""
if not self.data:
raise ValueError("No data available")
if hasattr(self, 'calculations'):
self.calculations()
self.start_svg()
self.calculate_graph_dimensions()
self.foreground = etree.Element("g")
self.draw_graph()
self.draw_titles()
self.draw_legend()
self.draw_data()
self.graph.append(self.foreground)
self.render_inline_styles()
return self.render(self.root) | python | {
"resource": ""
} |
q275424 | Graph.calculate_left_margin | test | def calculate_left_margin(self):
"""
Calculates the margin to the left of the plot area, setting
border_left.
"""
bl = 7
# Check for Y labels
if self.rotate_y_labels:
max_y_label_height_px = self.y_label_font_size
else:
label_lengths = map(len, self.get_y_labels())
max_y_label_len = max(label_lengths)
max_y_label_height_px = 0.6 * max_y_label_len * self.y_label_font_size
if self.show_y_labels:
bl += max_y_label_height_px
if self.stagger_y_labels:
bl += max_y_label_height_px + 10
if self.show_y_title:
bl += self.y_title_font_size + 5
self.border_left = bl | python | {
"resource": ""
} |
q275425 | Graph.calculate_right_margin | test | def calculate_right_margin(self):
"""
Calculate the margin in pixels to the right of the plot area,
setting border_right.
"""
br = 7
if self.key and self.key_position == 'right':
max_key_len = max(map(len, self.keys()))
br += max_key_len * self.key_font_size * 0.6
br += self.KEY_BOX_SIZE
br += 10 # Some padding around the box
self.border_right = br | python | {
"resource": ""
} |
q275426 | Graph.calculate_top_margin | test | def calculate_top_margin(self):
"""
Calculate the margin in pixels above the plot area, setting
border_top.
"""
self.border_top = 5
if self.show_graph_title:
self.border_top += self.title_font_size
self.border_top += 5
if self.show_graph_subtitle:
self.border_top += self.subtitle_font_size | python | {
"resource": ""
} |
q275427 | Graph.add_popup | test | def add_popup(self, x, y, label):
"""
Add pop-up information to a point on the graph.
"""
txt_width = len(label) * self.font_size * 0.6 + 10
tx = x + [5, -5][int(x + txt_width > self.width)]
anchor = ['start', 'end'][x + txt_width > self.width]
style = 'fill: #000; text-anchor: %s;' % anchor
id = 'label-%s' % self._w3c_name(label)
attrs = {
'x': str(tx),
'y': str(y - self.font_size),
'visibility': 'hidden',
'style': style,
'text': label,
'id': id,
}
etree.SubElement(self.foreground, 'text', attrs)
# add the circle element to the foreground
vis_tmpl = (
"document.getElementById('{id}').setAttribute('visibility', {val})"
)
attrs = {
'cx': str(x),
'cy': str(y),
'r': str(10),
'style': 'opacity: 0;',
'onmouseover': vis_tmpl.format(val='visible', id=id),
'onmouseout': vis_tmpl.format(val='hidden', id=id),
}
etree.SubElement(self.foreground, 'circle', attrs) | python | {
"resource": ""
} |
q275428 | Graph.calculate_bottom_margin | test | def calculate_bottom_margin(self):
"""
Calculate the margin in pixels below the plot area, setting
border_bottom.
"""
bb = 7
if self.key and self.key_position == 'bottom':
bb += len(self.data) * (self.font_size + 5)
bb += 10
if self.show_x_labels:
max_x_label_height_px = self.x_label_font_size
if self.rotate_x_labels:
label_lengths = map(len, self.get_x_labels())
max_x_label_len = functools.reduce(max, label_lengths)
max_x_label_height_px *= 0.6 * max_x_label_len
bb += max_x_label_height_px
if self.stagger_x_labels:
bb += max_x_label_height_px + 10
if self.show_x_title:
bb += self.x_title_font_size + 5
self.border_bottom = bb | python | {
"resource": ""
} |
q275429 | Graph.draw_graph | test | def draw_graph(self):
"""
The central logic for drawing the graph.
Sets self.graph (the 'g' element in the SVG root)
"""
transform = 'translate (%s %s)' % (self.border_left, self.border_top)
self.graph = etree.SubElement(self.root, 'g', transform=transform)
etree.SubElement(self.graph, 'rect', {
'x': '0',
'y': '0',
'width': str(self.graph_width),
'height': str(self.graph_height),
'class': 'graphBackground'
})
# Axis
etree.SubElement(self.graph, 'path', {
'd': 'M 0 0 v%s' % self.graph_height,
'class': 'axis',
'id': 'xAxis'
})
etree.SubElement(self.graph, 'path', {
'd': 'M 0 %s h%s' % (self.graph_height, self.graph_width),
'class': 'axis',
'id': 'yAxis'
})
self.draw_x_labels()
self.draw_y_labels() | python | {
"resource": ""
} |
q275430 | Graph.make_datapoint_text | test | def make_datapoint_text(self, x, y, value, style=None):
"""
Add text for a datapoint
"""
if not self.show_data_values:
# do nothing
return
# first lay down the text in a wide white stroke to
# differentiate it from the background
e = etree.SubElement(self.foreground, 'text', {
'x': str(x),
'y': str(y),
'class': 'dataPointLabel',
'style': '%(style)s stroke: #fff; stroke-width: 2;' % vars(),
})
e.text = str(value)
# then lay down the text in the specified style
e = etree.SubElement(self.foreground, 'text', {
'x': str(x),
'y': str(y),
'class': 'dataPointLabel'})
e.text = str(value)
if style:
e.set('style', style) | python | {
"resource": ""
} |
q275431 | Graph.draw_x_labels | test | def draw_x_labels(self):
"Draw the X axis labels"
if self.show_x_labels:
labels = self.get_x_labels()
count = len(labels)
labels = enumerate(iter(labels))
start = int(not self.step_include_first_x_label)
labels = itertools.islice(labels, start, None, self.step_x_labels)
list(map(self.draw_x_label, labels))
self.draw_x_guidelines(self.field_width(), count) | python | {
"resource": ""
} |
q275432 | Graph.draw_y_labels | test | def draw_y_labels(self):
"Draw the Y axis labels"
if not self.show_y_labels:
# do nothing
return
labels = self.get_y_labels()
count = len(labels)
labels = enumerate(iter(labels))
start = int(not self.step_include_first_y_label)
labels = itertools.islice(labels, start, None, self.step_y_labels)
list(map(self.draw_y_label, labels))
self.draw_y_guidelines(self.field_height(), count) | python | {
"resource": ""
} |
q275433 | Graph.draw_x_guidelines | test | def draw_x_guidelines(self, label_height, count):
"Draw the X-axis guidelines"
if not self.show_x_guidelines:
return
# skip the first one
for count in range(1, count):
move = 'M {start} 0 v{stop}'.format(
start=label_height * count,
stop=self.graph_height,
)
path = {'d': move, 'class': 'guideLines'}
etree.SubElement(self.graph, 'path', path) | python | {
"resource": ""
} |
q275434 | Graph.draw_y_guidelines | test | def draw_y_guidelines(self, label_height, count):
"Draw the Y-axis guidelines"
if not self.show_y_guidelines:
return
for count in range(1, count):
move = 'M 0 {start} h{stop}'.format(
start=self.graph_height - label_height * count,
stop=self.graph_width,
)
path = {'d': move, 'class': 'guideLines'}
etree.SubElement(self.graph, 'path', path) | python | {
"resource": ""
} |
q275435 | Graph.draw_titles | test | def draw_titles(self):
"Draws the graph title and subtitle"
if self.show_graph_title:
self.draw_graph_title()
if self.show_graph_subtitle:
self.draw_graph_subtitle()
if self.show_x_title:
self.draw_x_title()
if self.show_y_title:
self.draw_y_title() | python | {
"resource": ""
} |
q275436 | Graph.render_inline_styles | test | def render_inline_styles(self):
"Hard-code the styles into the SVG XML if style sheets are not used."
if not self.css_inline:
# do nothing
return
styles = self.parse_css()
for node in self.root.xpath('//*[@class]'):
cl = '.' + node.attrib['class']
if cl not in styles:
continue
style = styles[cl]
if 'style' in node.attrib:
style += node.attrib['style']
node.attrib['style'] = style | python | {
"resource": ""
} |
q275437 | Graph.start_svg | test | def start_svg(self):
"Base SVG Document Creation"
SVG_NAMESPACE = 'http://www.w3.org/2000/svg'
SVG = '{%s}' % SVG_NAMESPACE
NSMAP = {
None: SVG_NAMESPACE,
'xlink': 'http://www.w3.org/1999/xlink',
'a3': 'http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/',
}
root_attrs = self._get_root_attributes()
self.root = etree.Element(SVG + "svg", attrib=root_attrs, nsmap=NSMAP)
if hasattr(self, 'style_sheet_href'):
pi = etree.ProcessingInstruction(
'xml-stylesheet',
'href="%s" type="text/css"' % self.style_sheet_href
)
self.root.addprevious(pi)
comment_strings = (
' Created with SVG.Graph ',
' SVG.Graph by Jason R. Coombs ',
' Based on SVG::Graph by Sean E. Russel ',
' Based on Perl SVG:TT:Graph by Leo Lapworth & Stephan Morgan ',
' ' + '/' * 66,
)
list(map(self.root.append, map(etree.Comment, comment_strings)))
defs = etree.SubElement(self.root, 'defs')
self.add_defs(defs)
if not hasattr(self, 'style_sheet_href') and not self.css_inline:
self.root.append(etree.Comment(
' include default stylesheet if none specified '))
style = etree.SubElement(defs, 'style', type='text/css')
# TODO: the text was previously escaped in a CDATA declaration... how
# to do that with etree?
style.text = self.get_stylesheet().cssText
self.root.append(etree.Comment('SVG Background'))
etree.SubElement(self.root, 'rect', {
'width': str(self.width),
'height': str(self.height),
'x': '0',
'y': '0',
'class': 'svgBackground'}) | python | {
"resource": ""
} |
q275438 | Graph.get_stylesheet_resources | test | def get_stylesheet_resources(self):
"Get the stylesheets for this instance"
# allow css to include class variables
class_vars = class_dict(self)
loader = functools.partial(
self.load_resource_stylesheet,
subs=class_vars)
sheets = list(map(loader, self.stylesheet_names))
return sheets | python | {
"resource": ""
} |
q275439 | run_bot | test | def run_bot(bot_class, host, port, nick, channels=None, ssl=None):
"""\
Convenience function to start a bot on the given network, optionally joining
some channels
"""
conn = IRCConnection(host, port, nick, ssl)
bot_instance = bot_class(conn)
while 1:
if not conn.connect():
break
channels = channels or []
for channel in channels:
conn.join(channel)
conn.enter_event_loop() | python | {
"resource": ""
} |
q275440 | IRCConnection.send | test | def send(self, data, force=False):
"""\
Send raw data over the wire if connection is registered. Otherewise,
save the data to an output buffer for transmission later on.
If the force flag is true, always send data, regardless of
registration status.
"""
if self._registered or force:
self._sock_file.write('%s\r\n' % data)
self._sock_file.flush()
else:
self._out_buffer.append(data) | python | {
"resource": ""
} |
q275441 | IRCConnection.connect | test | def connect(self):
"""\
Connect to the IRC server using the nickname
"""
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if self.use_ssl:
self._sock = ssl.wrap_socket(self._sock)
try:
self._sock.connect((self.server, self.port))
except socket.error:
self.logger.error('Unable to connect to %s on port %d' % (self.server, self.port), exc_info=1)
return False
self._sock_file = self._sock.makefile()
if self.password:
self.set_password()
self.register_nick()
self.register()
return True | python | {
"resource": ""
} |
q275442 | IRCConnection.respond | test | def respond(self, message, channel=None, nick=None):
"""\
Multipurpose method for sending responses to channel or via message to
a single user
"""
if channel:
if not channel.startswith('#'):
channel = '#%s' % channel
self.send('PRIVMSG %s :%s' % (channel, message))
elif nick:
self.send('PRIVMSG %s :%s' % (nick, message)) | python | {
"resource": ""
} |
q275443 | IRCConnection.dispatch_patterns | test | def dispatch_patterns(self):
"""\
Low-level dispatching of socket data based on regex matching, in general
handles
* In event a nickname is taken, registers under a different one
* Responds to periodic PING messages from server
* Dispatches to registered callbacks when
- any user leaves or enters a room currently connected to
- a channel message is observed
- a private message is received
"""
return (
(self.nick_re, self.new_nick),
(self.nick_change_re, self.handle_nick_change),
(self.ping_re, self.handle_ping),
(self.part_re, self.handle_part),
(self.join_re, self.handle_join),
(self.quit_re, self.handle_quit),
(self.chanmsg_re, self.handle_channel_message),
(self.privmsg_re, self.handle_private_message),
(self.registered_re, self.handle_registered),
) | python | {
"resource": ""
} |
q275444 | IRCConnection.new_nick | test | def new_nick(self):
"""\
Generates a new nickname based on original nickname followed by a
random number
"""
old = self.nick
self.nick = '%s_%s' % (self.base_nick, random.randint(1, 1000))
self.logger.warn('Nick %s already taken, trying %s' % (old, self.nick))
self.register_nick()
self.handle_nick_change(old, self.nick) | python | {
"resource": ""
} |
q275445 | IRCConnection.handle_ping | test | def handle_ping(self, payload):
"""\
Respond to periodic PING messages from server
"""
self.logger.info('server ping: %s' % payload)
self.send('PONG %s' % payload, True) | python | {
"resource": ""
} |
q275446 | IRCConnection.handle_registered | test | def handle_registered(self, server):
"""\
When the connection to the server is registered, send all pending
data.
"""
if not self._registered:
self.logger.info('Registered')
self._registered = True
for data in self._out_buffer:
self.send(data)
self._out_buffer = [] | python | {
"resource": ""
} |
q275447 | IRCConnection.enter_event_loop | test | def enter_event_loop(self):
"""\
Main loop of the IRCConnection - reads from the socket and dispatches
based on regex matching
"""
patterns = self.dispatch_patterns()
self.logger.debug('entering receive loop')
while 1:
try:
data = self._sock_file.readline()
except socket.error:
data = None
if not data:
self.logger.info('server closed connection')
self.close()
return True
data = data.rstrip()
for pattern, callback in patterns:
match = pattern.match(data)
if match:
callback(**match.groupdict()) | python | {
"resource": ""
} |
q275448 | BaseWorkerBot.register_with_boss | test | def register_with_boss(self):
"""\
Register the worker with the boss
"""
gevent.sleep(10) # wait for things to connect, etc
while not self.registered.is_set():
self.respond('!register {%s}' % platform.node(), nick=self.boss)
gevent.sleep(30) | python | {
"resource": ""
} |
q275449 | BaseWorkerBot.task_runner | test | def task_runner(self):
"""\
Run tasks in a greenlet, pulling from the workers' task queue and
reporting results to the command channel
"""
while 1:
(task_id, command) = self.task_queue.get()
for pattern, callback in self.task_patterns:
match = re.match(pattern, command)
if match:
# execute the callback
ret = callback(**match.groupdict()) or ''
# clear the stop flag in the event it was set
self.stop_flag.clear()
# send output of command to channel
for line in ret.splitlines():
self.respond('!task-data %s:%s' % (task_id, line), self.channel)
gevent.sleep(.34)
# indicate task is complete
self.respond('!task-finished %s' % task_id, self.channel) | python | {
"resource": ""
} |
q275450 | BaseWorkerBot.require_boss | test | def require_boss(self, callback):
"""\
Decorator to ensure that commands only can come from the boss
"""
def inner(nick, message, channel, *args, **kwargs):
if nick != self.boss:
return
return callback(nick, message, channel, *args, **kwargs)
return inner | python | {
"resource": ""
} |
q275451 | BaseWorkerBot.command_patterns | test | def command_patterns(self):
"""\
Actual messages listened for by the worker bot - note that worker-execute
actually dispatches again by adding the command to the task queue,
from which it is pulled then matched against self.task_patterns
"""
return (
('!register-success (?P<cmd_channel>.+)', self.require_boss(self.register_success)),
('!worker-execute (?:\((?P<workers>.+?)\) )?(?P<task_id>\d+):(?P<command>.+)', self.require_boss(self.worker_execute)),
('!worker-ping', self.require_boss(self.worker_ping_handler)),
('!worker-stop', self.require_boss(self.worker_stop)),
) | python | {
"resource": ""
} |
q275452 | BaseWorkerBot.register_success | test | def register_success(self, nick, message, channel, cmd_channel):
"""\
Received registration acknowledgement from the BotnetBot, as well as the
name of the command channel, so join up and indicate that registration
succeeded
"""
# the boss will tell what channel to join
self.channel = cmd_channel
self.conn.join(self.channel)
# indicate that registered so we'll stop trying
self.registered.set() | python | {
"resource": ""
} |
q275453 | BaseWorkerBot.worker_execute | test | def worker_execute(self, nick, message, channel, task_id, command, workers=None):
"""\
Work on a task from the BotnetBot
"""
if workers:
nicks = workers.split(',')
do_task = self.conn.nick in nicks
else:
do_task = True
if do_task:
self.task_queue.put((int(task_id), command))
return '!task-received %s' % task_id | python | {
"resource": ""
} |
q275454 | Task.add | test | def add(self, nick):
"""\
Indicate that the worker with given nick is performing this task
"""
self.data[nick] = ''
self.workers.add(nick) | python | {
"resource": ""
} |
q275455 | EmailVerifyUserMethodsMixin.send_validation_email | test | def send_validation_email(self):
"""Send a validation email to the user's email address."""
if self.email_verified:
raise ValueError(_('Cannot validate already active user.'))
site = Site.objects.get_current()
self.validation_notification(user=self, site=site).notify() | python | {
"resource": ""
} |
q275456 | EmailVerifyUserMethodsMixin.send_password_reset | test | def send_password_reset(self):
"""Send a password reset to the user's email address."""
site = Site.objects.get_current()
self.password_reset_notification(user=self, site=site).notify() | python | {
"resource": ""
} |
q275457 | validate_password_strength | test | def validate_password_strength(value):
"""
Passwords should be tough.
That means they should use:
- mixed case letters,
- numbers,
- (optionally) ascii symbols and spaces.
The (contrversial?) decision to limit the passwords to ASCII only
is for the sake of:
- simplicity (no need to normalise UTF-8 input)
- security (some character sets are visible as typed into password fields)
TODO: In future, it may be worth considering:
- rejecting common passwords. (Where can we get a list?)
- rejecting passwords with too many repeated characters.
It should be noted that no restriction has been placed on the length of the
password here, as that can easily be achieved with use of the min_length
attribute of a form/serializer field.
"""
used_chars = set(value)
good_chars = set(ascii_letters + digits + punctuation + ' ')
required_sets = (ascii_uppercase, ascii_lowercase, digits)
if not used_chars.issubset(good_chars):
raise ValidationError(too_fancy)
for required in required_sets:
if not used_chars.intersection(required):
raise ValidationError(too_simple) | python | {
"resource": ""
} |
q275458 | VerifyAccountViewMixin.verify_token | test | def verify_token(self, request, *args, **kwargs):
"""
Use `token` to allow one-time access to a view.
Set the user as a class attribute or raise an `InvalidExpiredToken`.
Token expiry can be set in `settings` with `VERIFY_ACCOUNT_EXPIRY` and is
set in seconds.
"""
User = get_user_model()
try:
max_age = settings.VERIFY_ACCOUNT_EXPIRY
except AttributeError:
max_age = self.DEFAULT_VERIFY_ACCOUNT_EXPIRY
try:
email_data = signing.loads(kwargs['token'], max_age=max_age)
except signing.BadSignature:
raise self.invalid_exception_class
email = email_data['email']
try:
self.user = User.objects.get_by_natural_key(email)
except User.DoesNotExist:
raise self.invalid_exception_class
if self.user.email_verified:
raise self.permission_denied_class | python | {
"resource": ""
} |
q275459 | ProfileAvatar.delete | test | def delete(self, request, *args, **kwargs):
"""
Delete the user's avatar.
We set `user.avatar = None` instead of calling `user.avatar.delete()`
to avoid test errors with `django.inmemorystorage`.
"""
user = self.get_object()
user.avatar = None
user.save()
return response.Response(status=HTTP_204_NO_CONTENT) | python | {
"resource": ""
} |
q275460 | PostRequestThrottleMixin.allow_request | test | def allow_request(self, request, view):
"""
Throttle POST requests only.
"""
if request.method != 'POST':
return True
return super(PostRequestThrottleMixin, self).allow_request(request, view) | python | {
"resource": ""
} |
q275461 | SwarmSpawner.executor | test | def executor(self, max_workers=1):
"""single global executor"""
cls = self.__class__
if cls._executor is None:
cls._executor = ThreadPoolExecutor(max_workers)
return cls._executor | python | {
"resource": ""
} |
q275462 | SwarmSpawner.client | test | def client(self):
"""single global client instance"""
cls = self.__class__
if cls._client is None:
kwargs = {}
if self.tls_config:
kwargs['tls'] = docker.tls.TLSConfig(**self.tls_config)
kwargs.update(kwargs_from_env())
client = docker.APIClient(version='auto', **kwargs)
cls._client = client
return cls._client | python | {
"resource": ""
} |
q275463 | SwarmSpawner.tls_client | test | def tls_client(self):
"""A tuple consisting of the TLS client certificate and key if they
have been provided, otherwise None.
"""
if self.tls_cert and self.tls_key:
return (self.tls_cert, self.tls_key)
return None | python | {
"resource": ""
} |
q275464 | SwarmSpawner.service_name | test | def service_name(self):
"""
Service name inside the Docker Swarm
service_suffix should be a numerical value unique for user
{service_prefix}-{service_owner}-{service_suffix}
"""
if hasattr(self, "server_name") and self.server_name:
server_name = self.server_name
else:
server_name = 1
return "{}-{}-{}".format(self.service_prefix,
self.service_owner,
server_name
) | python | {
"resource": ""
} |
q275465 | SwarmSpawner._docker | test | def _docker(self, method, *args, **kwargs):
"""wrapper for calling docker methods
to be passed to ThreadPoolExecutor
"""
m = getattr(self.client, method)
return m(*args, **kwargs) | python | {
"resource": ""
} |
q275466 | SwarmSpawner.docker | test | def docker(self, method, *args, **kwargs):
"""Call a docker method in a background thread
returns a Future
"""
return self.executor.submit(self._docker, method, *args, **kwargs) | python | {
"resource": ""
} |
q275467 | SwarmSpawner.poll | test | def poll(self):
"""Check for a task state like `docker service ps id`"""
service = yield self.get_service()
if not service:
self.log.warn("Docker service not found")
return 0
task_filter = {'service': service['Spec']['Name']}
tasks = yield self.docker(
'tasks', task_filter
)
running_task = None
for task in tasks:
task_state = task['Status']['State']
self.log.debug(
"Task %s of Docker service %s status: %s",
task['ID'][:7],
self.service_id[:7],
pformat(task_state),
)
if task_state == 'running':
# there should be at most one running task
running_task = task
if running_task is not None:
return None
else:
return 1 | python | {
"resource": ""
} |
q275468 | SwarmSpawner.stop | test | def stop(self, now=False):
"""Stop and remove the service
Consider using stop/start when Docker adds support
"""
self.log.info(
"Stopping and removing Docker service %s (id: %s)",
self.service_name, self.service_id[:7])
yield self.docker('remove_service', self.service_id[:7])
self.log.info(
"Docker service %s (id: %s) removed",
self.service_name, self.service_id[:7])
self.clear_state() | python | {
"resource": ""
} |
q275469 | UniqueEmailValidator.filter_queryset | test | def filter_queryset(self, value, queryset):
"""Check lower-cased email is unique."""
return super(UniqueEmailValidator, self).filter_queryset(
value.lower(),
queryset,
) | python | {
"resource": ""
} |
q275470 | PasswordChangeSerializer.update | test | def update(self, instance, validated_data):
"""Check the old password is valid and set the new password."""
if not instance.check_password(validated_data['old_password']):
msg = _('Invalid password.')
raise serializers.ValidationError({'old_password': msg})
instance.set_password(validated_data['new_password'])
instance.save()
return instance | python | {
"resource": ""
} |
q275471 | PasswordResetSerializer.update | test | def update(self, instance, validated_data):
"""Set the new password for the user."""
instance.set_password(validated_data['new_password'])
instance.save()
return instance | python | {
"resource": ""
} |
q275472 | ResendConfirmationEmailSerializer.validate_email | test | def validate_email(self, email):
"""
Validate if email exists and requires a verification.
`validate_email` will set a `user` attribute on the instance allowing
the view to send an email confirmation.
"""
try:
self.user = User.objects.get_by_natural_key(email)
except User.DoesNotExist:
msg = _('A user with this email address does not exist.')
raise serializers.ValidationError(msg)
if self.user.email_verified:
msg = _('User email address is already verified.')
raise serializers.ValidationError(msg)
return email | python | {
"resource": ""
} |
q275473 | GetAuthToken.post | test | def post(self, request):
"""Create auth token. Differs from DRF that it always creates new token
but not re-using them."""
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
user = serializer.validated_data['user']
signals.user_logged_in.send(type(self), user=user, request=request)
token = self.model.objects.create(user=user)
token.update_expiry()
return response.Response({'token': token.key})
return response.Response(
serializer.errors, status=status.HTTP_400_BAD_REQUEST) | python | {
"resource": ""
} |
q275474 | GetAuthToken.delete | test | def delete(self, request, *args, **kwargs):
"""Delete auth token when `delete` request was issued."""
# Logic repeated from DRF because one cannot easily reuse it
auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != b'token':
return response.Response(status=status.HTTP_400_BAD_REQUEST)
if len(auth) == 1:
msg = 'Invalid token header. No credentials provided.'
return response.Response(msg, status=status.HTTP_400_BAD_REQUEST)
elif len(auth) > 2:
msg = 'Invalid token header. Token string should not contain spaces.'
return response.Response(msg, status=status.HTTP_400_BAD_REQUEST)
try:
token = self.model.objects.get(key=auth[1])
except self.model.DoesNotExist:
pass
else:
token.delete()
signals.user_logged_out.send(
type(self),
user=token.user,
request=request,
)
return response.Response(status=status.HTTP_204_NO_CONTENT) | python | {
"resource": ""
} |
q275475 | ResendConfirmationEmail.initial | test | def initial(self, request, *args, **kwargs):
"""Disallow users other than the user whose email is being reset."""
email = request.data.get('email')
if request.user.is_authenticated() and email != request.user.email:
raise PermissionDenied()
return super(ResendConfirmationEmail, self).initial(
request,
*args,
**kwargs
) | python | {
"resource": ""
} |
q275476 | ResendConfirmationEmail.post | test | def post(self, request, *args, **kwargs):
"""Validate `email` and send a request to confirm it."""
serializer = self.serializer_class(data=request.data)
if not serializer.is_valid():
return response.Response(
serializer.errors,
status=status.HTTP_400_BAD_REQUEST,
)
serializer.user.send_validation_email()
msg = _('Email confirmation sent.')
return response.Response(msg, status=status.HTTP_204_NO_CONTENT) | python | {
"resource": ""
} |
q275477 | AuthToken.update_expiry | test | def update_expiry(self, commit=True):
"""Update token's expiration datetime on every auth action."""
self.expires = update_expiry(self.created)
if commit:
self.save() | python | {
"resource": ""
} |
q275478 | password_reset_email_context | test | def password_reset_email_context(notification):
"""Email context to reset a user password."""
return {
'protocol': 'https',
'uid': notification.user.generate_uid(),
'token': notification.user.generate_token(),
'site': notification.site,
} | python | {
"resource": ""
} |
q275479 | email_handler | test | def email_handler(notification, email_context):
"""Send a notification by email."""
incuna_mail.send(
to=notification.user.email,
subject=notification.email_subject,
template_name=notification.text_email_template,
html_template_name=notification.html_email_template,
context=email_context(notification),
headers=getattr(notification, 'headers', {}),
) | python | {
"resource": ""
} |
q275480 | password_reset_email_handler | test | def password_reset_email_handler(notification):
"""Password reset email handler."""
base_subject = _('{domain} password reset').format(domain=notification.site.domain)
subject = getattr(settings, 'DUM_PASSWORD_RESET_SUBJECT', base_subject)
notification.email_subject = subject
email_handler(notification, password_reset_email_context) | python | {
"resource": ""
} |
q275481 | validation_email_handler | test | def validation_email_handler(notification):
"""Validation email handler."""
base_subject = _('{domain} account validate').format(domain=notification.site.domain)
subject = getattr(settings, 'DUM_VALIDATE_EMAIL_SUBJECT', base_subject)
notification.email_subject = subject
email_handler(notification, validation_email_context) | python | {
"resource": ""
} |
q275482 | FormTokenAuthentication.authenticate | test | def authenticate(self, request):
"""
Authenticate a user from a token form field
Errors thrown here will be swallowed by django-rest-framework, and it
expects us to return None if authentication fails.
"""
try:
key = request.data['token']
except KeyError:
return
try:
token = AuthToken.objects.get(key=key)
except AuthToken.DoesNotExist:
return
return (token.user, token) | python | {
"resource": ""
} |
q275483 | TokenAuthentication.authenticate_credentials | test | def authenticate_credentials(self, key):
"""Custom authentication to check if auth token has expired."""
user, token = super(TokenAuthentication, self).authenticate_credentials(key)
if token.expires < timezone.now():
msg = _('Token has expired.')
raise exceptions.AuthenticationFailed(msg)
# Update the token's expiration date
token.update_expiry()
return (user, token) | python | {
"resource": ""
} |
q275484 | notebook_show | test | def notebook_show(obj, doc, comm):
"""
Displays bokeh output inside a notebook.
"""
target = obj.ref['id']
load_mime = 'application/vnd.holoviews_load.v0+json'
exec_mime = 'application/vnd.holoviews_exec.v0+json'
# Publish plot HTML
bokeh_script, bokeh_div, _ = bokeh.embed.notebook.notebook_content(obj, comm.id)
publish_display_data(data={'text/html': encode_utf8(bokeh_div)})
# Publish comm manager
JS = '\n'.join([PYVIZ_PROXY, JupyterCommManager.js_manager])
publish_display_data(data={load_mime: JS, 'application/javascript': JS})
# Publish bokeh plot JS
msg_handler = bokeh_msg_handler.format(plot_id=target)
comm_js = comm.js_template.format(plot_id=target, comm_id=comm.id, msg_handler=msg_handler)
bokeh_js = '\n'.join([comm_js, bokeh_script])
# Note: extension should be altered so text/html is not required
publish_display_data(data={exec_mime: '', 'text/html': '',
'application/javascript': bokeh_js},
metadata={exec_mime: {'id': target}}) | python | {
"resource": ""
} |
q275485 | process_hv_plots | test | def process_hv_plots(widgets, plots):
"""
Temporary fix to patch HoloViews plot comms
"""
bokeh_plots = []
for plot in plots:
if hasattr(plot, '_update_callbacks'):
for subplot in plot.traverse(lambda x: x):
subplot.comm = widgets.server_comm
for cb in subplot.callbacks:
for c in cb.callbacks:
c.code = c.code.replace(plot.id, widgets.plot_id)
plot = plot.state
bokeh_plots.append(plot)
return bokeh_plots | python | {
"resource": ""
} |
q275486 | Widgets._get_customjs | test | def _get_customjs(self, change, p_name):
"""
Returns a CustomJS callback that can be attached to send the
widget state across the notebook comms.
"""
data_template = "data = {{p_name: '{p_name}', value: cb_obj['{change}']}};"
fetch_data = data_template.format(change=change, p_name=p_name)
self_callback = JS_CALLBACK.format(comm_id=self.comm.id,
timeout=self.timeout,
debounce=self.debounce,
plot_id=self.plot_id)
js_callback = CustomJS(code='\n'.join([fetch_data,
self_callback]))
return js_callback | python | {
"resource": ""
} |
q275487 | Widgets.widget | test | def widget(self, param_name):
"""Get widget for param_name"""
if param_name not in self._widgets:
self._widgets[param_name] = self._make_widget(param_name)
return self._widgets[param_name] | python | {
"resource": ""
} |
q275488 | render_function | test | def render_function(obj, view):
"""
The default Renderer function which handles HoloViews objects.
"""
try:
import holoviews as hv
except:
hv = None
if hv and isinstance(obj, hv.core.Dimensioned):
renderer = hv.renderer('bokeh')
if not view._notebook:
renderer = renderer.instance(mode='server')
plot = renderer.get_plot(obj, doc=view._document)
if view._notebook:
plot.comm = view._comm
plot.document = view._document
return plot.state
return obj | python | {
"resource": ""
} |
q275489 | TextWidget | test | def TextWidget(*args, **kw):
"""Forces a parameter value to be text"""
kw['value'] = str(kw['value'])
kw.pop('options', None)
return TextInput(*args,**kw) | python | {
"resource": ""
} |
q275490 | named_objs | test | def named_objs(objlist):
"""
Given a list of objects, returns a dictionary mapping from
string name for the object to the object itself.
"""
objs = []
for k, obj in objlist:
if hasattr(k, '__name__'):
k = k.__name__
else:
k = as_unicode(k)
objs.append((k, obj))
return objs | python | {
"resource": ""
} |
q275491 | get_method_owner | test | def get_method_owner(meth):
"""
Returns the instance owning the supplied instancemethod or
the class owning the supplied classmethod.
"""
if inspect.ismethod(meth):
if sys.version_info < (3,0):
return meth.im_class if meth.im_self is None else meth.im_self
else:
return meth.__self__ | python | {
"resource": ""
} |
q275492 | AsyncHttpConnection._assign_auth_values | test | def _assign_auth_values(self, http_auth):
"""Take the http_auth value and split it into the attributes that
carry the http auth username and password
:param str|tuple http_auth: The http auth value
"""
if not http_auth:
pass
elif isinstance(http_auth, (tuple, list)):
self._auth_user, self._auth_password = http_auth
elif isinstance(http_auth, str):
self._auth_user, self._auth_password = http_auth.split(':')
else:
raise ValueError('HTTP Auth Credentials should be str or '
'tuple, not %s' % type(http_auth)) | python | {
"resource": ""
} |
q275493 | AsyncElasticsearch.ping | test | def ping(self, params=None):
""" Returns True if the cluster is up, False otherwise. """
try:
self.transport.perform_request('HEAD', '/', params=params)
except TransportError:
raise gen.Return(False)
raise gen.Return(True) | python | {
"resource": ""
} |
q275494 | AsyncElasticsearch.info | test | def info(self, params=None):
"""Get the basic info from the current cluster.
:rtype: dict
"""
_, data = yield self.transport.perform_request('GET', '/',
params=params)
raise gen.Return(data) | python | {
"resource": ""
} |
q275495 | AsyncElasticsearch.health | test | def health(self, params=None):
"""Coroutine. Queries cluster Health API.
Returns a 2-tuple, where first element is request status, and second
element is a dictionary with response data.
:param params: dictionary of query parameters, will be handed over to
the underlying :class:`~torando_elasticsearch.AsyncHTTPConnection`
class for serialization
"""
status, data = yield self.transport.perform_request(
"GET", "/_cluster/health", params=params)
raise gen.Return((status, data)) | python | {
"resource": ""
} |
q275496 | SynoFormatHelper.bytes_to_readable | test | def bytes_to_readable(num):
"""Converts bytes to a human readable format"""
if num < 512:
return "0 Kb"
elif num < 1024:
return "1 Kb"
for unit in ['', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb', 'Eb', 'Zb']:
if abs(num) < 1024.0:
return "%3.1f%s" % (num, unit)
num /= 1024.0
return "%.1f%s" % (num, 'Yb') | python | {
"resource": ""
} |
q275497 | SynoUtilization.cpu_total_load | test | def cpu_total_load(self):
"""Total CPU load for Synology DSM"""
system_load = self.cpu_system_load
user_load = self.cpu_user_load
other_load = self.cpu_other_load
if system_load is not None and \
user_load is not None and \
other_load is not None:
return system_load + user_load + other_load | python | {
"resource": ""
} |
q275498 | SynoUtilization.memory_size | test | def memory_size(self, human_readable=True):
"""Total Memory Size of Synology DSM"""
if self._data is not None:
# Memory is actually returned in KB's so multiply before converting
return_data = int(self._data["memory"]["memory_size"]) * 1024
if human_readable:
return SynoFormatHelper.bytes_to_readable(
return_data)
else:
return return_data | python | {
"resource": ""
} |
q275499 | SynoUtilization.network_up | test | def network_up(self, human_readable=True):
"""Total upload speed being used"""
network = self._get_network("total")
if network is not None:
return_data = int(network["tx"])
if human_readable:
return SynoFormatHelper.bytes_to_readable(
return_data)
else:
return return_data | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.