buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
MSG_USERAUTH_INFO_REQUEST, MSG_USERAUTH_INFO_RESPONSE = range(60, 62)
MSG_USERAUTH_GSSAPI_RESPONSE, MSG_USERAUTH_GSSAPI_TOKEN = range(60, 62)
MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE, MSG_USERAUTH_GSSAPI_ERROR,\
MSG_USERAUTH_GSSAPI_ERRTOK, MSG_USERAUTH_GSSAPI_MIC = range(63, 67)
MSG_GLOBAL_REQUEST, MSG_REQUEST_SUCCESS, MS... | MSG_USERAUTH_INFO_REQUEST, MSG_USERAUTH_INFO_RESPONSE = range(60, 62)
MSG_USERAUTH_GSSAPI_RESPONSE, MSG_USERAUTH_GSSAPI_TOKEN = range(60, 62)
MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE, MSG_USERAUTH_GSSAPI_ERROR,\
MSG_USERAUTH_GSSAPI_ERRTOK, MSG_USERAUTH_GSSAPI_MIC = range(63, 67)
HIGHEST_USERAUTH_MESSAGE_ID = 79
MSG_GLOBAL... |
from paramiko.common import xffffffff, cMSG_CHANNEL_OPEN, cMSG_IGNORE, \
MSG_CHANNEL_SUCCESS, MSG_CHANNEL_FAILURE, MSG_CHANNEL_DATA, \
MSG_CHANNEL_EXTENDED_DATA, MSG_CHANNEL_WINDOW_ADJUST, MSG_CHANNEL_REQUEST, \
MSG_CHANNEL_EOF, MSG_CHANNEL_CLOSE, MIN_WINDOW_SIZE, MIN_PACKET_SIZE, \
MAX_WINDOW_SIZE, DEF... | from paramiko.common import xffffffff, cMSG_CHANNEL_OPEN, cMSG_IGNORE, \
MSG_CHANNEL_SUCCESS, MSG_CHANNEL_FAILURE, MSG_CHANNEL_DATA, \
MSG_CHANNEL_EXTENDED_DATA, MSG_CHANNEL_WINDOW_ADJUST, MSG_CHANNEL_REQUEST, \
MSG_CHANNEL_EOF, MSG_CHANNEL_CLOSE, MIN_WINDOW_SIZE, MIN_PACKET_SIZE, \
MAX_WINDOW_SIZE, DEF... |
class Transport (threading.Thread, ClosingContextManager):
max_packet_size = self.default_max_packet_size
return clamp_value(MIN_PACKET_SIZE, max_packet_size, MAX_WINDOW_SIZE)
def run(self):
# (use the exposed "run" method, because if we specify a thread target | class Transport (threading.Thread, ClosingContextManager):
max_packet_size = self.default_max_packet_size
return clamp_value(MIN_PACKET_SIZE, max_packet_size, MAX_WINDOW_SIZE)
def _ensure_authed(self, ptype, message):
"""
Checks message type against current auth state.
... |
class Transport (threading.Thread, ClosingContextManager):
continue
if ptype in self._handler_table:
self._handler_table[ptype](self, m)
elif ptype in self._channel_handler_table:
chanid = m.get_int()
... | class Transport (threading.Thread, ClosingContextManager):
continue
if ptype in self._handler_table:
error_msg = self._ensure_authed(ptype, m)
if error_msg:
self._send_message(error_msg)
... |
import copy
from django import forms
from django.core.exceptions import ValidationError
from django.db.models.deletion import CASCADE
from django.urls import reverse
from django.urls.exceptions import NoReverseMatch | import copy
from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
from django.db.models.deletion import CASCADE
from django.urls import reverse
from django.urls.exceptions import NoReverseMatch |
class AdminEmailInputWidget(forms.EmailInput):
class AdminURLFieldWidget(forms.URLInput):
template_name = 'admin/widgets/url.html'
def __init__(self, attrs=None):
final_attrs = {'class': 'vURLField'}
if attrs is not None:
final_attrs.update(attrs)
super(AdminURLFieldWidget, ... | class AdminEmailInputWidget(forms.EmailInput):
class AdminURLFieldWidget(forms.URLInput):
template_name = 'admin/widgets/url.html'
def __init__(self, attrs=None, validator_class=URLValidator):
final_attrs = {'class': 'vURLField'}
if attrs is not None:
final_attrs.update(attrs)
... |
class AdminSplitDateTimeWidgetTest(SimpleTestCase):
class AdminURLWidgetTest(SimpleTestCase):
def test_render(self):
w = widgets.AdminURLFieldWidget()
self.assertHTMLEqual( | class AdminSplitDateTimeWidgetTest(SimpleTestCase):
class AdminURLWidgetTest(SimpleTestCase):
def test_get_context_validates_url(self):
w = widgets.AdminURLFieldWidget()
for invalid in ['', '/not/a/full/url/', 'javascript:alert("Danger XSS!")']:
self.assertFalse(w.get_context('name', i... |
class AdminURLWidgetTest(SimpleTestCase):
VALUE_RE = re.compile('value="([^"]+)"')
TEXT_RE = re.compile('<a[^>]+>([^>]+)</a>')
w = widgets.AdminURLFieldWidget()
output = w.render('test', 'http://example.com/<sometag>some text</sometag>')
self.assertEqual(
HREF_RE.sear... | class AdminURLWidgetTest(SimpleTestCase):
VALUE_RE = re.compile('value="([^"]+)"')
TEXT_RE = re.compile('<a[^>]+>([^>]+)</a>')
w = widgets.AdminURLFieldWidget()
output = w.render('test', 'http://example.com/<sometag>some-text</sometag>')
self.assertEqual(
HREF_RE.sear... |
def test_sampleformat_not_corrupted(self):
out.seek(0)
with Image.open(out) as im:
im.load() | def test_sampleformat_not_corrupted(self):
out.seek(0)
with Image.open(out) as im:
im.load()
def test_realloc_overflow(self):
TiffImagePlugin.READ_LIBTIFF = True
with Image.open("Tests/images/tiff_overflow_rows_per_strip.tif") as im:
with self.assertRaises(IO... |
def categorical_accuracy(y_true, y_pred):
def sparse_categorical_accuracy(y_true, y_pred):
return K.cast(K.equal(K.max(y_true, axis=-1),
K.cast(K.argmax(y_pred, axis=-1), K.floatx())),
K.floatx())
| def categorical_accuracy(y_true, y_pred):
def sparse_categorical_accuracy(y_true, y_pred):
# flatten y_true in case it's in shape (num_samples, 1) instead of (num_samples,)
return K.cast(K.equal(K.flatten(y_true),
K.cast(K.argmax(y_pred, axis=-1), K.floatx())),
K.fl... |
def test_sparse_metrics():
assert K.eval(metric(y_a, y_b)).shape == (6,)
def test_serialize():
'''This is a mock 'round trip' of serialize and deserialize.
''' | def test_sparse_metrics():
assert K.eval(metric(y_a, y_b)).shape == (6,)
@keras_test
def test_sparse_categorical_accuracy_correctness():
y_a = K.variable(np.random.randint(0, 7, (6,)), dtype=K.floatx())
y_b = K.variable(np.random.random((6, 7)), dtype=K.floatx())
# use one_hot embedding to convert... |
from rencode import rencode_orig
# Hack to deal with python 2 and 3 differences with unicode literals.
if sys.version < '3':
import codecs
def u(x):
return codecs.unicode_escape_decode(x)[0]
else:
unicode = str
def u(x):
return x
class TestRencode(unittest.TestCase):
def test_enc... | from rencode import rencode_orig
class TestRencode(unittest.TestCase):
def _cmp(self, *values):
for v in values:
self.assertEqual(rencode.dumps(v), rencode_orig.dumps(v))
def _reload(self, *values):
for v in values:
self.assertEqual(rencode.loads(rencode.dumps(v)), v)... |
def test_encode_float_invalid_size(self):
self.assertRaises(ValueError, rencode.dumps, 1234.56, 36)
def test_encode_fixed_str(self):
self.assertEqual(rencode.dumps(b"foobarbaz"), rencode_orig.dumps(b"foobarbaz"))
def test_encode_str(self):
self.assertEqual(rencode.dumps(b"f"*255), renc... | def test_encode_float_invalid_size(self):
self.assertRaises(ValueError, rencode.dumps, 1234.56, 36)
def test_encode_fixed_str(self):
self._cmp(b"foobarbaz")
def test_encode_str(self):
self._cmp(b"f"*255, b"\0")
def test_encode_unicode(self):
self._cmp(u"fööbar")
def t... |
def test_decode_float_64bit(self):
self.assertRaises(IndexError, rencode.loads, bytes(bytearray([44])))
def test_decode_fixed_str(self):
self.assertEqual(rencode.loads(rencode.dumps(b"foobarbaz")), b"foobarbaz")
self.assertRaises(IndexError, rencode.loads, bytes(bytearray([130])))
def ... | def test_decode_float_64bit(self):
self.assertRaises(IndexError, rencode.loads, bytes(bytearray([44])))
def test_decode_fixed_str(self):
self._reload(b"foobarbaz")
self.assertRaises(IndexError, rencode.loads, bytes(bytearray([130])))
def test_decode_str(self):
self._reload(b"f"... |
def test_version_exposed(self):
assert rencode_orig.__version__
self.assertEqual(rencode.__version__[1:], rencode_orig.__version__[1:], "version number does not match")
if __name__ == '__main__':
unittest.main() | def test_version_exposed(self):
assert rencode_orig.__version__
self.assertEqual(rencode.__version__[1:], rencode_orig.__version__[1:], "version number does not match")
def test_invalidtypecode(self):
s = b';\x2f\x7f'
try:
rencode.loads(s)
except Exception:
... |
class PamdRule(PamdLine):
valid_control_actions = ['ignore', 'bad', 'die', 'ok', 'done', 'reset']
def __init__(self, rule_type, rule_control, rule_path, rule_args=None):
self._control = None
self._args = None
self.rule_type = rule_type | class PamdRule(PamdLine):
valid_control_actions = ['ignore', 'bad', 'die', 'ok', 'done', 'reset']
def __init__(self, rule_type, rule_control, rule_path, rule_args=None):
self.prev = None
self.next = None
self._control = None
self._args = None
self.rule_type = rule_type |
class PamdService(object):
if current_line.matches(rule_type, rule_control, rule_path):
if current_line.prev is not None:
current_line.prev.next = current_line.next
current_line.next.prev = current_line.prev
else:
se... | class PamdService(object):
if current_line.matches(rule_type, rule_control, rule_path):
if current_line.prev is not None:
current_line.prev.next = current_line.next
if current_line.next is not None:
current_line.next.prev = curr... |
session required pam_unix.so"""
auth required pam_env.so
"""
self.pamd = PamdService(self.system_auth_string)
def test_properly_parsed(self): | session required pam_unix.so"""
auth required pam_env.so
"""
self.no_header_system_auth_string = """auth required pam_env.so
auth sufficient pam_unix.so nullok try_first_pass
auth requisite pam_succeed_if.so uid
auth required pam_deny.so
"""
self.pamd = PamdSer... |
session required pam_unix.so"""
self.assertFalse(self.pamd.remove('account', 'required', 'pam_unix.so'))
test_rule = PamdRule('account', 'required', 'pam_unix.so')
self.assertNotIn(str(test_rule), str(self.pamd)) | session required pam_unix.so"""
self.assertFalse(self.pamd.remove('account', 'required', 'pam_unix.so'))
test_rule = PamdRule('account', 'required', 'pam_unix.so')
self.assertNotIn(str(test_rule), str(self.pamd))
def test_remove_first_rule(self):
no_header_service = PamdService(s... |
def add_special_arithmetic_methods(cls):
def f(self, other):
result = method(self, other)
# this makes sure that we are aligned like the input
# we are updating inplace so we want to ignore is_copy
self._update_inplace( | def add_special_arithmetic_methods(cls):
def f(self, other):
result = method(self, other)
# Delete cacher
self._reset_cacher()
# this makes sure that we are aligned like the input
# we are updating inplace so we want to ignore is_copy
self... |
class TestDataFrameSelectReindex:
result = df2.reindex(midx)
expected = pd.DataFrame({"a": [0, 1, 2, 3, 4, 5, 6, np.nan, 8]}, index=midx)
tm.assert_frame_equal(result, expected) | class TestDataFrameSelectReindex:
result = df2.reindex(midx)
expected = pd.DataFrame({"a": [0, 1, 2, 3, 4, 5, 6, np.nan, 8]}, index=midx)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"operation", ["__iadd__", "__isub__", "__imul__", "__ipow__"]
)
@pytest... |
class Model(Container):
nested_weighted_metrics = _collect_metrics(weighted_metrics, self.output_names)
self.metrics_updates = []
self.stateful_metric_names = []
with K.name_scope('metrics'):
for i in range(len(self.outputs)):
if i in skip_target_indices: | class Model(Container):
nested_weighted_metrics = _collect_metrics(weighted_metrics, self.output_names)
self.metrics_updates = []
self.stateful_metric_names = []
self.stateful_metric_functions = []
with K.name_scope('metrics'):
for i in range(len(self.outputs)):
... |
class Model(Container):
# stateful metrics (i.e. metrics layers).
if isinstance(metric_fn, Layer) and metric_fn.stateful:
self.stateful_metric_names.append(metric_name)
self.metrics_updates += metric_fn.updates
... | class Model(Container):
# stateful metrics (i.e. metrics layers).
if isinstance(metric_fn, Layer) and metric_fn.stateful:
self.stateful_metric_names.append(metric_name)
self.stateful_metric_functions.append(metric_fn... |
class Model(Container):
for epoch in range(initial_epoch, epochs):
# Reset stateful metrics
for m in self.metrics:
if isinstance(m, Layer) and m.stateful:
m.reset_states()
callbacks.on_epoch_begin(epoch)
epoch_logs = {}
... | class Model(Container):
for epoch in range(initial_epoch, epochs):
# Reset stateful metrics
for m in self.stateful_metric_functions:
m.reset_states()
callbacks.on_epoch_begin(epoch)
epoch_logs = {}
if steps_per_epoch is not None: |
class Model(Container):
"""
if hasattr(self, 'metrics'):
for m in self.metrics:
if isinstance(m, Layer) and m.stateful:
m.reset_states()
stateful_metric_indices = [
i for i, name in enumerate(self.metrics_names)
... | class Model(Container):
"""
if hasattr(self, 'metrics'):
for m in self.stateful_metric_functions:
m.reset_states()
stateful_metric_indices = [
i for i, name in enumerate(self.metrics_names)
if str(name) in self.stateful_metric_name... |
class Model(Container):
# Construct epoch logs.
epoch_logs = {}
while epoch < epochs:
for m in self.metrics:
if isinstance(m, Layer) and m.stateful:
m.reset_states()
callbacks.on_epoch_begin(epoch)
... | class Model(Container):
# Construct epoch logs.
epoch_logs = {}
while epoch < epochs:
for m in self.stateful_metric_functions:
m.reset_states()
callbacks.on_epoch_begin(epoch)
steps_done = 0
batch_ind... |
class Model(Container):
stateful_metric_indices = []
if hasattr(self, 'metrics'):
for i, m in enumerate(self.metrics):
if isinstance(m, Layer) and m.stateful:
m.reset_states()
stateful_metric_indices = [
i for i, name in enumer... | class Model(Container):
stateful_metric_indices = []
if hasattr(self, 'metrics'):
for m in self.stateful_metric_functions:
m.reset_states()
stateful_metric_indices = [
i for i, name in enumerate(self.metrics_names)
if str(name) in ... |
def test_sparse_top_k_categorical_accuracy():
@keras_test
def test_stateful_metrics():
np.random.seed(1334)
class BinaryTruePositives(keras.layers.Layer): | def test_sparse_top_k_categorical_accuracy():
@keras_test
@pytest.mark.parametrize('metrics_mode', ['list', 'dict'])
def test_stateful_metrics(metrics_mode):
np.random.seed(1334)
class BinaryTruePositives(keras.layers.Layer): |
def test_stateful_metrics():
# Test on simple model
inputs = keras.Input(shape=(2,))
outputs = keras.layers.Dense(1, activation='sigmoid')(inputs)
model = keras.Model(inputs, outputs)
model.compile(optimizer='sgd',
loss='binary_crossentropy',
metrics=['acc', metr... | def test_stateful_metrics():
# Test on simple model
inputs = keras.Input(shape=(2,))
outputs = keras.layers.Dense(1, activation='sigmoid', name='out')(inputs)
model = keras.Model(inputs, outputs)
if metrics_mode == 'list':
model.compile(optimizer='sgd',
loss='binary_c... |
class HttpRequest(object):
if server_port != ('443' if self.is_secure() else '80'):
host = '%s:%s' % (host, server_port)
# There is no hostname validation when DEBUG=True
if settings.DEBUG:
return host
domain, port = split_domain_port(host)
if do... | class HttpRequest(object):
if server_port != ('443' if self.is_secure() else '80'):
host = '%s:%s' % (host, server_port)
# Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True.
allowed_hosts = settings.ALLOWED_HOSTS
if settings.DEBUG and not allowed_h... |
class HostValidationTests(SimpleTestCase):
request.get_host()
@override_settings(DEBUG=True, ALLOWED_HOSTS=[])
def test_host_validation_disabled_in_debug_mode(self):
"""If ALLOWED_HOSTS is empty and DEBUG is True, all hosts pass."""
request = HttpRequest()
request.META =... | class HostValidationTests(SimpleTestCase):
request.get_host()
@override_settings(DEBUG=True, ALLOWED_HOSTS=[])
def test_host_validation_in_debug_mode(self):
"""
If ALLOWED_HOSTS is empty and DEBUG is True, variants of localhost are
allowed.
"""
valid_host... |
def read_json(
dtype = True
if convert_axes is None and orient != "table":
convert_axes = True
compression = _infer_compression(path_or_buf, compression)
filepath_or_buffer, _, compression, should_close = get_filepath_or_buffer( | def read_json(
dtype = True
if convert_axes is None and orient != "table":
convert_axes = True
if encoding is None:
encoding = "utf-8"
compression = _infer_compression(path_or_buf, compression)
filepath_or_buffer, _, compression, should_close = get_filepath_or_buffer( |
def test_readjson_chunks_multiple_empty_lines(chunksize):
tm.assert_frame_equal(
orig, test, obj="chunksize: {chunksize}".format(chunksize=chunksize)
) | def test_readjson_chunks_multiple_empty_lines(chunksize):
tm.assert_frame_equal(
orig, test, obj="chunksize: {chunksize}".format(chunksize=chunksize)
)
def test_readjson_unicode(monkeypatch):
with tm.ensure_clean("test.json") as path:
monkeypatch.setattr("_bootlocale.getpreferredencoding",... |
class PythonItemExporter(BaseItemExporter):
return dict(self._serialize_dict(value))
if is_listlike(value):
return [self._serialize_value(v) for v in value]
if self.binary:
return to_bytes(value, encoding=self.encoding)
else:
return to_unicode(valu... | class PythonItemExporter(BaseItemExporter):
return dict(self._serialize_dict(value))
if is_listlike(value):
return [self._serialize_value(v) for v in value]
encode_func = to_bytes if self.binary else to_unicode
if isinstance(value, (six.text_type, bytes)):
ret... |
class PythonItemExporterTest(BaseItemExporterTest):
expected = {b'name': b'John\xc2\xa3', b'age': b'22'}
self.assertEqual(expected, exporter.export_item(value))
class PprintItemExporterTest(BaseItemExporterTest):
| class PythonItemExporterTest(BaseItemExporterTest):
expected = {b'name': b'John\xc2\xa3', b'age': b'22'}
self.assertEqual(expected, exporter.export_item(value))
def test_other_python_types_item(self):
from datetime import datetime
now = datetime.now()
item = {
'b... |
TECHNICAL_500_TEMPLATE = ("""
<h2>Traceback <span class="commands">{% if not is_email %}<a href="#" onclick="return switchPastebinFriendly(this);">
Switch to copy-and-paste view</a></span>{% endif %}
</h2>
{% autoescape off %}
<div id="browserTraceback">
<ul class="traceback">
{% for frame in fram... | TECHNICAL_500_TEMPLATE = ("""
<h2>Traceback <span class="commands">{% if not is_email %}<a href="#" onclick="return switchPastebinFriendly(this);">
Switch to copy-and-paste view</a></span>{% endif %}
</h2>
<div id="browserTraceback">
<ul class="traceback">
{% for frame in frames %}
{% ifchan... |
TECHNICAL_500_TEMPLATE = ("""
<tbody>
{% for var in frame.vars|dictsort:0 %}
<tr>
<td>{{ var.0|force_escape }}</td>
<td class="code"><pre>{{ var.1 }}</pre></td>
</tr>
{% endfor %} | TECHNICAL_500_TEMPLATE = ("""
<tbody>
{% for var in frame.vars|dictsort:0 %}
<tr>
<td>{{ var.0 }}</td>
<td class="code"><pre>{{ var.1 }}</pre></td>
</tr>
{% endfor %} |
TECHNICAL_500_TEMPLATE = ("""
{% endfor %}
</ul>
</div>
{% endautoescape %}
<form action="http://dpaste.com/" name="pasteform" id="pasteform" method="post">
{% if not is_email %}
<div id="pastebinTraceback" class="pastebin"> | TECHNICAL_500_TEMPLATE = ("""
{% endfor %}
</ul>
</div>
<form action="http://dpaste.com/" name="pasteform" id="pasteform" method="post">
{% if not is_email %}
<div id="pastebinTraceback" class="pastebin"> |
In template {{ template_info.name }}, error at line {{ template_info.line }}
Traceback:{% for frame in frames %}
{% ifchanged frame.exc_cause %}{% if frame.exc_cause %}{% if frame.exc_cause_explicit %}
The above exception ({{ frame.exc_cause }}) was the direct cause of the following exception:
{% else %}
During handli... | In template {{ template_info.name }}, error at line {{ template_info.line }}
Traceback:{% for frame in frames %}
{% ifchanged frame.exc_cause %}{% if frame.exc_cause %}{% if frame.exc_cause_explicit %}
The above exception ({{ frame.exc_cause|force_escape }}) was the direct cause of the following exception:
{% else %}
... |
error (raise ... from ...) can't be silenced using NOQA.
import sys
from django.test import RequestFactory, TestCase
from django.views.debug import ExceptionReporter
| error (raise ... from ...) can't be silenced using NOQA.
import sys
from django.test import RequestFactory, TestCase
from django.utils.safestring import mark_safe
from django.views.debug import ExceptionReporter
|
class Py3ExceptionReporterTests(TestCase):
request = self.rf.get('/test_view/')
try:
try:
raise AttributeError('Top level')
except AttributeError as explicit:
try:
raise ValueError('Second exception') from explicit
... | class Py3ExceptionReporterTests(TestCase):
request = self.rf.get('/test_view/')
try:
try:
raise AttributeError(mark_safe('<p>Top level</p>'))
except AttributeError as explicit:
try:
raise ValueError('<p>Second exception</p>') fr... |
class Py3ExceptionReporterTests(TestCase):
html = reporter.get_traceback_html()
# Both messages are twice on page -- one rendered as html,
# one as plain text (for pastebin)
self.assertEqual(2, html.count(explicit_exc.format("Top level")))
self.assertEqual(2, html.count(implicit_... | class Py3ExceptionReporterTests(TestCase):
html = reporter.get_traceback_html()
# Both messages are twice on page -- one rendered as html,
# one as plain text (for pastebin)
self.assertEqual(2, html.count(explicit_exc.format('<p>Top level</p>')))
self.assertEqual(2, h... |
import stat
from django.http import (
FileResponse, Http404, HttpResponse, HttpResponseNotModified,
HttpResponseRedirect,
)
from django.template import Context, Engine, TemplateDoesNotExist, loader
from django.utils.http import http_date, parse_http_date
from django.utils.six.moves.urllib.parse import unquote
... | import stat
from django.http import (
FileResponse, Http404, HttpResponse, HttpResponseNotModified,
)
from django.template import Context, Engine, TemplateDoesNotExist, loader
from django.utils._os import safe_join
from django.utils.http import http_date, parse_http_date
from django.utils.six.moves.urllib.parse im... |
def serve(request, path, document_root=None, show_indexes=False):
but if you'd like to override it, you can create a template called
``static/directory_index.html``.
"""
path = posixpath.normpath(unquote(path))
path = path.lstrip('/')
newpath = ''
for part in path.split('/'):
if not ... | def serve(request, path, document_root=None, show_indexes=False):
but if you'd like to override it, you can create a template called
``static/directory_index.html``.
"""
path = posixpath.normpath(unquote(path)).lstrip('/')
fullpath = safe_join(document_root, path)
if os.path.isdir(fullpath):
... |
Name: Max Speed, dtype: float64
if copy:
new_values = new_values.copy()
assert isinstance(self.index, PeriodIndex)
new_index = self.index.to_timestamp(freq=freq, how=how) # type: ignore
return self._constructor(new_values, index=new_index).__finalize__(
self, me... | Name: Max Speed, dtype: float64
if copy:
new_values = new_values.copy()
if not isinstance(self.index, PeriodIndex):
raise TypeError(f"unsupported Type {type(self.index).__name__}")
new_index = self.index.to_timestamp(freq=freq, how=how) # type: ignore
return sel... |
Name: Max Speed, dtype: float64
if copy:
new_values = new_values.copy()
assert isinstance(self.index, DatetimeIndex)
new_index = self.index.to_period(freq=freq) # type: ignore
return self._constructor(new_values, index=new_index).__finalize__(
self, method="to_p... | Name: Max Speed, dtype: float64
if copy:
new_values = new_values.copy()
if not isinstance(self.index, DatetimeIndex):
raise TypeError(f"unsupported Type {type(self.index).__name__}")
new_index = self.index.to_period(freq=freq) # type: ignore
return self._constru... |
import numpy as np
from pandas import (
DataFrame, | import numpy as np
import pytest
from pandas import (
DataFrame, |
class TestToPeriod:
expected = df.copy()
expected.columns = exp_idx
tm.assert_frame_equal(df.to_period(axis=1), expected) | class TestToPeriod:
expected = df.copy()
expected.columns = exp_idx
tm.assert_frame_equal(df.to_period(axis=1), expected)
def test_to_period_raises(self, indices):
# https://github.com/pandas-dev/pandas/issues/33327
index = indices
ser = Series(index=index, dtype=obj... |
from datetime import timedelta
from pandas import Series, Timedelta, date_range, period_range, to_datetime
import pandas._testing as tm
| from datetime import timedelta
import pytest
from pandas import PeriodIndex, Series, Timedelta, date_range, period_range, to_datetime
import pandas._testing as tm
|
class TestToTimestamp:
exp_index = exp_index + Timedelta(1, "s") - Timedelta(1, "ns")
tm.assert_index_equal(result.index, exp_index)
assert result.name == "foo" | class TestToTimestamp:
exp_index = exp_index + Timedelta(1, "s") - Timedelta(1, "ns")
tm.assert_index_equal(result.index, exp_index)
assert result.name == "foo"
def test_to_timestamp_raises(self, indices):
# https://github.com/pandas-dev/pandas/issues/33327
index = indices
... |
class Categorical(ExtensionArray, PandasObject):
Only ordered `Categoricals` have a minimum!
Raises
------
TypeError | class Categorical(ExtensionArray, PandasObject):
Only ordered `Categoricals` have a minimum!
.. versionchanged:: 1.0.0
Returns an NA value on empty arrays
Raises
------
TypeError |
class Categorical(ExtensionArray, PandasObject):
min : the minimum of this `Categorical`
"""
self.check_for_ordered("min")
good = self._codes != -1
if not good.all():
if skipna: | class Categorical(ExtensionArray, PandasObject):
min : the minimum of this `Categorical`
"""
self.check_for_ordered("min")
if not len(self._codes):
return self.dtype.na_value
good = self._codes != -1
if not good.all():
if skipna: |
class Categorical(ExtensionArray, PandasObject):
Only ordered `Categoricals` have a maximum!
Raises
------
TypeError | class Categorical(ExtensionArray, PandasObject):
Only ordered `Categoricals` have a maximum!
.. versionchanged:: 1.0.0
Returns an NA value on empty arrays
Raises
------
TypeError |
class Categorical(ExtensionArray, PandasObject):
max : the maximum of this `Categorical`
"""
self.check_for_ordered("max")
good = self._codes != -1
if not good.all():
if skipna: | class Categorical(ExtensionArray, PandasObject):
max : the maximum of this `Categorical`
"""
self.check_for_ordered("max")
if not len(self._codes):
return self.dtype.na_value
good = self._codes != -1
if not good.all():
if skipna: |
import pytest
from pandas.compat import PYPY
from pandas import Categorical, Index, Series
from pandas.api.types import is_scalar
import pandas.util.testing as tm
class TestCategoricalAnalytics:
def test_min_max(self):
# unordered cats have no min/max
cat = Categorical(["a", "b", "c", "d"], ord... | import pytest
from pandas.compat import PYPY
from pandas import Categorical, Index, NaT, Series, date_range
from pandas.api.types import is_scalar
import pandas.util.testing as tm
class TestCategoricalAnalytics:
@pytest.mark.parametrize("aggregation", ["min", "max"])
def test_min_max_not_ordered_raises(self... |
class TestCategoricalAnalytics:
assert _min == "d"
assert _max == "a"
@pytest.mark.parametrize("skipna", [True, False])
def test_min_max_with_nan(self, skipna):
# GH 25303 | class TestCategoricalAnalytics:
assert _min == "d"
assert _max == "a"
@pytest.mark.parametrize(
"categories,expected",
[
(list("ABC"), np.NaN),
([1, 2, 3], np.NaN),
pytest.param(
Series(date_range("2020-01-01", periods=3), dtype="c... |
from django.contrib.postgres.fields import JSONField
from django.db.models.aggregates import Aggregate
__all__ = [ | from django.contrib.postgres.fields import JSONField
from django.db.models import Value
from django.db.models.aggregates import Aggregate
__all__ = [ |
class JSONBAgg(Aggregate):
class StringAgg(Aggregate):
function = 'STRING_AGG'
template = "%(function)s(%(distinct)s%(expressions)s, '%(delimiter)s')"
def __init__(self, expression, delimiter, distinct=False, **extra):
distinct = 'DISTINCT ' if distinct else ''
super(StringAgg, self).__ini... | class JSONBAgg(Aggregate):
class StringAgg(Aggregate):
function = 'STRING_AGG'
template = '%(function)s(%(distinct)s%(expressions)s)'
def __init__(self, expression, delimiter, distinct=False, **extra):
distinct = 'DISTINCT ' if distinct else ''
delimiter_expr = Value(str(delimiter))
... |
class TestGeneralAggregate(PostgreSQLTestCase):
with self.assertRaises(TypeError):
AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field'))
def test_string_agg_charfield(self):
values = AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field', delimiter=';'))... | class TestGeneralAggregate(PostgreSQLTestCase):
with self.assertRaises(TypeError):
AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field'))
def test_string_agg_delimiter_escaping(self):
values = AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field', delimi... |
from youtube_dl.utils import (
shell_quote,
smuggle_url,
str_to_int,
timeconvert,
unescapeHTML,
unified_strdate, | from youtube_dl.utils import (
shell_quote,
smuggle_url,
str_to_int,
struct_unpack,
timeconvert,
unescapeHTML,
unified_strdate, |
class TestUtil(unittest.TestCase):
testPL(5, 2, (2, 99), [2, 3, 4])
testPL(5, 2, (20, 99), [])
if __name__ == '__main__':
unittest.main() | class TestUtil(unittest.TestCase):
testPL(5, 2, (2, 99), [2, 3, 4])
testPL(5, 2, (20, 99), [])
def test_struct_unpack(self):
self.assertEqual(struct_unpack(u'!B', b'\x00'), (0,))
if __name__ == '__main__':
unittest.main() |
import base64
import io
import itertools
import os
from struct import unpack, pack
import time
import xml.etree.ElementTree as etree
from .common import FileDownloader
from .http import HttpFD
from ..utils import (
compat_urllib_request,
compat_urlparse,
format_bytes, | import base64
import io
import itertools
import os
import time
import xml.etree.ElementTree as etree
from .common import FileDownloader
from .http import HttpFD
from ..utils import (
struct_pack,
struct_unpack,
compat_urllib_request,
compat_urlparse,
format_bytes, |
class FlvReader(io.BytesIO):
# Utility functions for reading numbers and strings
def read_unsigned_long_long(self):
return unpack('!Q', self.read(8))[0]
def read_unsigned_int(self):
return unpack('!I', self.read(4))[0]
def read_unsigned_char(self):
return unpack('!B', self.rea... | class FlvReader(io.BytesIO):
# Utility functions for reading numbers and strings
def read_unsigned_long_long(self):
return struct_unpack('!Q', self.read(8))[0]
def read_unsigned_int(self):
return struct_unpack('!I', self.read(4))[0]
def read_unsigned_char(self):
return struct_... |
def write_flv_header(stream, metadata):
# Script data
stream.write(b'\x12')
# Size of the metadata with 3 bytes
stream.write(pack('!L', len(metadata))[1:])
stream.write(b'\x00\x00\x00\x00\x00\x00\x00')
stream.write(metadata)
# Magic numbers extracted from the output files produced by AdobeHD... | def write_flv_header(stream, metadata):
# Script data
stream.write(b'\x12')
# Size of the metadata with 3 bytes
stream.write(struct_pack('!L', len(metadata))[1:])
stream.write(b'\x00\x00\x00\x00\x00\x00\x00')
stream.write(metadata)
# Magic numbers extracted from the output files produced by ... |
import platform
import re
import ssl
import socket
import subprocess
import sys
import traceback | import platform
import re
import ssl
import socket
import struct
import subprocess
import sys
import traceback |
def uppercase_escape(s):
return re.sub(
r'\\U([0-9a-fA-F]{8})',
lambda m: compat_chr(int(m.group(1), base=16)), s) | def uppercase_escape(s):
return re.sub(
r'\\U([0-9a-fA-F]{8})',
lambda m: compat_chr(int(m.group(1), base=16)), s)
try:
struct.pack(u'!I', 0)
except TypeError:
# In Python 2.6 (and some 2.7 versions), struct requires a bytes argument
def struct_pack(spec, *args):
if isinstance(s... |
class RangeIndex(Int64Index):
@Appender(_index_shared_docs["get_indexer"])
def get_indexer(self, target, method=None, limit=None, tolerance=None):
if not (method is None and tolerance is None and is_list_like(target)):
return super().get_indexer(target, method=method, tolerance=tolerance)
... | class RangeIndex(Int64Index):
@Appender(_index_shared_docs["get_indexer"])
def get_indexer(self, target, method=None, limit=None, tolerance=None):
if com.any_not_none(method, tolerance, limit) or not is_list_like(target):
return super().get_indexer(
target, method=method, to... |
class TestDataFrameIndexing(TestData):
assert mask[-5:].all()
assert not mask[:-5].any()
def test_set_dataframe_column_ns_dtype(self):
x = DataFrame([datetime.now(), datetime.now()])
assert x[0].dtype == np.dtype("M8[ns]") | class TestDataFrameIndexing(TestData):
assert mask[-5:].all()
assert not mask[:-5].any()
def test_reindex_limit(self):
# GH 28631
data = [["A", "A", "A"], ["B", "B", "B"], ["C", "C", "C"], ["D", "D", "D"]]
exp_data = [
["A", "A", "A"],
["B", "B", "B"]... |
class TestRangeIndex(Numeric):
expected = np.array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5], dtype=np.intp)
tm.assert_numpy_array_equal(indexer, expected)
def test_join_outer(self):
# join with Int64Index
other = Int64Index(np.arange(25, 14, -1)) | class TestRangeIndex(Numeric):
expected = np.array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5], dtype=np.intp)
tm.assert_numpy_array_equal(indexer, expected)
def test_get_indexer_limit(self):
# GH 28631
idx = RangeIndex(4)
target = RangeIndex(6)
result = idx.get_indexer(target, m... |
class TestJSInterpreter(unittest.TestCase):
}''')
self.assertEqual(jsi.call_function('x'), [20, 20, 30, 40, 50])
if __name__ == '__main__':
unittest.main() | class TestJSInterpreter(unittest.TestCase):
}''')
self.assertEqual(jsi.call_function('x'), [20, 20, 30, 40, 50])
def test_call(self):
jsi = JSInterpreter('''
function x() { return 2; }
function y(a) { return x() + a; }
function z() { return y(3); }
''')
... |
class JSInterpreter(object):
return opfunc(x, y)
m = re.match(
r'^(?P<func>%s)\((?P<args>[a-zA-Z0-9_$,]+)\)$' % _NAME_RE, expr)
if m:
fname = m.group('func')
argvals = tuple([
int(v) if v.isdigit() else local_vars[v]
for v ... | class JSInterpreter(object):
return opfunc(x, y)
m = re.match(
r'^(?P<func>%s)\((?P<args>[a-zA-Z0-9_$,]*)\)$' % _NAME_RE, expr)
if m:
fname = m.group('func')
argvals = tuple([
int(v) if v.isdigit() else local_vars[v]
for v ... |
"""
from os import path, listdir
import os
import sys
import errno
import marshal | """
from os import path, listdir
import os
import stat
import sys
import errno
import marshal |
class FileSystemBytecodeCache(BytecodeCache):
# On windows the temporary directory is used specific unless
# explicitly forced otherwise. We can just use that.
if os.name == 'n':
return tmpdir
if not hasattr(os, 'getuid'):
raise RuntimeError('Cannot determine sa... | class FileSystemBytecodeCache(BytecodeCache):
# On windows the temporary directory is used specific unless
# explicitly forced otherwise. We can just use that.
if os.name == 'nt':
return tmpdir
if not hasattr(os, 'getuid'):
raise RuntimeError('Cannot determine s... |
class FileSystemBytecodeCache(BytecodeCache):
dirname = '_jinja2-cache-%d' % os.getuid()
actual_dir = os.path.join(tmpdir, dirname)
try:
# 448 == 0700
os.mkdir(actual_dir, 448)
except OSError as e:
if e.errno != errno.EEXIST:
raise
... | class FileSystemBytecodeCache(BytecodeCache):
dirname = '_jinja2-cache-%d' % os.getuid()
actual_dir = os.path.join(tmpdir, dirname)
try:
os.mkdir(actual_dir, stat.S_IRWXU) # 0o700
except OSError as e:
if e.errno != errno.EEXIST:
raise
actu... |
class APIRouter(routing.Router):
assert not prefix.endswith(
"/"
), "A path prefix must not end with '/', as the routes will start with '/'"
for route in router.routes:
if isinstance(route, APIRoute):
if responses is None:
r... | class APIRouter(routing.Router):
assert not prefix.endswith(
"/"
), "A path prefix must not end with '/', as the routes will start with '/'"
if responses is None:
responses = {}
for route in router.routes:
if isinstance(route, APIRoute):
... |
class APIRouter(routing.Router):
summary=route.summary,
description=route.description,
response_description=route.response_description,
responses=responses,
deprecated=route.deprecated,
methods=route.... | class APIRouter(routing.Router):
summary=route.summary,
description=route.description,
response_description=route.response_description,
responses=combined_responses,
deprecated=route.deprecated,
metho... |
import time
from django.conf import settings
from django.db.backends.base.creation import BaseDatabaseCreation
from django.db.utils import DatabaseError
from django.utils.functional import cached_property
from django.utils.six.moves import input
TEST_DATABASE_PREFIX = 'test_'
PASSWORD = 'Im_a_lumberjack'
class Datab... | import time
from django.conf import settings
from django.db.backends.base.creation import BaseDatabaseCreation
from django.db.utils import DatabaseError
from django.utils.crypto import get_random_string
from django.utils.functional import cached_property
from django.utils.six.moves import input
TEST_DATABASE_PREFIX = ... |
class DatabaseCreation(BaseDatabaseCreation):
]
# Ignore "user already exists" error when keepdb is on
acceptable_ora_err = 'ORA-01920' if keepdb else None
self._execute_allow_fail_statements(cursor, statements, parameters, verbosity, acceptable_ora_err)
# Most test-suites can be... | class DatabaseCreation(BaseDatabaseCreation):
]
# Ignore "user already exists" error when keepdb is on
acceptable_ora_err = 'ORA-01920' if keepdb else None
success = self._execute_allow_fail_statements(cursor, statements, parameters, verbosity, acceptable_ora_err)
# If the passwo... |
class DatabaseCreation(BaseDatabaseCreation):
"""
settings_dict = self.connection.settings_dict
val = settings_dict['TEST'].get(key, default)
if val is None:
val = TEST_DATABASE_PREFIX + settings_dict[prefixed]
return val
| class DatabaseCreation(BaseDatabaseCreation):
"""
settings_dict = self.connection.settings_dict
val = settings_dict['TEST'].get(key, default)
if val is None and prefixed:
val = TEST_DATABASE_PREFIX + settings_dict[prefixed]
return val
|
class DatabaseCreation(BaseDatabaseCreation):
return self._test_settings_get('USER', prefixed='USER')
def _test_database_passwd(self):
return self._test_settings_get('PASSWORD', default=PASSWORD)
def _test_database_tblspace(self):
return self._test_settings_get('TBLSPACE', prefixed='US... | class DatabaseCreation(BaseDatabaseCreation):
return self._test_settings_get('USER', prefixed='USER')
def _test_database_passwd(self):
password = self._test_settings_get('PASSWORD')
if password is None and self._test_user_create():
# Oracle passwords are limited to 30 chars and ... |
def authenticate(username, password):
retval = PAM_AUTHENTICATE(handle, 0)
if retval == 0:
PAM_ACCT_MGMT(handle, 0)
PAM_END(handle, 0)
return retval == 0
| def authenticate(username, password):
retval = PAM_AUTHENTICATE(handle, 0)
if retval == 0:
retval = PAM_ACCT_MGMT(handle, 0)
PAM_END(handle, 0)
return retval == 0
|
import salt.utils.json
import salt.utils.stringutils
import salt.utils.url
import salt.utils.yaml
from jinja2 import BaseLoader, Markup, TemplateNotFound, nodes
from jinja2.environment import TemplateModule
from jinja2.exceptions import TemplateRuntimeError
from jinja2.ext import Extension | import salt.utils.json
import salt.utils.stringutils
import salt.utils.url
import salt.utils.yaml
from jinja2 import BaseLoader, TemplateNotFound, nodes
from jinja2.environment import TemplateModule
from jinja2.exceptions import TemplateRuntimeError
from jinja2.ext import Extension |
from salt.utils.decorators.jinja import jinja_filter, jinja_global, jinja_test
from salt.utils.odict import OrderedDict
from salt.utils.versions import LooseVersion
log = logging.getLogger(__name__)
__all__ = ["SaltCacheLoader", "SerializerExtension"] | from salt.utils.decorators.jinja import jinja_filter, jinja_global, jinja_test
from salt.utils.odict import OrderedDict
from salt.utils.versions import LooseVersion
try:
from markupsafe import Markup
except ImportError:
# jinja < 3.1
from jinja2 import Markup
log = logging.getLogger(__name__)
__all__ = [... |
def method_call(obj, f_name, *f_args, **f_kwargs):
return getattr(obj, f_name, lambda *args, **kwargs: None)(*f_args, **f_kwargs)
@jinja2.contextfunction
def show_full_context(ctx):
return salt.utils.data.simple_types_filter(
{key: value for key, value in ctx.items()} | def method_call(obj, f_name, *f_args, **f_kwargs):
return getattr(obj, f_name, lambda *args, **kwargs: None)(*f_args, **f_kwargs)
try:
contextfunction = jinja2.contextfunction
except AttributeError:
contextfunction = jinja2.pass_context
@contextfunction
def show_full_context(ctx):
return salt.utils.... |
def assert_series_equal(
f"is not equal to {right._values}."
)
raise AssertionError(msg)
elif is_interval_dtype(left.dtype) or is_interval_dtype(right.dtype):
assert_interval_array_equal(left.array, right.array)
elif is_categorical_dtype(left.dtype) or is_categori... | def assert_series_equal(
f"is not equal to {right._values}."
)
raise AssertionError(msg)
elif is_interval_dtype(left.dtype) and is_interval_dtype(right.dtype):
assert_interval_array_equal(left.array, right.array)
elif is_categorical_dtype(left.dtype) or is_categor... |
def assert_series_equal(
check_dtype=check_dtype,
obj=str(obj),
)
elif is_extension_array_dtype(left.dtype) or is_extension_array_dtype(right.dtype):
assert_extension_array_equal(left._values, right._values)
elif needs_i8_conversion(left.dtype) or needs_i8_conversion(righ... | def assert_series_equal(
check_dtype=check_dtype,
obj=str(obj),
)
elif is_extension_array_dtype(left.dtype) and is_extension_array_dtype(right.dtype):
assert_extension_array_equal(left._values, right._values)
elif needs_i8_conversion(left.dtype) or needs_i8_conversion(rig... |
import pytest
from pandas import DataFrame
import pandas._testing as tm
| import pytest
import pandas as pd
from pandas import DataFrame
import pandas._testing as tm
|
def test_frame_equal_unicode(df1, df2, msg, by_blocks_fixture, obj_fixture):
msg = msg.format(obj=obj_fixture)
with pytest.raises(AssertionError, match=msg):
tm.assert_frame_equal(df1, df2, by_blocks=by_blocks_fixture, obj=obj_fixture) | def test_frame_equal_unicode(df1, df2, msg, by_blocks_fixture, obj_fixture):
msg = msg.format(obj=obj_fixture)
with pytest.raises(AssertionError, match=msg):
tm.assert_frame_equal(df1, df2, by_blocks=by_blocks_fixture, obj=obj_fixture)
def test_assert_frame_equal_extension_dtype_mismatch():
# http... |
import pytest
from pandas import Categorical, DataFrame, Series
import pandas._testing as tm
| import pytest
import pandas as pd
from pandas import Categorical, DataFrame, Series
import pandas._testing as tm
|
ordered=False\\)"""
_assert_series_equal_both(s1, s2, check_categorical=check_categorical)
def test_series_equal_series_type():
class MySeries(Series):
pass | ordered=False\\)"""
_assert_series_equal_both(s1, s2, check_categorical=check_categorical)
def test_assert_series_equal_extension_dtype_mismatch():
# https://github.com/pandas-dev/pandas/issues/32747
left = Series(pd.array([1, 2, 3], dtype="Int64"))
right = left.astype(int)
msg = """Attribute... |
def test_sampleformat_not_corrupted(self):
out.seek(0)
with Image.open(out) as im:
im.load() | def test_sampleformat_not_corrupted(self):
out.seek(0)
with Image.open(out) as im:
im.load()
def test_realloc_overflow(self):
TiffImagePlugin.READ_LIBTIFF = True
with Image.open("Tests/images/tiff_overflow_rows_per_strip.tif") as im:
with self.assertRaises(IO... |
class TestUtil(unittest.TestCase):
inp = '''{"duration": "00:01:07"}'''
self.assertEqual(js_to_json(inp), '''{"duration": "00:01:07"}''')
def test_js_to_json_edgecases(self):
on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\... | class TestUtil(unittest.TestCase):
inp = '''{"duration": "00:01:07"}'''
self.assertEqual(js_to_json(inp), '''{"duration": "00:01:07"}''')
inp = '''{segments: [{"offset":-3.885780586188048e-16,"duration":39.75000000000001}]}'''
self.assertEqual(js_to_json(inp), '''{"segments": [{"offset"... |
class TestUtil(unittest.TestCase):
on = js_to_json('{/*comment\n*/42/*comment\n*/:/*comment\n*/42/*comment\n*/}')
self.assertEqual(json.loads(on), {'42': 42})
def test_extract_attributes(self):
self.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
self.assertEqual(extract_at... | class TestUtil(unittest.TestCase):
on = js_to_json('{/*comment\n*/42/*comment\n*/:/*comment\n*/42/*comment\n*/}')
self.assertEqual(json.loads(on), {'42': 42})
on = js_to_json('{42:4.2e1}')
self.assertEqual(json.loads(on), {'42': 42.0})
def test_extract_attributes(self):
sel... |
def js_to_json(code):
"(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"|
'(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
{comment}|,(?={skip}[\]}}])|
[a-zA-Z_][.a-zA-Z_0-9]*|
\b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:{skip}:)?|
[0-9]+(?={skip}:)
'''.format(comment=COMMENT_R... | def js_to_json(code):
"(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"|
'(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
{comment}|,(?={skip}[\]}}])|
(?:(?<![0-9])[eE]|[a-df-zA-DF-Z_])[.a-zA-Z_0-9]*|
\b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:{skip}:)?|
[0-9]+(?={skip}:)
'''... |
from pandas.errors import AbstractMethodError
from pandas import DataFrame, get_option
from pandas.io.common import get_filepath_or_buffer, is_s3_url
def get_engine(engine): | from pandas.errors import AbstractMethodError
from pandas import DataFrame, get_option
from pandas.io.common import get_filepath_or_buffer, is_gcs_url, is_s3_url
def get_engine(engine): |
class FastParquetImpl(BaseImpl):
if partition_cols is not None:
kwargs["file_scheme"] = "hive"
if is_s3_url(path):
# path is s3:// so we need to open the s3file in 'wb' mode.
# TODO: Support 'ab'
path, _, _, _ = get_filepath_or_buffer(path, mode="wb")
... | class FastParquetImpl(BaseImpl):
if partition_cols is not None:
kwargs["file_scheme"] = "hive"
if is_s3_url(path) or is_gcs_url(path):
# if path is s3:// or gs:// we need to open the file in 'wb' mode.
# TODO: Support 'ab'
path, _, _, _ = get_filepath_or... |
from io import StringIO
import numpy as np
import pytest | from io import StringIO
import os
import numpy as np
import pytest |
def test_to_csv_gcs(monkeypatch):
assert_frame_equal(df1, df2)
@td.skip_if_no("gcsfs")
def test_gcs_get_filepath_or_buffer(monkeypatch):
df1 = DataFrame( | def test_to_csv_gcs(monkeypatch):
assert_frame_equal(df1, df2)
@td.skip_if_no("fastparquet")
@td.skip_if_no("gcsfs")
def test_to_parquet_gcs_new_file(monkeypatch, tmpdir):
"""Regression test for writing to a not-yet-existent GCS Parquet file."""
df1 = DataFrame(
{
"int": [1, 3],
... |
class CertificateError(ValueError):
pass
def _dnsname_to_pat(dn):
pats = []
for frag in dn.split(r'.'):
if frag == '*':
# When '*' is a fragment by itself, it matches a non-empty dotless
# fragment. | class CertificateError(ValueError):
pass
def _dnsname_to_pat(dn, max_wildcards=1):
pats = []
for frag in dn.split(r'.'):
if frag.count('*') > max_wildcards:
# Issue #17980: avoid denials of service by refusing more
# than one wildcard per fragment. A survery of established... |
def fail(cert, hostname):
self.assertRaises(ValueError, ssl.match_hostname, None, 'example.com')
self.assertRaises(ValueError, ssl.match_hostname, {}, 'example.com')
def test_server_side(self):
# server_hostname doesn't work for server sockets
ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv2... | def fail(cert, hostname):
self.assertRaises(ValueError, ssl.match_hostname, None, 'example.com')
self.assertRaises(ValueError, ssl.match_hostname, {}, 'example.com')
# Issue #17980: avoid denials of service by refusing more than one
# wildcard per fragment.
cert = {'subject': ((... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.