buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
class BinGrouper(BaseGrouper):
ngroups,
)
@cache_readonly
def result_index(self):
if len(self.binlabels) != 0 and isna(self.binlabels[0]): | class BinGrouper(BaseGrouper):
ngroups,
)
@cache_readonly
def recons_codes(self):
# get unique result indices, and prepend 0 as groupby starts from the first
return [np.r_[0, np.flatnonzero(self.bins[1:] != self.bins[:-1]) + 1]]
@cache_readonly
def result_index(self... |
from itertools import product
import numpy as np
import pytest
from pandas import DataFrame, MultiIndex, Series, date_range
import pandas.util.testing as tm
| from itertools import product
import numpy as np
import pytest
from pandas import DataFrame, Grouper, MultiIndex, Series, date_range, to_datetime
import pandas.util.testing as tm
|
def test_series_groupby_value_counts(
# have to sort on index because of unstable sort on values
left, right = map(rebuild_index, (left, right)) # xref GH9212
tm.assert_series_equal(left.sort_index(), right.sort_index()) | def test_series_groupby_value_counts(
# have to sort on index because of unstable sort on values
left, right = map(rebuild_index, (left, right)) # xref GH9212
tm.assert_series_equal(left.sort_index(), right.sort_index())
def test_series_groupby_value_counts_with_grouper():
# GH28479
df = DataFram... |
class Sanic:
if _rn not in self.named_response_middleware:
self.named_response_middleware[_rn] = deque()
if middleware not in self.named_response_middleware[_rn]:
self.named_response_middleware[_rn].append(middleware)
# Decorator
def middl... | class Sanic:
if _rn not in self.named_response_middleware:
self.named_response_middleware[_rn] = deque()
if middleware not in self.named_response_middleware[_rn]:
self.named_response_middleware[_rn].appendleft(middleware)
# Decorator
def m... |
def test_several_bp_with_host(app):
def test_bp_middleware(app):
blueprint = Blueprint("test_middleware")
@blueprint.middleware("response")
async def process_response(request, response): | def test_several_bp_with_host(app):
def test_bp_middleware(app):
blueprint = Blueprint("test_bp_middleware")
@blueprint.middleware("response")
async def process_response(request, response): |
def test_bp_middleware(app):
assert response.status == 200
assert response.text == "FAIL"
def test_bp_exception_handler(app):
blueprint = Blueprint("test_middleware") | def test_bp_middleware(app):
assert response.status == 200
assert response.text == "FAIL"
def test_bp_middleware_order(app):
blueprint = Blueprint("test_bp_middleware_order")
order = list()
@blueprint.middleware("request")
def mw_1(request):
order.append(1)
@blueprint.middleware("re... |
setup(
python_requires="~=3.6",
install_requires=[
"urwid>=1.1.1",
"pygments>=1.0",
"jedi>=0.18,<1"
],
test_requires=[ | setup(
python_requires="~=3.6",
install_requires=[
"urwid>=1.1.1",
"pygments>=2.7.4",
"jedi>=0.18,<1"
],
test_requires=[ |
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):
... |
class ImageDataGenerator(object):
# Returns
The inputs, normalized.
"""
if self.preprocessing_function:
x = self.preprocessing_function(x)
if self.rescale:
x *= self.rescale
if self.samplewise_center: | class ImageDataGenerator(object):
# Returns
The inputs, normalized.
"""
if self.rescale:
x *= self.rescale
if self.samplewise_center: |
class NumpyArrayIterator(Iterator):
dtype=K.floatx())
for i, j in enumerate(index_array):
x = self.x[j]
x = self.image_data_generator.random_transform(x.astype(K.floatx()))
x = self.image_data_generator.standardize(x)
batch_x[i] = x | class NumpyArrayIterator(Iterator):
dtype=K.floatx())
for i, j in enumerate(index_array):
x = self.x[j]
if self.image_data_generator.preprocessing_function:
x = self.image_data_generator.preprocessing_function(x)
x = self.image_data_... |
class DirectoryIterator(Iterator):
fname = self.filenames[j]
img = load_img(os.path.join(self.directory, fname),
grayscale=grayscale,
target_size=self.target_size,
interpolation=self.interpolation)
x = i... | class DirectoryIterator(Iterator):
fname = self.filenames[j]
img = load_img(os.path.join(self.directory, fname),
grayscale=grayscale,
target_size=None,
interpolation=self.interpolation)
if self.image_dat... |
class TestImage(object):
with pytest.raises(ValueError):
x1, y1 = dir_seq[9]
def test_directory_iterator_class_mode_input(self, tmpdir):
tmpdir.join('class-1').mkdir()
| class TestImage(object):
with pytest.raises(ValueError):
x1, y1 = dir_seq[9]
# Test Preprocessing before resize
def preprocess_test(img):
return img.resize((1, 1))
generator = image.ImageDataGenerator(preprocessing_function=preprocess_test)
dir_seq = gen... |
commands:
- string
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.connection import exec_command
from ansible.module_utils.network.ios.ios import load_config
from ansible.module_utils.network.ios.ios import ios_argument_spec
import re
def map_obj_to_commands(updates, module): | commands:
- string
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.ios.ios import get_config, load_config
from ansible.module_utils.network.ios.ios import ios_argument_spec
from re import search, M
def map_obj_to_commands(updates, module): |
def map_obj_to_commands(updates, module):
if want['text'] and (want['text'] != have.get('text')):
banner_cmd = 'banner %s' % module.params['banner']
banner_cmd += ' @\n'
banner_cmd += want['text'].strip()
banner_cmd += '\n@'
commands.append(banner_cmd)... | def map_obj_to_commands(updates, module):
if want['text'] and (want['text'] != have.get('text')):
banner_cmd = 'banner %s' % module.params['banner']
banner_cmd += ' @\n'
banner_cmd += want['text'].strip('\n')
banner_cmd += '\n@'
commands.append(banner_... |
def map_obj_to_commands(updates, module):
def map_config_to_obj(module):
rc, out, err = exec_command(module, 'show banner %s' % module.params['banner'])
if rc == 0:
output = out
else:
rc, out, err = exec_command(module,
'show running-config | begin banne... | def map_obj_to_commands(updates, module):
def map_config_to_obj(module):
"""
This function gets the banner config without stripping any whitespaces,
and then fetches the required banner from it.
:param module:
:return: banner config dict object.
"""
out = get_config(module, flags='| begin ... |
def map_config_to_obj(module):
def map_params_to_obj(module):
text = module.params['text']
if text:
text = str(text).strip()
return {
'banner': module.params['banner'],
'text': text, | def map_config_to_obj(module):
def map_params_to_obj(module):
text = module.params['text']
return {
'banner': module.params['banner'],
'text': text, |
class TestIosBannerModule(TestIosModule):
def setUp(self):
super(TestIosBannerModule, self).setUp()
self.mock_exec_command = patch('ansible.modules.network.ios.ios_banner.exec_command')
self.exec_command = self.mock_exec_command.start()
self.mock_load_config = patch('ansible.module... | class TestIosBannerModule(TestIosModule):
def setUp(self):
super(TestIosBannerModule, self).setUp()
self.mock_get_config = patch('ansible.modules.network.ios.ios_banner.get_config')
self.get_config = self.mock_get_config.start()
self.mock_load_config = patch('ansible.modules.networ... |
class TestIosBannerModule(TestIosModule):
self.execute_module(changed=True, commands=commands)
def test_ios_banner_nochange(self):
banner_text = load_fixture('ios_banner_show_banner.txt').strip()
set_module_args(dict(banner='login', text=banner_text))
self.execute_module()
class T... | class TestIosBannerModule(TestIosModule):
self.execute_module(changed=True, commands=commands)
def test_ios_banner_nochange(self):
banner_text = load_fixture('ios_banner_show_banner.txt')
set_module_args(dict(banner='login', text=banner_text))
self.execute_module()
class TestIosBa... |
def Ghostscript(tile, size, fp, scale=1):
status = gs.wait()
if status:
raise IOError("gs failed (status %d)" % status)
im = Image.core.open_ppm(outfile)
finally:
try:
os.unlink(outfile) | def Ghostscript(tile, size, fp, scale=1):
status = gs.wait()
if status:
raise IOError("gs failed (status %d)" % status)
im = Image.open(outfile)
im.load()
finally:
try:
os.unlink(outfile) |
def Ghostscript(tile, size, fp, scale=1):
except OSError:
pass
return im
class PSFile(object): | def Ghostscript(tile, size, fp, scale=1):
except OSError:
pass
return im.im.copy()
class PSFile(object): |
def _wedge():
return Image()._new(core.wedge("L"))
def new(mode, size, color=0):
""" | def _wedge():
return Image()._new(core.wedge("L"))
def _check_size(size):
"""
Common check to enforce type and sanity check on size tuples
:param size: Should be a 2 tuple of (width, height)
:returns: True, or raises a ValueError
"""
if not isinstance(size, tuple):
raise ValueErr... |
def new(mode, size, color=0):
:returns: An :py:class:`~PIL.Image.Image` object.
"""
if color is None:
# don't initialize
return Image()._new(core.new(mode, size)) | def new(mode, size, color=0):
:returns: An :py:class:`~PIL.Image.Image` object.
"""
_check_size(size)
if color is None:
# don't initialize
return Image()._new(core.new(mode, size)) |
def frombytes(mode, size, data, decoder_name="raw", *args):
:returns: An :py:class:`~PIL.Image.Image` object.
"""
# may pass tuple instead of argument list
if len(args) == 1 and isinstance(args[0], tuple):
args = args[0] | def frombytes(mode, size, data, decoder_name="raw", *args):
:returns: An :py:class:`~PIL.Image.Image` object.
"""
_check_size(size)
# may pass tuple instead of argument list
if len(args) == 1 and isinstance(args[0], tuple):
args = args[0] |
def frombuffer(mode, size, data, decoder_name="raw", *args):
.. versionadded:: 1.1.4
"""
# may pass tuple instead of argument list
if len(args) == 1 and isinstance(args[0], tuple):
args = args[0] | def frombuffer(mode, size, data, decoder_name="raw", *args):
.. versionadded:: 1.1.4
"""
_check_size(size)
# may pass tuple instead of argument list
if len(args) == 1 and isinstance(args[0], tuple):
args = args[0] |
def load(self):
if d == "raw" and a[0] == self.mode and a[0] in Image._MAPMODES:
try:
if hasattr(Image.core, "map"):
# use built-in mapper
self.map = Image.core.map(self.filename)
self.map.seek(o)
... | def load(self):
if d == "raw" and a[0] == self.mode and a[0] in Image._MAPMODES:
try:
if hasattr(Image.core, "map"):
# use built-in mapper WIN32 only
self.map = Image.core.map(self.filename)
self.map... |
def load(self):
o.close()
try:
try:
# fast
self.im = Image.core.open_ppm(outfile)
except:
# slightly slower
im = Image.open(outfile)
im.load()
self.im = im.im
finally:
... | def load(self):
o.close()
try:
_im = Image.open(outfile)
_im.load()
self.im = _im.im
finally:
try:
os.unlink(outfile) |
def load_djpeg(self):
raise ValueError("Invalid Filename")
try:
self.im = Image.core.open_ppm(path)
finally:
try:
os.unlink(path) | def load_djpeg(self):
raise ValueError("Invalid Filename")
try:
_im = Image.open(path)
_im.load()
self.im = _im.im
finally:
try:
os.unlink(path) |
def _open(self):
self.fp.tell(),
(rawmode, 0, 1))]
# ALTERNATIVE: load via builtin debug function
# self.im = Image.core.open_ppm(self.filename)
# self.mode = self.im.mode
# self.size = self.im.size
#
# ----------------------------------------... | def _open(self):
self.fp.tell(),
(rawmode, 0, 1))]
#
# -------------------------------------------------------------------- |
def test_truncated_file(self):
self.assertRaises(ValueError, lambda: Image.open(path))
if __name__ == '__main__':
unittest.main() | def test_truncated_file(self):
self.assertRaises(ValueError, lambda: Image.open(path))
def test_neg_ppm(self):
# Storage.c accepted negative values for xsize, ysize. the
# internal open_ppm function didn't check for sanity but it
# has been removed. The default opener doesn't acce... |
def test_effect_spread(self):
im3 = Image.open('Tests/images/effect_spread.png')
self.assert_image_similar(im2, im3, 110)
if __name__ == '__main__':
unittest.main() | def test_effect_spread(self):
im3 = Image.open('Tests/images/effect_spread.png')
self.assert_image_similar(im2, im3, 110)
def test_check_size(self):
# Checking that the _check_size function throws value errors when we want it to.
with self.assertRaises(ValueError):
Imag... |
Various other classes in this module support this usage:
from __future__ import division, absolute_import
__metaclass__ = type
from zope.interface import implementer
from twisted.python.compat import networkString | Various other classes in this module support this usage:
from __future__ import division, absolute_import
__metaclass__ = type
import re
from zope.interface import implementer
from twisted.python.compat import networkString |
class HTTPClientParser(HTTPParser):
@implementer(IClientRequest)
class Request:
""" | class HTTPClientParser(HTTPParser):
_VALID_METHOD = re.compile(
br"\A[%s]+\Z" % (
bytes().join(
(
b"!", b"#", b"$", b"%", b"&", b"'", b"*",
b"+", b"-", b".", b"^", b"_", b"`", b"|", b"~",
b"\x30-\x39",
b"\x41-\x5a",
... |
class Request:
connection, defaults to C{False}.
@type persistent: L{bool}
"""
self.method = method
self.uri = uri
self.headers = headers
self.bodyProducer = bodyProducer
self.persistent = persistent | class Request:
connection, defaults to C{False}.
@type persistent: L{bool}
"""
self.method = _ensureValidMethod(method)
self.uri = _ensureValidURI(uri)
self.headers = headers
self.bodyProducer = bodyProducer
self.persistent = persistent |
class Request:
# method would probably be good. It would be nice if this method
# weren't limited to issuing HTTP/1.1 requests.
requestLines = []
requestLines.append(b' '.join([self.method, self.uri,
b'HTTP/1.1\r\n']))
if not self.persistent:
requestLines... | class Request:
# method would probably be good. It would be nice if this method
# weren't limited to issuing HTTP/1.1 requests.
requestLines = []
requestLines.append(
b' '.join(
[
_ensureValidMethod(self.method),
_ensur... |
from twisted.web.iweb import UNKNOWN_LENGTH, IAgent, IBodyProducer, IResponse
from twisted.web.http_headers import Headers
from twisted.logger import Logger
class PartialDownloadError(error.Error):
""" | from twisted.web.iweb import UNKNOWN_LENGTH, IAgent, IBodyProducer, IResponse
from twisted.web.http_headers import Headers
from twisted.logger import Logger
from twisted.web._newclient import _ensureValidURI, _ensureValidMethod
class PartialDownloadError(error.Error):
""" |
class HTTPPageGetter(http.HTTPClient):
_completelyDone = True
_specialHeaders = set((b'host', b'user-agent', b'cookie', b'content-length'))
def connectionMade(self):
method = getattr(self.factory, 'method', b'GET')
self.sendCommand(method, self.factory.path)
if self.factory.scheme... | class HTTPPageGetter(http.HTTPClient):
_completelyDone = True
_specialHeaders = set(
(b'host', b'user-agent', b'cookie', b'content-length'),
)
def connectionMade(self):
method = _ensureValidMethod(getattr(self.factory, 'method', b'GET'))
self.sendCommand(method, _ensureValidUR... |
class HTTPClientFactory(protocol.ClientFactory):
# just in case a broken http/1.1 decides to keep connection alive
self.headers.setdefault(b"connection", b"close")
self.postdata = postdata
self.method = method
self.setURL(url)
| class HTTPClientFactory(protocol.ClientFactory):
# just in case a broken http/1.1 decides to keep connection alive
self.headers.setdefault(b"connection", b"close")
self.postdata = postdata
self.method = _ensureValidMethod(method)
self.setURL(url)
|
class HTTPClientFactory(protocol.ClientFactory):
return "<%s: %s>" % (self.__class__.__name__, self.url)
def setURL(self, url):
self.url = url
uri = URI.fromBytes(url)
if uri.scheme and uri.host: | class HTTPClientFactory(protocol.ClientFactory):
return "<%s: %s>" % (self.__class__.__name__, self.url)
def setURL(self, url):
_ensureValidURI(url.strip())
self.url = url
uri = URI.fromBytes(url)
if uri.scheme and uri.host: |
def _makeGetterFactory(url, factoryFactory, contextFactory=None,
@return: The factory created by C{factoryFactory}
"""
uri = URI.fromBytes(url)
factory = factoryFactory(url, *args, **kwargs)
if uri.scheme == b'https':
from twisted.internet import ssl | def _makeGetterFactory(url, factoryFactory, contextFactory=None,
@return: The factory created by C{factoryFactory}
"""
uri = URI.fromBytes(_ensureValidURI(url.strip()))
factory = factoryFactory(url, *args, **kwargs)
if uri.scheme == b'https':
from twisted.internet import ssl |
class _AgentBase(object):
if not isinstance(method, bytes):
raise TypeError('method={!r} is {}, but must be bytes'.format(
method, type(method)))
# Create minimal headers, if necessary:
if headers is None:
headers = Headers() | class _AgentBase(object):
if not isinstance(method, bytes):
raise TypeError('method={!r} is {}, but must be bytes'.format(
method, type(method)))
method = _ensureValidMethod(method)
# Create minimal headers, if necessary:
if headers is None:
... |
class Agent(_AgentBase):
@see: L{twisted.web.iweb.IAgent.request}
"""
parsedURI = URI.fromBytes(uri)
try:
endpoint = self._getEndpoint(parsedURI) | class Agent(_AgentBase):
@see: L{twisted.web.iweb.IAgent.request}
"""
uri = _ensureValidURI(uri.strip())
parsedURI = URI.fromBytes(uri)
try:
endpoint = self._getEndpoint(parsedURI) |
class ProxyAgent(_AgentBase):
"""
Issue a new request via the configured proxy.
"""
# Cache *all* connections under the same key, since we are only
# connecting to a single destination, the proxy:
key = ("http-proxy", self._proxyEndpoint) | class ProxyAgent(_AgentBase):
"""
Issue a new request via the configured proxy.
"""
uri = _ensureValidURI(uri.strip())
# Cache *all* connections under the same key, since we are only
# connecting to a single destination, the proxy:
key = ("http-proxy", self._prox... |
from io import BytesIO
from zope.interface.verify import verifyObject
from twisted.trial.unittest import TestCase
from twisted.web import client, error, http_headers
from twisted.web._newclient import RequestNotSent, RequestTransmissionFailed
from twisted.web._newclient import ResponseNeverReceived, ResponseFailed | from io import BytesIO
from zope.interface.verify import verifyObject
from twisted.trial.unittest import TestCase, SynchronousTestCase
from twisted.web import client, error, http_headers
from twisted.web._newclient import RequestNotSent, RequestTransmissionFailed
from twisted.web._newclient import ResponseNeverReceiv... |
from twisted.internet.endpoints import HostnameEndpoint
from twisted.test.proto_helpers import AccumulatingProtocol
from twisted.test.iosim import IOPump, FakeTransport
from twisted.test.test_sslverify import certificatesForAuthorityAndServer
from twisted.web.error import SchemeNotSupported
from twisted.logger import g... | from twisted.internet.endpoints import HostnameEndpoint
from twisted.test.proto_helpers import AccumulatingProtocol
from twisted.test.iosim import IOPump, FakeTransport
from twisted.test.test_sslverify import certificatesForAuthorityAndServer
from twisted.web.test.injectionhelpers import (
MethodInjectionTestsMixin... |
class AgentTests(TestCase, FakeReactorAndConnectMixin, AgentTestsMixin,
"""
Tests for the new HTTP client API provided by L{Agent}.
"""
def makeAgent(self):
"""
@return: a new L{twisted.web.client.Agent} instance | class AgentTests(TestCase, FakeReactorAndConnectMixin, AgentTestsMixin,
"""
Tests for the new HTTP client API provided by L{Agent}.
"""
def makeAgent(self):
"""
@return: a new L{twisted.web.client.Agent} instance |
class AgentTests(TestCase, FakeReactorAndConnectMixin, AgentTestsMixin,
class AgentHTTPSTests(TestCase, FakeReactorAndConnectMixin,
IntegrationTestingMixin):
""" | class AgentTests(TestCase, FakeReactorAndConnectMixin, AgentTestsMixin,
class AgentMethodInjectionTests(
FakeReactorAndConnectMixin,
MethodInjectionTestsMixin,
SynchronousTestCase,
):
"""
Test L{client.Agent} against HTTP method injections.
"""
def attemptRequestWithMalicious... |
class HostnameCachingHTTPSPolicyTests(TestCase):
self.assertEquals(5, len(policy._cache))
self.assertIn(hostn, policy._cache) | class HostnameCachingHTTPSPolicyTests(TestCase):
self.assertEquals(5, len(policy._cache))
self.assertIn(hostn, policy._cache)
class RequestMethodInjectionTests(
MethodInjectionTestsMixin,
SynchronousTestCase,
):
"""
Test L{client.Request} against HTTP method injections.
"... |
Tests for the old L{twisted.web.client} APIs, C{getPage} and friends.
from __future__ import division, absolute_import
import os
from errno import ENOSPC
| Tests for the old L{twisted.web.client} APIs, C{getPage} and friends.
from __future__ import division, absolute_import
import io
import os
from errno import ENOSPC
|
from twisted.trial import unittest, util
from twisted.web import server, client, error, resource
from twisted.web.static import Data
from twisted.web.util import Redirect
from twisted.internet import reactor, defer, interfaces
from twisted.python.filepath import FilePath
from twisted.protocols.policies import WrappingF... | from twisted.trial import unittest, util
from twisted.web import server, client, error, resource
from twisted.web.static import Data
from twisted.web.util import Redirect
from twisted.internet import address, reactor, defer, interfaces
from twisted.internet.protocol import ClientFactory
from twisted.python.filepath imp... |
from twisted import test
from twisted.logger import (globalLogPublisher, FilteringLogObserver,
LogLevelFilterPredicate, LogLevel, Logger)
serverPEM = FilePath(test.__file__).sibling('server.pem')
serverPEMPath = serverPEM.asBytesMode().path | from twisted import test
from twisted.logger import (globalLogPublisher, FilteringLogObserver,
LogLevelFilterPredicate, LogLevel, Logger)
from twisted.web.test.injectionhelpers import (
MethodInjectionTestsMixin,
URIInjectionTestsMixin,
)
serverPEM = FilePath(test.__file__).sibli... |
class DeprecationTests(unittest.TestCase):
L{client.HTTPDownloader} is deprecated.
"""
self._testDeprecatedClass("HTTPDownloader") | class DeprecationTests(unittest.TestCase):
L{client.HTTPDownloader} is deprecated.
"""
self._testDeprecatedClass("HTTPDownloader")
class GetPageMethodInjectionTests(
MethodInjectionTestsMixin,
unittest.SynchronousTestCase,
):
"""
Test L{client.getPage} against HTTP met... |
class HMACKey(Key):
invalid_strings = [
b'-----BEGIN PUBLIC KEY-----',
b'-----BEGIN CERTIFICATE-----',
b'ssh-rsa'
] | class HMACKey(Key):
invalid_strings = [
b'-----BEGIN PUBLIC KEY-----',
b'-----BEGIN RSA PUBLIC KEY-----',
b'-----BEGIN CERTIFICATE-----',
b'ssh-rsa'
] |
class TestHMACAlgorithm:
with pytest.raises(JOSEError):
HMACKey(key, ALGORITHMS.HS256)
key = "-----BEGIN CERTIFICATE-----"
with pytest.raises(JOSEError):
HMACKey(key, ALGORITHMS.HS256) | class TestHMACAlgorithm:
with pytest.raises(JOSEError):
HMACKey(key, ALGORITHMS.HS256)
key = "-----BEGIN RSA PUBLIC KEY-----"
with pytest.raises(JOSEError):
HMACKey(key, ALGORITHMS.HS256)
key = "-----BEGIN CERTIFICATE-----"
with pytest.raises(JOSEError):... |
class SimpleTaskState(object):
def get_necessary_tasks(self):
necessary_tasks = set()
for task in self.get_active_tasks():
if task.status not in (DONE, DISABLED) or \
getattr(task, 'scheduler_disable_time', None) is not None:
necessary_tasks.update(tas... | class SimpleTaskState(object):
def get_necessary_tasks(self):
necessary_tasks = set()
for task in self.get_active_tasks():
if task.status not in (DONE, DISABLED, UNKNOWN) or \
task.scheduler_disable_time is not None:
necessary_tasks.update(task.deps)
... |
from helpers import unittest
from nose.plugins.attrib import attr
import luigi.notifications
from luigi.scheduler import DISABLED, DONE, FAILED, PENDING, CentralPlannerScheduler
luigi.notifications.DEBUG = True
WORKER = 'myworker' | from helpers import unittest
from nose.plugins.attrib import attr
import luigi.notifications
from luigi.scheduler import DISABLED, DONE, FAILED, PENDING, \
UNKNOWN, CentralPlannerScheduler
luigi.notifications.DEBUG = True
WORKER = 'myworker' |
class CentralPlannerTest(unittest.TestCase):
self.assertTrue(0 <= res < NUM_PENDING)
self.sch.add_task(worker=WORKER, task_id=str(res), status=DONE)
if __name__ == '__main__':
unittest.main() | class CentralPlannerTest(unittest.TestCase):
self.assertTrue(0 <= res < NUM_PENDING)
self.sch.add_task(worker=WORKER, task_id=str(res), status=DONE)
def test_assistants_dont_nurture_finished_statuses(self):
"""
Assistants should not affect longevity of DONE tasks
Al... |
import json
from django import forms
from django.conf import settings
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 json
from django import forms
from django.conf import settings
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):
super().__init__(attrs={'class': 'vURLField', **(attrs or {})})
def get_context(self, name, value, attrs):
context = super().ge... | class AdminEmailInputWidget(forms.EmailInput):
class AdminURLFieldWidget(forms.URLInput):
template_name = 'admin/widgets/url.html'
def __init__(self, attrs=None, validator_class=URLValidator):
super().__init__(attrs={'class': 'vURLField', **(attrs or {})})
self.validator = validator_class()
... |
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!")']:
with self.subTest(url=invalid):
... |
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... |
class MultiPartParser:
remaining = len(stripped_chunk) % 4
while remaining != 0:
over_chunk = field_stream.read(4 - remaining)
stripped_chunk += b"".join(over_chunk.split())
... | class MultiPartParser:
remaining = len(stripped_chunk) % 4
while remaining != 0:
over_chunk = field_stream.read(4 - remaining)
if not over_chunk:
... |
class FileUploadTests(TestCase):
def test_big_base64_newlines_upload(self):
self._test_base64_upload("Big data" * 68000, encode=base64.encodebytes)
def test_unicode_file_name(self):
with sys_tempfile.TemporaryDirectory() as temp_dir:
# This file contains Chinese symbols and an accen... | class FileUploadTests(TestCase):
def test_big_base64_newlines_upload(self):
self._test_base64_upload("Big data" * 68000, encode=base64.encodebytes)
def test_base64_invalid_upload(self):
payload = client.FakePayload('\r\n'.join([
'--' + client.BOUNDARY,
'Content-Dispositi... |
https://support.sas.com/techsup/technote/ts140.pdf
"""
from collections import abc
from datetime import datetime
from io import BytesIO
import struct
import warnings
| https://support.sas.com/techsup/technote/ts140.pdf
"""
from collections import abc
from datetime import datetime
import struct
import warnings
|
class XportReader(abc.Iterator):
if isinstance(filepath_or_buffer, (str, bytes)):
self.filepath_or_buffer = open(filepath_or_buffer, "rb")
else:
# Copy to BytesIO, and ensure no encoding
contents = filepath_or_buffer.read()
try:
contents = ... | class XportReader(abc.Iterator):
if isinstance(filepath_or_buffer, (str, bytes)):
self.filepath_or_buffer = open(filepath_or_buffer, "rb")
else:
# Since xport files include non-text byte sequences, xport files
# should already be opened in binary mode in Python 3.
... |
class TestXport:
self.dirpath = datapath("io", "sas", "data")
self.file01 = os.path.join(self.dirpath, "DEMO_G.xpt")
self.file02 = os.path.join(self.dirpath, "SSHSV1_A.xpt")
self.file03 = os.path.join(self.dirpath, "DRXFCD_G.xpt")
self.file04 = os.path.join(self.dirpath, "paxraw_... | class TestXport:
self.dirpath = datapath("io", "sas", "data")
self.file01 = os.path.join(self.dirpath, "DEMO_G.xpt")
self.file02 = os.path.join(self.dirpath, "SSHSV1_A.xpt")
self.file02b = open(os.path.join(self.dirpath, "SSHSV1_A.xpt"), "rb")
self.file03 = os.path.join(self.dirp... |
class TestXport:
data = read_sas(self.file02)
tm.assert_frame_equal(data, data_csv)
def test_multiple_types(self):
# Test with DRXFCD_G.xpt (contains text and numeric variables)
| class TestXport:
data = read_sas(self.file02)
tm.assert_frame_equal(data, data_csv)
def test2_binary(self):
# Test with SSHSV1_A.xpt, read as a binary file
# Compare to this
data_csv = pd.read_csv(self.file02.replace(".xpt", ".csv"))
numeric_as_float(data_csv)
... |
try:
import pickle
except ImportError:
import cPickle as pickle
import marshal
import os
import socket | import base64
import hashlib
import hmac
try:
import cPickle as pickle
except ImportError:
import pickle
import marshal
import os
import socket |
import tempfile
import threading
class PythonFileRunner(object):
"""A class for running python project files"""
| import tempfile
import threading
def _compat_compare_digest(a, b):
"""Implementation of hmac.compare_digest for python < 2.7.7.
This function uses an approach designed to prevent timing analysis by
avoiding content-based short circuiting behaviour, making it appropriate
for cryptography.
"""
... |
class _SocketReceiver(_MessageReceiver):
def __init__(self):
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.data_port = 3037
while self.data_port < 4000:
try:
self.server_socket.bind(('', self.data_port))
break
... | class _SocketReceiver(_MessageReceiver):
def __init__(self):
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.data_port = 3037
self.key = os.urandom(32)
while self.data_port < 4000:
try:
self.server_socket.bind(('localhost', sel... |
def __rope_start_everything():
import sys
import socket
try:
import pickle
except ImportError:
import cPickle as pickle
import marshal
import inspect
import types
import threading
import rope.base.utils.pycompat as pycompat
class _MessageSender(object):
| def __rope_start_everything():
import sys
import socket
try:
import cPickle as pickle
except ImportError:
import pickle
import marshal
import inspect
import types
import threading
import rope.base.utils.pycompat as pycompat
import base64
import hashlib
imp... |
def __rope_start_everything():
class _SocketSender(_MessageSender):
def __init__(self, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', port))
self.my_file = s.makefile('wb')
def send_data(self, data):
if not self... | def __rope_start_everything():
class _SocketSender(_MessageSender):
def __init__(self, port, key):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', port))
self.my_file = s.makefile('wb')
self.key = base64.b64decode(key)
... |
def __rope_start_everything():
def __init__(self, send_info, project_root):
self.project_root = project_root
if send_info.isdigit():
self.sender = _SocketSender(int(send_info))
else:
self.sender = _FileSender(send_info)
| def __rope_start_everything():
def __init__(self, send_info, project_root):
self.project_root = project_root
if send_info[0].isdigit():
port, key = send_info.split(':', 1)
self.sender = _SocketSender(int(port), key)
else:
self.... |
from rope.base.exceptions import ModuleNotFoundError
from rope.base.resources import File, Folder, _ResourceMatcher
try:
import pickle
except ImportError:
import cPickle as pickle
class _Project(object): | from rope.base.exceptions import ModuleNotFoundError
from rope.base.resources import File, Folder, _ResourceMatcher
try:
import cPickle as pickle
except ImportError:
import pickle
class _Project(object): |
except ImportError:
import ropetest.projecttest
import ropetest.codeanalyzetest
import ropetest.type_hinting_test
import ropetest.pycoretest
import ropetest.pyscopestest | except ImportError:
import ropetest.projecttest
import ropetest.codeanalyzetest
import ropetest.doatest
import ropetest.type_hinting_test
import ropetest.pycoretest
import ropetest.pyscopestest |
def suite():
result = unittest.TestSuite()
result.addTests(ropetest.projecttest.suite())
result.addTests(ropetest.codeanalyzetest.suite())
result.addTests(ropetest.type_hinting_test.suite())
result.addTests(ropetest.pycoretest.suite())
result.addTests(ropetest.pyscopestest.suite()) | def suite():
result = unittest.TestSuite()
result.addTests(ropetest.projecttest.suite())
result.addTests(ropetest.codeanalyzetest.suite())
result.addTests(ropetest.doatest.suite())
result.addTests(ropetest.type_hinting_test.suite())
result.addTests(ropetest.pycoretest.suite())
result.addTest... |
class RegexPattern(CheckURLMixin):
self.converters = {}
def match(self, path):
match = self.regex.search(path)
if match:
# If there are any named groups, use those as kwargs, ignoring
# non-named groups. Otherwise, pass all non-named arguments as | class RegexPattern(CheckURLMixin):
self.converters = {}
def match(self, path):
match = (
self.regex.fullmatch(path)
if self._is_endpoint and self.regex.pattern.endswith('$')
else self.regex.search(path)
)
if match:
# If there are any n... |
def _route_to_regex(route, is_endpoint=False):
converters[parameter] = converter
parts.append('(?P<' + parameter + '>' + converter.regex + ')')
if is_endpoint:
parts.append('$')
return ''.join(parts), converters
| def _route_to_regex(route, is_endpoint=False):
converters[parameter] = converter
parts.append('(?P<' + parameter + '>' + converter.regex + ')')
if is_endpoint:
parts.append(r'\Z')
return ''.join(parts), converters
|
class SimplifiedURLTests(SimpleTestCase):
with self.assertRaisesMessage(ImproperlyConfigured, msg):
path('space/<int: num>', empty_view)
@override_settings(ROOT_URLCONF='urlpatterns.converter_urls')
class ConverterTests(SimpleTestCase): | class SimplifiedURLTests(SimpleTestCase):
with self.assertRaisesMessage(ImproperlyConfigured, msg):
path('space/<int: num>', empty_view)
def test_path_trailing_newlines(self):
tests = [
'/articles/2003/\n',
'/articles/2010/\n',
'/en/foo/\n',
... |
class TunnelingTCP4ClientEndpoint(TCP4ClientEndpoint):
for it.
"""
_responseMatcher = re.compile('HTTP/1\.. 200')
def __init__(self, reactor, host, port, proxyConf, contextFactory,
timeout=30, bindAddress=None): | class TunnelingTCP4ClientEndpoint(TCP4ClientEndpoint):
for it.
"""
_responseMatcher = re.compile(b'HTTP/1\.. 200')
def __init__(self, reactor, host, port, proxyConf, contextFactory,
timeout=30, bindAddress=None): |
class TunnelingTCP4ClientEndpoint(TCP4ClientEndpoint):
def requestTunnel(self, protocol):
"""Asks the proxy to open a tunnel."""
tunnelReq = 'CONNECT %s:%s HTTP/1.1\r\n' % (self._tunneledHost,
self._tunneledPort)
if self._proxyAuthHeader:
... | class TunnelingTCP4ClientEndpoint(TCP4ClientEndpoint):
def requestTunnel(self, protocol):
"""Asks the proxy to open a tunnel."""
tunnelReq = (
b'CONNECT ' +
to_bytes(self._tunneledHost, encoding='ascii') + b':' +
to_bytes(str(self._tunneledPort)) +
b'... |
class HttpProxyTestCase(unittest.TestCase):
request = Request('https://example.com', meta={'proxy': http_proxy})
return self.download_request(request, Spider('foo')).addCallback(_test)
def test_download_without_proxy(self):
def _test(response):
self.assertEquals(response.status,... | class HttpProxyTestCase(unittest.TestCase):
request = Request('https://example.com', meta={'proxy': http_proxy})
return self.download_request(request, Spider('foo')).addCallback(_test)
@defer.inlineCallbacks
def test_download_with_proxy_https_timeout(self):
http_proxy = self.getURL('')
... |
def add_codes(err_cls):
class ErrorsWithCodes(object):
def __getattribute__(self, code):
msg = getattr(err_cls, code)
return "[{code}] {msg}".format(code=code, msg=msg)
return ErrorsWithCodes()
| def add_codes(err_cls):
class ErrorsWithCodes(object):
def __getattribute__(self, code):
if not code.startswith('__'):
msg = getattr(err_cls, code)
return "[{code}] {msg}".format(code=code, msg=msg)
else:
return super().__getattribute_... |
class IcnsFile:
i = HEADERSIZE
while i < filesize:
sig, blocksize = nextheader(fobj)
i = i + HEADERSIZE
blocksize = blocksize - HEADERSIZE
dct[sig] = (i, blocksize) | class IcnsFile:
i = HEADERSIZE
while i < filesize:
sig, blocksize = nextheader(fobj)
if blocksize <= 0:
raise SyntaxError('invalid block header')
i = i + HEADERSIZE
blocksize = blocksize - HEADERSIZE
dct[sig] = (i, blocksize) |
class StringMethods(NoNewAttributesMixin):
_doc_args["istitle"] = dict(type="titlecase", method="istitle")
_doc_args["isnumeric"] = dict(type="numeric", method="isnumeric")
_doc_args["isdecimal"] = dict(type="decimal", method="isdecimal")
isalnum = _noarg_wrapper(
lambda x: x.isalnum(),
... | class StringMethods(NoNewAttributesMixin):
_doc_args["istitle"] = dict(type="titlecase", method="istitle")
_doc_args["isnumeric"] = dict(type="numeric", method="isnumeric")
_doc_args["isdecimal"] = dict(type="decimal", method="isdecimal")
# force _noarg_wrapper return type with dtype=bool (GH 29624)
... |
class TestStringMethods:
tm.assert_series_equal(empty_str, empty.str.get(0))
tm.assert_series_equal(empty_str, empty_bytes.str.decode("ascii"))
tm.assert_series_equal(empty_bytes, empty.str.encode("ascii"))
tm.assert_series_equal(empty_str, empty.str.isalnum())
tm.assert_series_e... | class TestStringMethods:
tm.assert_series_equal(empty_str, empty.str.get(0))
tm.assert_series_equal(empty_str, empty_bytes.str.decode("ascii"))
tm.assert_series_equal(empty_bytes, empty.str.encode("ascii"))
# ismethods should always return boolean (GH 29624)
tm.assert_series_equa... |
HOST = test_support.HOST
CERTFILE = None
SVN_PYTHON_ORG_ROOT_CERT = None
def handle_error(prefix):
exc_format = ' '.join(traceback.format_exception(*sys.exc_info())) | HOST = test_support.HOST
CERTFILE = None
SVN_PYTHON_ORG_ROOT_CERT = None
NULLBYTECERT = None
def handle_error(prefix):
exc_format = ' '.join(traceback.format_exception(*sys.exc_info())) |
def test_parse_cert(self):
if test_support.verbose:
sys.stdout.write("\n" + pprint.pformat(p) + "\n")
def test_DER_to_PEM(self):
with open(SVN_PYTHON_ORG_ROOT_CERT, 'r') as f:
pem = f.read() | def test_parse_cert(self):
if test_support.verbose:
sys.stdout.write("\n" + pprint.pformat(p) + "\n")
def test_parse_cert_CVE_2013_4073(self):
p = ssl._ssl._test_decode_cert(NULLBYTECERT)
if test_support.verbose:
sys.stdout.write("\n" + pprint.pformat(p) + "\n")
... |
def test_main(verbose=False):
if skip_expected:
raise test_support.TestSkipped("No SSL support")
global CERTFILE, SVN_PYTHON_ORG_ROOT_CERT
CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir,
"keycert.pem")
SVN_PYTHON_ORG_ROOT_CERT = os.path.join(
... | def test_main(verbose=False):
if skip_expected:
raise test_support.TestSkipped("No SSL support")
global CERTFILE, SVN_PYTHON_ORG_ROOT_CERT, NULLBYTECERT
CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir,
"keycert.pem")
SVN_PYTHON_ORG_ROOT_CERT = os.path.... |
def nanstd(values, axis=None, skipna=True, ddof=1, mask=None):
>>> nanops.nanstd(s)
1.0
"""
result = np.sqrt(nanvar(values, axis=axis, skipna=skipna, ddof=ddof, mask=mask))
return _wrap_results(result, values.dtype)
@disallow("M8")
@bottleneck_switch(ddof=1)
def nanvar(values, axis=None, skipna=Tr... | def nanstd(values, axis=None, skipna=True, ddof=1, mask=None):
>>> nanops.nanstd(s)
1.0
"""
orig_dtype = values.dtype
values, mask, dtype, dtype_max, fill_value = _get_values(values, skipna, mask=mask)
result = np.sqrt(nanvar(values, axis=axis, skipna=skipna, ddof=ddof, mask=mask))
return _... |
class Series(base.IndexOpsMixin, generic.NDFrame):
If we have an ndarray as a value, then simply perform the operation,
otherwise delegate to the object.
"""
delegate = self._values
if axis is not None: | class Series(base.IndexOpsMixin, generic.NDFrame):
If we have an ndarray as a value, then simply perform the operation,
otherwise delegate to the object.
"""
delegate = self._values
if axis is not None: |
class TestIndexReductions:
assert result[0] == expected
# invalid ops
for op in ["skew", "kurt", "sem", "prod"]:
msg = "reduction operation '{}' not allowed for this dtype"
with pytest.raises(TypeError, match=msg.format(op)):
getattr(td, op)()
# ... | class TestIndexReductions:
assert result[0] == expected
# invalid ops
for op in ["skew", "kurt", "sem", "prod", "var"]:
msg = "reduction operation '{}' not allowed for this dtype"
with pytest.raises(TypeError, match=msg.format(op)):
getattr(td, op)()
... |
class TestSeriesReductions:
assert pd.isna(result)
# timedelta64[ns]
result = getattr(Series(dtype="m8[ns]"), method)()
assert result is pd.NaT
def test_nansum_buglet(self):
ser = Series([1.0, np.nan], index=[0, 1]) | class TestSeriesReductions:
assert pd.isna(result)
# timedelta64[ns]
tdser = Series([], dtype="m8[ns]")
if method == "var":
with pytest.raises(TypeError, match="operation 'var' not allowed"):
getattr(tdser, method)()
else:
result = getattr... |
def __lt__(self, other):
return False
def __hash__(self):
return self._ip ^ self._prefixlen ^ int(self.network.network_address)
__reduce__ = _IPAddressBase.__reduce__
| def __lt__(self, other):
return False
def __hash__(self):
return hash((self._ip, self._prefixlen, int(self.network.network_address)))
__reduce__ = _IPAddressBase.__reduce__
|
def __lt__(self, other):
return False
def __hash__(self):
return self._ip ^ self._prefixlen ^ int(self.network.network_address)
__reduce__ = _IPAddressBase.__reduce__
| def __lt__(self, other):
return False
def __hash__(self):
return hash((self._ip, self._prefixlen, int(self.network.network_address)))
__reduce__ = _IPAddressBase.__reduce__
|
def testsixtofour(self):
sixtofouraddr.sixtofour)
self.assertFalse(bad_addr.sixtofour)
if __name__ == '__main__':
unittest.main() | def testsixtofour(self):
sixtofouraddr.sixtofour)
self.assertFalse(bad_addr.sixtofour)
# issue41004 Hash collisions in IPv4Interface and IPv6Interface
def testV4HashIsNotConstant(self):
ipv4_address1 = ipaddress.IPv4Interface("1.2.3.4")
ipv4_address2 = ipaddress... |
from __future__ import absolute_import
import datetime
import logging
import os | from __future__ import absolute_import
import re
import datetime
import logging
import os |
class ConnectionError(Exception):
# (ie test_recent_date is failing) update it to ~6 months before the current date.
RECENT_DATE = datetime.date(2019, 1, 1)
class DummyConnection(object):
"""Used to detect a failed ConnectionCls import.""" | class ConnectionError(Exception):
# (ie test_recent_date is failing) update it to ~6 months before the current date.
RECENT_DATE = datetime.date(2019, 1, 1)
_CONTAINS_CONTROL_CHAR_RE = re.compile(r"[^-!#$%&'*+.^_`|~0-9a-zA-Z]")
class DummyConnection(object):
"""Used to detect a failed ConnectionCls import.""" |
def connect(self):
conn = self._new_conn()
self._prepare_conn(conn)
def request_chunked(self, method, url, body=None, headers=None):
"""
Alternative to the common request method, which sends the | def connect(self):
conn = self._new_conn()
self._prepare_conn(conn)
def putrequest(self, method, url, *args, **kwargs):
"""Send a request to the server"""
match = _CONTAINS_CONTROL_CHAR_RE.search(method)
if match:
raise ValueError(
"Method cannot ... |
def test_dns_error(self):
with pytest.raises(MaxRetryError):
pool.request("GET", "/test", retries=2)
def test_percent_encode_invalid_target_chars(self):
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.request("GET", "/echo_params?q=\r&k=\n \n") | def test_dns_error(self):
with pytest.raises(MaxRetryError):
pool.request("GET", "/test", retries=2)
@pytest.mark.parametrize("char", [" ", "\r", "\n", "\x00"])
def test_invalid_method_not_allowed(self, char):
with pytest.raises(ValueError):
with HTTPConnectionPo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.