buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
class TestScatter:
with pytest.raises(ValueError):
plt.scatter([1, 2, 3], [1, 2, 3], color=[1, 2, 3])
def test_scatter_size_arg_size(self):
x = np.arange(4)
with pytest.raises(ValueError): | class TestScatter:
with pytest.raises(ValueError):
plt.scatter([1, 2, 3], [1, 2, 3], color=[1, 2, 3])
def test_scatter_unfilled(self):
coll = plt.scatter([0, 1, 2], [1, 3, 2], c=['0.1', '0.3', '0.5'],
marker=mmarkers.MarkerStyle('o', fillstyle='none'),
... |
class Model(Container):
@interfaces.legacy_generator_methods_support
def fit_generator(self,
generator,
steps_per_epoch,
epochs=1,
verbose=1,
callbacks=None, | class Model(Container):
@interfaces.legacy_generator_methods_support
def fit_generator(self,
generator,
steps_per_epoch=None,
epochs=1,
verbose=1,
callbacks=None, |
class Model(Container):
to yield from `generator` before declaring one epoch
finished and starting the next epoch. It should typically
be equal to the number of samples of your dataset
divided by the batch size. Not used if using `Sequence`.
ep... | class Model(Container):
to yield from `generator` before declaring one epoch
finished and starting the next epoch. It should typically
be equal to the number of samples of your dataset
divided by the batch size.
Optional for `Sequence`: if ... |
class Model(Container):
validation_steps: Only relevant if `validation_data`
is a generator. Total number of steps (batches of samples)
to yield from `generator` before stopping.
class_weight: Dictionary mapping class indices to a weight
for the cl... | class Model(Container):
validation_steps: Only relevant if `validation_data`
is a generator. Total number of steps (batches of samples)
to yield from `generator` before stopping.
Optional for `Sequence`: if unspecified, will use
the `len(valida... |
class Model(Container):
if do_validation:
self._make_test_function()
# python 2 has 'next', 3 has '__next__'
# avoid any explicit version checks
val_gen = (hasattr(validation_data, 'next') or
hasattr(validation_data, '__next__') or
isins... | class Model(Container):
if do_validation:
self._make_test_function()
is_sequence = isinstance(generator, Sequence)
if not is_sequence and use_multiprocessing and workers > 1:
warnings.warn(
UserWarning('Using a generator with `use_multiprocessing=True`'
... |
class Model(Container):
val_data += [0.]
for cbk in callbacks:
cbk.validation_data = val_data
is_sequence = isinstance(generator, Sequence)
if not is_sequence and use_multiprocessing and workers > 1:
warnings.warn(
UserWarning('Usin... | class Model(Container):
val_data += [0.]
for cbk in callbacks:
cbk.validation_data = val_data
enqueuer = None
try: |
class Model(Container):
return self.history
@interfaces.legacy_generator_methods_support
def evaluate_generator(self, generator, steps,
max_queue_size=10,
workers=1,
use_multiprocessing=False): | class Model(Container):
return self.history
@interfaces.legacy_generator_methods_support
def evaluate_generator(self, generator, steps=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False): |
class Model(Container):
when using multiprocessing.
steps: Total number of steps (batches of samples)
to yield from `generator` before stopping.
Not used if using Sequence.
max_queue_size: maximum size for the generator queue
worker... | class Model(Container):
when using multiprocessing.
steps: Total number of steps (batches of samples)
to yield from `generator` before stopping.
Optional for `Sequence`: if unspecified, will use
the `len(generator)` as a number of steps.
... |
class Model(Container):
' and multiple workers may duplicate your data.'
' Please consider using the`keras.utils.Sequence'
' class.'))
if is_sequence:
steps = len(generator)
enqueuer = None
try: | class Model(Container):
' and multiple workers may duplicate your data.'
' Please consider using the`keras.utils.Sequence'
' class.'))
if steps is None:
if is_sequence:
steps = len(generator)
... |
class Model(Container):
return averages
@interfaces.legacy_generator_methods_support
def predict_generator(self, generator, steps,
max_queue_size=10,
workers=1,
use_multiprocessing=False, | class Model(Container):
return averages
@interfaces.legacy_generator_methods_support
def predict_generator(self, generator, steps=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False, |
class Model(Container):
when using multiprocessing.
steps: Total number of steps (batches of samples)
to yield from `generator` before stopping.
Not used if using Sequence.
max_queue_size: Maximum size for the generator queue.
worke... | class Model(Container):
when using multiprocessing.
steps: Total number of steps (batches of samples)
to yield from `generator` before stopping.
Optional for `Sequence`: if unspecified, will use
the `len(generator)` as a number of steps.
... |
class Model(Container):
' and multiple workers may duplicate your data.'
' Please consider using the`keras.utils.Sequence'
' class.'))
if is_sequence:
steps = len(generator)
enqueuer = None
try: | class Model(Container):
' and multiple workers may duplicate your data.'
' Please consider using the`keras.utils.Sequence'
' class.'))
if steps is None:
if is_sequence:
steps = len(generator)
... |
class Sequential(Model):
@interfaces.legacy_generator_methods_support
def fit_generator(self, generator,
steps_per_epoch,
epochs=1,
verbose=1,
callbacks=None, | class Sequential(Model):
@interfaces.legacy_generator_methods_support
def fit_generator(self, generator,
steps_per_epoch=None,
epochs=1,
verbose=1,
callbacks=None, |
class Sequential(Model):
finished and starting the next epoch. It should typically
be equal to the number of samples of your dataset
divided by the batch size.
epochs: Integer, total number of iterations on the data.
Note that in conjunction wi... | class Sequential(Model):
finished and starting the next epoch. It should typically
be equal to the number of samples of your dataset
divided by the batch size.
Optional for `Sequence`: if unspecified, will use
the `len(generator)` as a numb... |
class Sequential(Model):
at the end of every epoch. It should typically
be equal to the number of samples of your
validation dataset divided by the batch size.
class_weight: Dictionary mapping class indices to a weight
for the class.
... | class Sequential(Model):
at the end of every epoch. It should typically
be equal to the number of samples of your
validation dataset divided by the batch size.
Optional for `Sequence`: if unspecified, will use
the `len(validation_data)` as ... |
class Sequential(Model):
initial_epoch=initial_epoch)
@interfaces.legacy_generator_methods_support
def evaluate_generator(self, generator, steps,
max_queue_size=10, workers=1,
use_multiprocessing=False):
"""Ev... | class Sequential(Model):
initial_epoch=initial_epoch)
@interfaces.legacy_generator_methods_support
def evaluate_generator(self, generator, steps=None,
max_queue_size=10, workers=1,
use_multiprocessing=False):
... |
class Sequential(Model):
or (inputs, targets, sample_weights)
steps: Total number of steps (batches of samples)
to yield from `generator` before stopping.
max_queue_size: maximum size for the generator queue
workers: maximum number of processes to spin... | class Sequential(Model):
or (inputs, targets, sample_weights)
steps: Total number of steps (batches of samples)
to yield from `generator` before stopping.
Optional for `Sequence`: if unspecified, will use
the `len(generator)` as a number of ste... |
class Sequential(Model):
use_multiprocessing=use_multiprocessing)
@interfaces.legacy_generator_methods_support
def predict_generator(self, generator, steps,
max_queue_size=10, workers=1,
use_multiprocessing=False, ... | class Sequential(Model):
use_multiprocessing=use_multiprocessing)
@interfaces.legacy_generator_methods_support
def predict_generator(self, generator, steps=None,
max_queue_size=10, workers=1,
use_multiprocessing=Fa... |
class Sequential(Model):
generator: generator yielding batches of input samples.
steps: Total number of steps (batches of samples)
to yield from `generator` before stopping.
max_queue_size: maximum size for the generator queue
workers: maximum number of pr... | class Sequential(Model):
generator: generator yielding batches of input samples.
steps: Total number of steps (batches of samples)
to yield from `generator` before stopping.
Optional for `Sequence`: if unspecified, will use
the `len(generator)` as ... |
def test_model_methods():
# test starting from non-zero initial epoch
trained_epochs = []
# define tracer callback
def on_epoch_begin(epoch, logs):
trained_epochs.append(epoch)
tracker_cb = LambdaCallback(on_epoch_begin=on_epoch_begin)
out = model.fit([input_a_np, input_b_np],
... | def test_model_methods():
# test starting from non-zero initial epoch
trained_epochs = []
trained_batches = []
# define tracer callback
def on_epoch_begin(epoch, logs):
trained_epochs.append(epoch)
def on_batch_begin(batch, logs):
trained_batches.append(batch)
tracker_cb ... |
def test_model_methods():
model.compile(optimizer, loss, metrics=[], loss_weights=loss_weights,
sample_weight_mode=None)
trained_epochs = []
out = model.fit_generator(generator=RandomSequence(3), steps_per_epoch=12, epochs=5,
initial_epoch=0, validation_data=R... | def test_model_methods():
model.compile(optimizer, loss, metrics=[], loss_weights=loss_weights,
sample_weight_mode=None)
trained_epochs = []
trained_batches = []
out = model.fit_generator(generator=RandomSequence(3), steps_per_epoch=3, epochs=5,
initial_ep... |
from pandas._libs.lib import infer_dtype
from pandas.core.dtypes.common import (
_NS_DTYPE,
ensure_int64,
is_categorical_dtype,
is_datetime64_dtype,
is_datetime64tz_dtype, | from pandas._libs.lib import infer_dtype
from pandas.core.dtypes.common import (
_NS_DTYPE,
ensure_int64,
is_bool_dtype,
is_categorical_dtype,
is_datetime64_dtype,
is_datetime64tz_dtype, |
def _bins_to_cuts(
def _coerce_to_type(x):
"""
if the passed data is of datetime/timedelta type,
this method converts it to numeric so that cut method can
handle it
"""
dtype = None | def _bins_to_cuts(
def _coerce_to_type(x):
"""
if the passed data is of datetime/timedelta or bool type,
this method converts it to numeric so that cut or qcut method can
handle it
"""
dtype = None |
def _coerce_to_type(x):
elif is_timedelta64_dtype(x):
x = to_timedelta(x)
dtype = np.dtype("timedelta64[ns]")
if dtype is not None:
# GH 19768: force NaT to NaN during integer conversion | def _coerce_to_type(x):
elif is_timedelta64_dtype(x):
x = to_timedelta(x)
dtype = np.dtype("timedelta64[ns]")
elif is_bool_dtype(x):
# GH 20303
x = x.astype(np.int64)
if dtype is not None:
# GH 19768: force NaT to NaN during integer conversion |
def test_timedelta_cut_roundtrip():
["0 days 23:57:07.200000", "2 days 00:00:00", "3 days 00:00:00"]
)
tm.assert_index_equal(result_bins, expected_bins) | def test_timedelta_cut_roundtrip():
["0 days 23:57:07.200000", "2 days 00:00:00", "3 days 00:00:00"]
)
tm.assert_index_equal(result_bins, expected_bins)
@pytest.mark.parametrize("bins", [6, 7])
@pytest.mark.parametrize(
"box, compare",
[
(Series, tm.assert_series_equal),
(np.ar... |
def test_date_like_qcut_bins(arg, expected_bins):
ser = Series(arg)
result, result_bins = qcut(ser, 2, retbins=True)
tm.assert_index_equal(result_bins, expected_bins) | def test_date_like_qcut_bins(arg, expected_bins):
ser = Series(arg)
result, result_bins = qcut(ser, 2, retbins=True)
tm.assert_index_equal(result_bins, expected_bins)
@pytest.mark.parametrize("bins", [6, 7])
@pytest.mark.parametrize(
"box, compare",
[
(Series, tm.assert_series_equal),
... |
'is_url', 'url_to_path', 'path_to_url',
'is_archive_file', 'unpack_vcs_link',
'unpack_file_url', 'is_vcs_url', 'is_file_url',
'unpack_http_url', 'unpack_url']
logger = logging.getLogger(__name__) | 'is_url', 'url_to_path', 'path_to_url',
'is_archive_file', 'unpack_vcs_link',
'unpack_file_url', 'is_vcs_url', 'is_file_url',
'unpack_http_url', 'unpack_url',
'parse_content_disposition', 'sanitize_content_filename']
logger = logging.getLogger(__name__) |
def unpack_url(
write_delete_marker_file(location)
def _download_http_url(
link, # type: Link
session, # type: PipSession | def unpack_url(
write_delete_marker_file(location)
def sanitize_content_filename(filename):
# type: (str) -> str
"""
Sanitize the "filename" value from a Content-Disposition header.
"""
return os.path.basename(filename)
def parse_content_disposition(content_disposition, default_filename)... |
def _download_http_url(
# Have a look at the Content-Disposition header for a better guess
content_disposition = resp.headers.get('content-disposition')
if content_disposition:
type, params = cgi.parse_header(content_disposition)
# We use ``or`` here because we don't want to use an "empty" v... | def _download_http_url(
# Have a look at the Content-Disposition header for a better guess
content_disposition = resp.headers.get('content-disposition')
if content_disposition:
filename = parse_content_disposition(content_disposition, filename)
ext = splitext(filename)[1]
if not ext:
... |
import pip
from pip._internal.download import (
CI_ENVIRONMENT_VARIABLES, MultiDomainBasicAuth, PipSession, SafeFileCache,
unpack_file_url, unpack_http_url, url_to_path,
)
from pip._internal.exceptions import HashMismatch | import pip
from pip._internal.download import (
CI_ENVIRONMENT_VARIABLES, MultiDomainBasicAuth, PipSession, SafeFileCache,
_download_http_url, parse_content_disposition, sanitize_content_filename,
unpack_file_url, unpack_http_url, url_to_path,
)
from pip._internal.exceptions import HashMismatch |
def test_unpack_http_url_bad_downloaded_checksum(mock_unpack_file):
rmtree(download_dir)
@pytest.mark.parametrize("url,win_expected,non_win_expected", [
('file:tmp', 'tmp', 'tmp'),
('file:c:/path/to/file', r'C:\path\to\file', 'c:/path/to/file'), | def test_unpack_http_url_bad_downloaded_checksum(mock_unpack_file):
rmtree(download_dir)
@pytest.mark.parametrize("filename, expected", [
('dir/file', 'file'),
('../file', 'file'),
('../../file', 'file'),
('../', ''),
('../..', '..'),
('/', ''),
])
def test_sanitize_content_filename(fi... |
class SitemapSpider(Spider):
def _parse_sitemap(self, response):
if response.url.endswith('/robots.txt'):
for url in sitemap_urls_from_robots(response.body):
yield Request(url, callback=self._parse_sitemap)
else:
body = self._get_sitemap_body(response) | class SitemapSpider(Spider):
def _parse_sitemap(self, response):
if response.url.endswith('/robots.txt'):
for url in sitemap_urls_from_robots(response.text):
yield Request(url, callback=self._parse_sitemap)
else:
body = self._get_sitemap_body(response) |
class SitemapSpiderTest(SpiderTest):
r = Response(url="http://www.example.com/sitemap.xml.gz", body=self.GZBODY)
self.assertSitemapBody(r, self.BODY)
class BaseSpiderDeprecationTest(unittest.TestCase):
| class SitemapSpiderTest(SpiderTest):
r = Response(url="http://www.example.com/sitemap.xml.gz", body=self.GZBODY)
self.assertSitemapBody(r, self.BODY)
def test_get_sitemap_urls_from_robotstxt(self):
robots = b"""# Sitemap files
Sitemap: http://example.com/sitemap.xml
Sitemap: http://example.... |
class StaticFileTest(WebTestCase):
self.assertEqual(response.headers.get("Content-Length"), "4")
self.assertEqual(response.headers.get("Content-Range"), "bytes 22-25/26")
def test_static_invalid_range(self):
response = self.get_and_head("/static/robots.txt", headers={"Range": "asdf"})
... | class StaticFileTest(WebTestCase):
self.assertEqual(response.headers.get("Content-Length"), "4")
self.assertEqual(response.headers.get("Content-Range"), "bytes 22-25/26")
def test_static_with_range_neg_past_start(self):
response = self.get_and_head(
"/static/robots.txt", headers... |
class StaticFileTest(WebTestCase):
self.assertEqual(response.code, 416)
self.assertEqual(response.headers.get("Content-Range"), "bytes */26")
def test_static_head(self):
response = self.fetch("/static/robots.txt", method="HEAD")
self.assertEqual(response.code, 200) | class StaticFileTest(WebTestCase):
self.assertEqual(response.code, 416)
self.assertEqual(response.headers.get("Content-Range"), "bytes */26")
def test_static_unsatisfiable_range_end_less_than_start(self):
response = self.get_and_head(
"/static/robots.txt", headers={"Range": "byt... |
class StaticFileHandler(RequestHandler):
size = self.get_content_size()
if request_range:
start, end = request_range
if (start is not None and start >= size) or end == 0:
# As per RFC 2616 14.35.1, a range is not satisfiable only: if
# the first re... | class StaticFileHandler(RequestHandler):
size = self.get_content_size()
if request_range:
start, end = request_range
if start is not None and start < 0:
start += size
if start < 0:
start = 0
if (
star... |
async def request_body_to_args(
for field in required_params:
value: Any = None
if received_body is not None:
if field.shape in sequence_shapes and isinstance(
received_body, FormData
):
value = received_body.getlist... | async def request_body_to_args(
for field in required_params:
value: Any = None
if received_body is not None:
if (
field.shape in sequence_shapes or field.type_ in sequence_types
) and isinstance(received_body, FormData):
... |
class MultiIndex(Index):
if len(uniques) < len(level_index):
# Remove unobserved levels from level_index
level_index = level_index.take(uniques)
if len(level_index):
grouper = level_index.take(codes) | class MultiIndex(Index):
if len(uniques) < len(level_index):
# Remove unobserved levels from level_index
level_index = level_index.take(uniques)
else:
# break references back to us so that setting the name
# on the output of a groupby doesn't reflect back ... |
def test_apply_series_return_dataframe_groups():
["17661101"], index=pd.DatetimeIndex(["2015-02-24"], name="day"), name="userId"
)
tm.assert_series_equal(result, expected) | def test_apply_series_return_dataframe_groups():
["17661101"], index=pd.DatetimeIndex(["2015-02-24"], name="day"), name="userId"
)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("category", [False, True])
def test_apply_multi_level_name(category):
# https://github.com/pandas-dev... |
'is_url', 'url_to_path', 'path_to_url',
'is_archive_file', 'unpack_vcs_link',
'unpack_file_url', 'is_vcs_url', 'is_file_url',
'unpack_http_url', 'unpack_url']
logger = logging.getLogger(__name__) | 'is_url', 'url_to_path', 'path_to_url',
'is_archive_file', 'unpack_vcs_link',
'unpack_file_url', 'is_vcs_url', 'is_file_url',
'unpack_http_url', 'unpack_url',
'parse_content_disposition', 'sanitize_content_filename']
logger = logging.getLogger(__name__) |
def unpack_url(
write_delete_marker_file(location)
def _download_http_url(
link, # type: Link
session, # type: PipSession | def unpack_url(
write_delete_marker_file(location)
def sanitize_content_filename(filename):
# type: (str) -> str
"""
Sanitize the "filename" value from a Content-Disposition header.
"""
return os.path.basename(filename)
def parse_content_disposition(content_disposition, default_filename)... |
def _download_http_url(
# Have a look at the Content-Disposition header for a better guess
content_disposition = resp.headers.get('content-disposition')
if content_disposition:
type, params = cgi.parse_header(content_disposition)
# We use ``or`` here because we don't want to use an "empty" v... | def _download_http_url(
# Have a look at the Content-Disposition header for a better guess
content_disposition = resp.headers.get('content-disposition')
if content_disposition:
filename = parse_content_disposition(content_disposition, filename)
ext = splitext(filename)[1]
if not ext:
... |
import pip
from pip._internal.download import (
CI_ENVIRONMENT_VARIABLES, MultiDomainBasicAuth, PipSession, SafeFileCache,
unpack_file_url, unpack_http_url, url_to_path,
)
from pip._internal.exceptions import HashMismatch | import pip
from pip._internal.download import (
CI_ENVIRONMENT_VARIABLES, MultiDomainBasicAuth, PipSession, SafeFileCache,
_download_http_url, parse_content_disposition, sanitize_content_filename,
unpack_file_url, unpack_http_url, url_to_path,
)
from pip._internal.exceptions import HashMismatch |
def test_unpack_http_url_bad_downloaded_checksum(mock_unpack_file):
rmtree(download_dir)
@pytest.mark.parametrize("url,win_expected,non_win_expected", [
('file:tmp', 'tmp', 'tmp'),
('file:c:/path/to/file', r'C:\path\to\file', 'c:/path/to/file'), | def test_unpack_http_url_bad_downloaded_checksum(mock_unpack_file):
rmtree(download_dir)
@pytest.mark.parametrize("filename, expected", [
('dir/file', 'file'),
('../file', 'file'),
('../../file', 'file'),
('../', ''),
('../..', '..'),
('/', ''),
])
def test_sanitize_content_filename(fi... |
from collections import namedtuple
from typing import Dict, List
from netaddr import IPSet
from synapse.config.server import DEFAULT_IP_RANGE_BLACKLIST
from synapse.python_dependencies import DependencyException, check_requirements
from synapse.util.module_loader import load_module
| from collections import namedtuple
from typing import Dict, List
from synapse.config.server import DEFAULT_IP_RANGE_BLACKLIST, generate_ip_set
from synapse.python_dependencies import DependencyException, check_requirements
from synapse.util.module_loader import load_module
|
def read_config(self, config, **kwargs):
"to work"
)
self.url_preview_ip_range_blacklist = IPSet(
config["url_preview_ip_range_blacklist"]
)
# we always blacklist '0.0.0.0' and '::', which are supposed to be
# unroutab... | def read_config(self, config, **kwargs):
"to work"
)
# we always blacklist '0.0.0.0' and '::', which are supposed to be
# unroutable addresses.
self.url_preview_ip_range_blacklist = generate_ip_set(
config["url_preview_ip_range_bla... |
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import os.path
import re | # See the License for the specific language governing permissions and
# limitations under the License.
import itertools
import logging
import os.path
import re |
import attr
import yaml
from netaddr import IPSet
from synapse.api.room_versions import KNOWN_ROOM_VERSIONS
from synapse.util.stringutils import parse_and_validate_server_name |
import attr
import yaml
from netaddr import AddrFormatError, IPNetwork, IPSet
from synapse.api.room_versions import KNOWN_ROOM_VERSIONS
from synapse.util.stringutils import parse_and_validate_server_name |
# in the list.
DEFAULT_BIND_ADDRESSES = ["::", "0.0.0.0"]
DEFAULT_IP_RANGE_BLACKLIST = [
# Localhost
"127.0.0.0/8", | # in the list.
DEFAULT_BIND_ADDRESSES = ["::", "0.0.0.0"]
def _6to4(network: IPNetwork) -> IPNetwork:
"""Convert an IPv4 network into a 6to4 IPv6 network per RFC 3056."""
# 6to4 networks consist of:
# * 2002 as the first 16 bits
# * The first IPv4 address in the network hex-encoded as the next 32 bit... |
"192.0.0.0/24",
# Link-local networks.
"169.254.0.0/16",
# Testing networks.
"198.18.0.0/15",
"192.0.2.0/24", | "192.0.0.0/24",
# Link-local networks.
"169.254.0.0/16",
# Formerly used for 6to4 relay.
"192.88.99.0/24",
# Testing networks.
"198.18.0.0/15",
"192.0.2.0/24", |
"fe80::/10",
# Unique local addresses.
"fc00::/7",
]
DEFAULT_ROOM_VERSION = "6" | "fe80::/10",
# Unique local addresses.
"fc00::/7",
# Testing networks.
"2001:db8::/32",
# Multicast.
"ff00::/8",
# Site-local addresses
"fec0::/10",
]
DEFAULT_ROOM_VERSION = "6" |
def read_config(self, config, **kwargs):
)
# Attempt to create an IPSet from the given ranges
try:
self.ip_range_blacklist = IPSet(ip_range_blacklist)
except Exception as e:
raise ConfigError("Invalid range(s) provided in ip_range_blacklist.") from e
# Al... | def read_config(self, config, **kwargs):
)
# Attempt to create an IPSet from the given ranges
# Always blacklist 0.0.0.0, ::
self.ip_range_blacklist = generate_ip_set(
ip_range_blacklist, ["0.0.0.0", "::"], config_path=("ip_range_blacklist",)
)
self.ip_rang... |
def read_config(self, config, **kwargs):
federation_ip_range_blacklist = config.get(
"federation_ip_range_blacklist", ip_range_blacklist
)
try:
self.federation_ip_range_blacklist = IPSet(federation_ip_range_blacklist)
except Exception as e:
raise Confi... | def read_config(self, config, **kwargs):
federation_ip_range_blacklist = config.get(
"federation_ip_range_blacklist", ip_range_blacklist
)
# Always blacklist 0.0.0.0, ::
self.federation_ip_range_blacklist = generate_ip_set(
federation_ip_range_blacklist,
... |
import yaml
from synapse.config.server import ServerConfig, is_threepid_reserved
from tests import unittest
|
import yaml
from synapse.config._base import ConfigError
from synapse.config.server import ServerConfig, generate_ip_set, is_threepid_reserved
from tests import unittest
|
def test_listeners_set_correctly_open_private_ports_true(self):
)
self.assertEqual(conf["listeners"], expected_listeners) | def test_listeners_set_correctly_open_private_ports_true(self):
)
self.assertEqual(conf["listeners"], expected_listeners)
class GenerateIpSetTestCase(unittest.TestCase):
def test_empty(self):
ip_set = generate_ip_set(())
self.assertFalse(ip_set)
ip_set = generate_ip_set((... |
def repercent_broken_unicode(path):
repercent-encode any octet produced that is not part of a strictly legal
UTF-8 octet sequence.
"""
try:
path.decode()
except UnicodeDecodeError as e:
repercent = quote(path[e.start:e.end], safe=b"/#%[]=:;$&()+,!?*@'~")
path = repercent_brok... | def repercent_broken_unicode(path):
repercent-encode any octet produced that is not part of a strictly legal
UTF-8 octet sequence.
"""
while True:
try:
path.decode()
except UnicodeDecodeError as e:
# CVE-2019-14235: A recursion shouldn't be used since the exceptio... |
import datetime
import unittest
from unittest import mock
from urllib.parse import quote_plus | import datetime
import sys
import unittest
from unittest import mock
from urllib.parse import quote_plus |
from urllib.parse import quote_plus
from django.test import SimpleTestCase
from django.utils.encoding import (
DjangoUnicodeDecodeError, escape_uri_path, filepath_to_uri, force_bytes,
force_str, get_system_encoding, iri_to_uri, smart_bytes, smart_str,
uri_to_iri,
)
from django.utils.functional import Simple... | from urllib.parse import quote_plus
from django.test import SimpleTestCase
from django.utils.encoding import (
DjangoUnicodeDecodeError, escape_uri_path, filepath_to_uri, force_bytes,
force_str, get_system_encoding, iri_to_uri, repercent_broken_unicode,
smart_bytes, smart_str, uri_to_iri,
)
from django.util... |
class TestEncodingUtils(SimpleTestCase):
with mock.patch('locale.getdefaultlocale', side_effect=Exception):
self.assertEqual(get_system_encoding(), 'ascii')
class TestRFC3987IEncodingUtils(unittest.TestCase):
| class TestEncodingUtils(SimpleTestCase):
with mock.patch('locale.getdefaultlocale', side_effect=Exception):
self.assertEqual(get_system_encoding(), 'ascii')
def test_repercent_broken_unicode_recursion_error(self):
# Prepare a string long enough to force a recursion error if the tested
... |
from pandas.core.dtypes.common import (
from pandas.core.dtypes.dtypes import IntervalDtype
from pandas.core.dtypes.generic import (
ABCDatetimeIndex,
ABCIndexClass,
ABCInterval,
ABCIntervalIndex, | from pandas.core.dtypes.common import (
from pandas.core.dtypes.dtypes import IntervalDtype
from pandas.core.dtypes.generic import (
ABCDatetimeIndex,
ABCExtensionArray,
ABCIndexClass,
ABCInterval,
ABCIntervalIndex, |
class IntervalArray(IntervalMixin, ExtensionArray):
# Avoid materializing self.values
return self.left.size
def take(self, indices, allow_fill=False, fill_value=None, axis=None, **kwargs):
"""
Take elements from the IntervalArray. | class IntervalArray(IntervalMixin, ExtensionArray):
# Avoid materializing self.values
return self.left.size
def shift(self, periods: int = 1, fill_value: object = None) -> ABCExtensionArray:
if not len(self) or periods == 0:
return self.copy()
if isna(fill_value):
... |
class TestMethods:
with pytest.raises(ValueError, match=match):
ser.where([True, False, True], other=other)
class TestSetitem:
def test_set_na(self, left_right_dtypes): | class TestMethods:
with pytest.raises(ValueError, match=match):
ser.where([True, False, True], other=other)
def test_shift(self):
# https://github.com/pandas-dev/pandas/issues/31495
a = IntervalArray.from_breaks([1, 2, 3])
result = a.shift()
# int -> float
... |
class BaseMethodsTests(BaseExtensionTests):
expected = empty
self.assert_extension_array_equal(result, expected)
def test_shift_fill_value(self, data):
arr = data[:4]
fill_value = data[0] | class BaseMethodsTests(BaseExtensionTests):
expected = empty
self.assert_extension_array_equal(result, expected)
def test_shift_zero_copies(self, data):
result = data.shift(0)
assert result is not data
result = data[:0].shift(2)
assert result is not data
def te... |
class Storage:
content = File(content, name)
name = self.get_available_name(name, max_length=max_length)
return self._save(name, content)
# These methods are part of the public API, with default implementations.
| class Storage:
content = File(content, name)
name = self.get_available_name(name, max_length=max_length)
name = self._save(name, content)
# Ensure that the name returned from the storage system is still valid.
validate_file_name(name, allow_relative_path=True)
return... |
class Storage:
Return a filename that's free on the target storage system and
available for new content to be written to.
"""
dir_name, file_name = os.path.split(name)
if '..' in pathlib.PurePath(dir_name).parts:
raise SuspiciousFileOperation("Detected path traversal ... | class Storage:
Return a filename that's free on the target storage system and
available for new content to be written to.
"""
name = str(name).replace('\\', '/')
dir_name, file_name = os.path.split(name)
if '..' in pathlib.PurePath(dir_name).parts:
raise Suspi... |
class Storage:
Validate the filename by calling get_valid_name() and return a filename
to be passed to the save() method.
"""
# `filename` may include a path as returned by FileField.upload_to.
dirname, filename = os.path.split(filename)
if '..' in pathlib.PurePath(dirnam... | class Storage:
Validate the filename by calling get_valid_name() and return a filename
to be passed to the save() method.
"""
filename = str(filename).replace('\\', '/')
# `filename` may include a path as returned by FileField.upload_to.
dirname, filename = os.path.split(... |
class FileSystemStorage(Storage):
if self.file_permissions_mode is not None:
os.chmod(full_path, self.file_permissions_mode)
# Store filenames with forward slashes, even on Windows.
return str(name).replace('\\', '/')
| class FileSystemStorage(Storage):
if self.file_permissions_mode is not None:
os.chmod(full_path, self.file_permissions_mode)
# Ensure the saved path is always relative to the storage root.
name = os.path.relpath(full_path, self.location)
# Store filenames with forward slashe... |
class GenerateFilenameStorageTests(SimpleTestCase):
s.generate_filename(file_name)
def test_storage_dangerous_paths_dir_name(self):
file_name = '/tmp/../path'
s = FileSystemStorage()
msg = "Detected path traversal attempt in '/tmp/..'"
with self.assertRaisesMessa... | class GenerateFilenameStorageTests(SimpleTestCase):
s.generate_filename(file_name)
def test_storage_dangerous_paths_dir_name(self):
candidates = [
('tmp/../path', 'tmp/..'),
('tmp\\..\\path', 'tmp/..'),
('/tmp/../path', '/tmp/..'),
('\\tmp... |
class FileStorageTests(SimpleTestCase):
self.storage.delete('path/to/test.file')
def test_save_doesnt_close(self):
with TemporaryUploadedFile('test', 'text/plain', 1, 'utf8') as file:
file.write(b'1') | class FileStorageTests(SimpleTestCase):
self.storage.delete('path/to/test.file')
def test_file_save_abs_path(self):
test_name = 'path/to/test.file'
f = ContentFile('file saved with path')
f_name = self.storage.save(os.path.join(self.temp_dir, test_name), f)
self.assertEqual... |
def do_setup():
scripts=['airflow/bin/airflow'],
install_requires=[
'alembic>=0.8.3, <0.9',
'bleach==2.1.2',
'configparser>=3.5.0, <3.6.0',
'croniter>=0.3.17, <0.4',
'dill>=0.2.2, <0.3', | def do_setup():
scripts=['airflow/bin/airflow'],
install_requires=[
'alembic>=0.8.3, <0.9',
'bleach~=2.1.3',
'configparser>=3.5.0, <3.6.0',
'croniter>=0.3.17, <0.4',
'dill>=0.2.2, <0.3', |
import inspect
import sys
PY3 = (sys.version_info[0] == 3)
if hasattr(abc, 'ABC'):
ABC = abc.ABC | import inspect
import sys
PY3 = (sys.version_info[0] == 3)
PY2 = not PY3
if hasattr(abc, 'ABC'):
ABC = abc.ABC |
import traceback
from .variables import CommonVariable, Exploding, BaseVariable
from . import utils, pycompat
ipython_filename_pattern = re.compile('^<ipython-input-([0-9]+)-.*>$') | import traceback
from .variables import CommonVariable, Exploding, BaseVariable
from . import utils, pycompat
if pycompat.PY2:
from io import open
ipython_filename_pattern = re.compile('^<ipython-input-([0-9]+)-.*>$') |
def get_source_from_frame(frame):
# apply tokenize.detect_encoding to decode the source into a
# string, then we should do that ourselves.
if isinstance(source[0], bytes):
encoding = 'ascii'
for line in source[:2]:
# File coding may be specified. Match pattern from PEP-263
... | def get_source_from_frame(frame):
# apply tokenize.detect_encoding to decode the source into a
# string, then we should do that ourselves.
if isinstance(source[0], bytes):
encoding = 'utf-8'
for line in source[:2]:
# File coding may be specified. Match pattern from PEP-263
... |
class FileWriter(object):
self.overwrite = overwrite
def write(self, s):
with open(self.path, 'w' if self.overwrite else 'a') as output_file:
output_file.write(s)
self.overwrite = False
| class FileWriter(object):
self.overwrite = overwrite
def write(self, s):
with open(self.path, 'w' if self.overwrite else 'a',
encoding='utf-8') as output_file:
output_file.write(s)
self.overwrite = False
|
def assert_output(output, expected_entries, prefix=None):
any_mismatch = False
result = ''
template = '\n{line!s:%s} {expected_entry} {arrow}' % max(map(len, lines))
for expected_entry, line in zip_longest(expected_entries, lines, fillvalue=""):
mismatch = not (expected_entry and expected_en... | def assert_output(output, expected_entries, prefix=None):
any_mismatch = False
result = ''
template = u'\n{line!s:%s} {expected_entry} {arrow}' % max(map(len, lines))
for expected_entry, line in zip_longest(expected_entries, lines, fillvalue=""):
mismatch = not (expected_entry and expected_e... |
def assert_sample_output(module):
with sys_tools.OutputCapturer(stdout=False,
stderr=True) as output_capturer:
module.main()
time = '21:10:42.298924'
time_pattern = re.sub(r'\d', r'\\d', time)
| def assert_sample_output(module):
with sys_tools.OutputCapturer(stdout=False,
stderr=True) as output_capturer:
module.main()
time = '21:10:42.298924'
time_pattern = re.sub(r'\d', r'\\d', time)
|
def __init__(self, host, port=None, strict=None,
(self.host, self.port) = self._get_hostport(host, port)
# This is stored as an instance variable to allow unittests
# to replace with a suitable mock
self._create_connection = socket.create_connection | def __init__(self, host, port=None, strict=None,
(self.host, self.port) = self._get_hostport(host, port)
self._validate_host(self.host)
# This is stored as an instance variable to allow unittests
# to replace with a suitable mock
self._create_connection = socket.create_connect... |
def _validate_path(self, url):
).format(matched=match.group(), url=url)
raise InvalidURL(msg)
def putheader(self, header, *values):
"""Send a request header line to the server.
| def _validate_path(self, url):
).format(matched=match.group(), url=url)
raise InvalidURL(msg)
def _validate_host(self, host):
"""Validate a host so it doesn't contain control characters."""
# Prevent CVE-2019-18348.
match = _contains_disallowed_url_pchar_re.search(ho... |
def test_proxy_tunnel_without_status_line(self):
with self.assertRaisesRegexp(socket.error, "Invalid response"):
conn._tunnel()
def test_putrequest_override_validation(self):
"""
It should be possible to override the default validation
behavior in putrequest (bpo-38216). | def test_proxy_tunnel_without_status_line(self):
with self.assertRaisesRegexp(socket.error, "Invalid response"):
conn._tunnel()
def test_putrequest_override_domain_validation(self):
"""
It should be possible to override the default validation
behavior in putrequest (bpo-... |
def _validate_path(self, url):
conn.sock = FakeSocket('')
conn.putrequest('GET', '/\x00')
class OfflineTest(TestCase):
def test_responses(self): | def _validate_path(self, url):
conn.sock = FakeSocket('')
conn.putrequest('GET', '/\x00')
def test_putrequest_override_host_validation(self):
class UnsafeHTTPConnection(httplib.HTTPConnection):
def _validate_host(self, url):
pass
conn = UnsafeHTTPConnect... |
def test_unsupported_algorithm(self):
)
@unittest.skipUnless(ssl, "ssl module required")
def test_url_with_control_char_rejected(self):
for char_no in range(0, 0x21) + range(0x7f, 0x100):
char = chr(char_no)
schemeless_url = "//localhost:7777/test%s/" % char | def test_unsupported_algorithm(self):
)
@unittest.skipUnless(ssl, "ssl module required")
def test_url_path_with_control_char_rejected(self):
for char_no in range(0, 0x21) + range(0x7f, 0x100):
char = chr(char_no)
schemeless_url = "//localhost:7777/test%s/" % char |
def test_url_with_control_char_rejected(self):
self.unfakehttp()
@unittest.skipUnless(ssl, "ssl module required")
def test_url_with_newline_header_injection_rejected(self):
self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.")
host = "localhost:7777?a=1 HTTP/1.1\r\nX-injected: header\... | def test_url_with_control_char_rejected(self):
self.unfakehttp()
@unittest.skipUnless(ssl, "ssl module required")
def test_url_path_with_newline_header_injection_rejected(self):
self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.")
host = "localhost:7777?a=1 HTTP/1.1\r\nX-injected: he... |
def test_url_with_newline_header_injection_rejected(self):
# calls urllib.parse.quote() on the URL which makes all of the
# above attempts at injection within the url _path_ safe.
InvalidURL = httplib.InvalidURL
with self.assertRaisesRegexp(
InvalidURL, r"... | def test_url_with_newline_header_injection_rejected(self):
# calls urllib.parse.quote() on the URL which makes all of the
# above attempts at injection within the url _path_ safe.
InvalidURL = httplib.InvalidURL
with self.assertRaisesRegexp(InvalidURL,
... |
def load(stream, Loader=Loader):
"""
Parse the first YAML document in a stream
and produce the corresponding Python object.
"""
loader = Loader(stream)
try:
return loader.get_single_data()
finally:
loader.dispose()
def load_all(stream, Loader=Loader):
"""
Parse all Y... | def load(stream, Loader=Loader):
"""
Parse the first YAML document in a stream
and produce the corresponding Python object.
By default resolve only basic YAML tags, if an alternate Loader is
provided, may be dangerous.
"""
loader = Loader(stream)
try:
return loader.get_single_da... |
def load_all(stream, Loader=Loader):
yield loader.get_data()
finally:
loader.dispose()
def safe_load(stream):
"""
Parse the first YAML document in a stream
and produce the corresponding Python object.
Resolve only basic YAML tags.
"""
return load(stream, SafeLoader)
def... | def load_all(stream, Loader=Loader):
yield loader.get_data()
finally:
loader.dispose()
safe_load_all = load_all
def danger_load(stream):
"""
Parse the first YAML document in a stream
and produce the corresponding Python object.
When used on untrusted input, can result in arbitra... |
def dump_all(documents, stream=None, Dumper=Dumper,
dumper.dispose()
if getvalue:
return getvalue()
def dump(data, stream=None, Dumper=Dumper, **kwds):
"""
Serialize a Python object into a YAML stream.
If stream is None, return the produced string instead.
"""
return dump_all([d... | def dump_all(documents, stream=None, Dumper=Dumper,
dumper.dispose()
if getvalue:
return getvalue()
safe_dump_all = dump_all
def danger_dump_all(documents, stream=None, **kwds):
"""
Serialize a sequence of Python objects into a YAML stream.
Produce only basic YAML tags.
If stream is... |
def to_yaml(cls, dumper, data):
return dumper.represent_yaml_object(cls.yaml_tag, data, cls,
flow_style=cls.yaml_flow_style)
to_yaml = classmethod(to_yaml)
| def to_yaml(cls, dumper, data):
return dumper.represent_yaml_object(cls.yaml_tag, data, cls,
flow_style=cls.yaml_flow_style)
to_yaml = classmethod(to_yaml) |
__all__ = ['CBaseLoader', 'CSafeLoader', 'CLoader',
'CBaseDumper', 'CSafeDumper', 'CDumper']
from _yaml import CParser, CEmitter
|
__all__ = ['CBaseLoader', 'CSafeLoader', 'CLoader', 'CDangerLoader',
'CBaseDumper', 'CSafeDumper', 'CDumper', 'CDangerDumper']
from _yaml import CParser, CEmitter
|
def __init__(self, stream):
BaseConstructor.__init__(self)
BaseResolver.__init__(self)
class CSafeLoader(CParser, SafeConstructor, Resolver):
def __init__(self, stream):
CParser.__init__(self, stream)
SafeConstructor.__init__(self)
Resolver.__init__(self)
class CLoader(CPa... | def __init__(self, stream):
BaseConstructor.__init__(self)
BaseResolver.__init__(self)
class CLoader(CParser, SafeConstructor, Resolver):
def __init__(self, stream):
CParser.__init__(self, stream)
SafeConstructor.__init__(self)
Resolver.__init__(self)
CSafeLoader = CLoader
... |
def __init__(self, stream,
default_flow_style=default_flow_style)
Resolver.__init__(self)
class CSafeDumper(CEmitter, SafeRepresenter, Resolver):
def __init__(self, stream,
default_style=None, default_flow_style=None, | def __init__(self, stream,
default_flow_style=default_flow_style)
Resolver.__init__(self)
class CDumper(CEmitter, SafeRepresenter, Resolver):
def __init__(self, stream,
default_style=None, default_flow_style=None, |
def __init__(self, stream,
SafeRepresenter.__init__(self, default_style=default_style,
default_flow_style=default_flow_style)
Resolver.__init__(self)
class CDumper(CEmitter, Serializer, Representer, Resolver):
def __init__(self, stream,
default_style=None, default_flow_... | def __init__(self, stream,
SafeRepresenter.__init__(self, default_style=default_style,
default_flow_style=default_flow_style)
Resolver.__init__(self)
CSafeDumper = CDumper
class CDangerDumper(CEmitter, Serializer, Representer, Resolver):
def __init__(self, stream,
defau... |
def __init__(self, stream,
Representer.__init__(self, default_style=default_style,
default_flow_style=default_flow_style)
Resolver.__init__(self)
| def __init__(self, stream,
Representer.__init__(self, default_style=default_style,
default_flow_style=default_flow_style)
Resolver.__init__(self) |
__all__ = ['BaseDumper', 'SafeDumper', 'Dumper']
from emitter import *
from serializer import * |
__all__ = ['BaseDumper', 'SafeDumper', 'Dumper', 'DangerDumper']
from emitter import *
from serializer import * |
def __init__(self, stream,
default_flow_style=default_flow_style)
Resolver.__init__(self)
class SafeDumper(Emitter, Serializer, SafeRepresenter, Resolver):
def __init__(self, stream,
default_style=None, default_flow_style=None, | def __init__(self, stream,
default_flow_style=default_flow_style)
Resolver.__init__(self)
class Dumper(Emitter, Serializer, SafeRepresenter, Resolver):
def __init__(self, stream,
default_style=None, default_flow_style=None, |
def __init__(self, stream,
SafeRepresenter.__init__(self, default_style=default_style,
default_flow_style=default_flow_style)
Resolver.__init__(self)
class Dumper(Emitter, Serializer, Representer, Resolver):
def __init__(self, stream,
default_style=None, default_flow_st... | def __init__(self, stream,
SafeRepresenter.__init__(self, default_style=default_style,
default_flow_style=default_flow_style)
Resolver.__init__(self)
SafeDumper = Dumper
class DangerDumper(Emitter, Serializer, Representer, Resolver):
def __init__(self, stream,
default_s... |
def __init__(self, stream,
Representer.__init__(self, default_style=default_style,
default_flow_style=default_flow_style)
Resolver.__init__(self)
| def __init__(self, stream,
Representer.__init__(self, default_style=default_style,
default_flow_style=default_flow_style)
Resolver.__init__(self) |
__all__ = ['BaseLoader', 'SafeLoader', 'Loader']
from reader import *
from scanner import * |
__all__ = ['BaseLoader', 'SafeLoader', 'Loader', 'DangerLoader']
from reader import *
from scanner import * |
def __init__(self, stream):
BaseConstructor.__init__(self)
BaseResolver.__init__(self)
class SafeLoader(Reader, Scanner, Parser, Composer, SafeConstructor, Resolver):
def __init__(self, stream):
Reader.__init__(self, stream) | def __init__(self, stream):
BaseConstructor.__init__(self)
BaseResolver.__init__(self)
class Loader(Reader, Scanner, Parser, Composer, SafeConstructor, Resolver):
def __init__(self, stream):
Reader.__init__(self, stream) |
def __init__(self, stream):
Composer.__init__(self)
SafeConstructor.__init__(self)
Resolver.__init__(self)
class Loader(Reader, Scanner, Parser, Composer, Constructor, Resolver):
def __init__(self, stream):
Reader.__init__(self, stream) | def __init__(self, stream):
Composer.__init__(self)
SafeConstructor.__init__(self)
Resolver.__init__(self)
SafeLoader = Loader
class DangerLoader(Reader, Scanner, Parser, Composer, Constructor, Resolver):
def __init__(self, stream):
Reader.__init__(self, stream) |
def __init__(self, stream):
Composer.__init__(self)
Constructor.__init__(self)
Resolver.__init__(self)
| def __init__(self, stream):
Composer.__init__(self)
Constructor.__init__(self)
Resolver.__init__(self) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.