buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
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 tqdm(object):
# Format left/right sides of the bar, and format the bar
# later in the remaining space (avoid breaking display)
l_bar_user, r_bar_user = bar_format.split('{bar}')
l_bar, r_bar = l_bar.format(**bar_args), r_bar.format(**... | class tqdm(object):
# Format left/right sides of the bar, and format the bar
# later in the remaining space (avoid breaking display)
l_bar_user, r_bar_user = bar_format.split('{bar}')
l_bar, r_bar = l_bar_user.format(**bar_args), r_bar_user... |
def test_format_meter():
"100KiB [00:13, 7.69KiB/s]"
assert format_meter(100, 1000, 12, ncols=0, rate=7.33) == \
" 10% 100/1000 [00:12<02:02, 7.33it/s]"
assert format_meter(20, 100, 12, ncols=30, rate=8.1,
bar_format=r'{l_bar}{bar}|{n_fmt}/{total_fmt}') == \
" 20... | def test_format_meter():
"100KiB [00:13, 7.69KiB/s]"
assert format_meter(100, 1000, 12, ncols=0, rate=7.33) == \
" 10% 100/1000 [00:12<02:02, 7.33it/s]"
# Check that bar_format correctly adapts {bar} size to the rest
assert format_meter(20, 100, 12, ncols=13, rate=8.1,
... |
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 categorical_accuracy(y_true, y_pred):
def sparse_categorical_accuracy(y_true, y_pred):
# reshape in case it's in shape (num_samples, 1) instead of (num_samples,)
if K.ndim(y_true) == K.ndim(y_pred):
y_true = K.squeeze(y_true, -1)
# convert dense predictions to labels
y_pred_labels = K.argm... |
def test_sparse_metrics():
assert K.eval(metric(y_a, y_b)).shape == (6,)
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 sparse labe... | def test_sparse_metrics():
assert K.eval(metric(y_a, y_b)).shape == (6,)
@pytest.mark.parametrize('shape', [(6,), (6, 3), (6, 3, 1)])
def test_sparse_categorical_accuracy_correctness(shape):
y_a = K.variable(np.random.randint(0, 7, shape), dtype=K.floatx())
y_b_shape = shape + (7,)
y_b = K.variabl... |
def main():
download_set = {}
for pkg in download_list:
remote = pkg.returnSimple('relativepath')
rpmname = os.path.basename(remote)
download_set[rpmname] = 1
for pkg in current_pkgs: | def main():
download_set = {}
for pkg in download_list:
rpmname = os.path.basename(pkg.remote_path)
download_set[rpmname] = 1
for pkg in current_pkgs: |
def main():
remote_size = 0
if not opts.urls:
for pkg in download_list:
remote = pkg.returnSimple('relativepath')
local = local_repo_path + '/' + remote
sz = int(pkg.returnSimple('packagesize'))
if os.path.exists(local) and os.p... | def main():
remote_size = 0
if not opts.urls:
for pkg in download_list:
local = os.path.join(local_repo_path, pkg.remote_path)
sz = int(pkg.returnSimple('packagesize'))
if os.path.exists(local) and os.path.getsize(local) == sz:
... |
def main():
download_list.sort(key=lambda pkg: pkg.name)
if opts.urls:
for pkg in download_list:
remote = pkg.returnSimple('relativepath')
local = os.path.join(local_repo_path, remote)
if not (os.path.exists(local) and my.verifyPkg(local, pkg, ... | def main():
download_list.sort(key=lambda pkg: pkg.name)
if opts.urls:
for pkg in download_list:
local = os.path.join(local_repo_path, pkg.remote_path)
if not (os.path.exists(local) and my.verifyPkg(local, pkg, False)):
print urljoin(pkg.re... |
def main():
# set localpaths
for pkg in download_list:
rpmfn = pkg.remote_path
pkg.localpath = os.path.join(local_repo_path, rpmfn)
pkg.repo.copy_local = True
pkg.repo.cache = 0
localdir = os.path.dirname(pkg.localpath) | def main():
# set localpaths
for pkg in download_list:
pkg.localpath = os.path.join(local_repo_path, pkg.remote_path)
pkg.repo.copy_local = True
pkg.repo.cache = 0
localdir = os.path.dirname(pkg.localpath) |
class _Alpha:
raise ValueError
def __gt__(self, other):
return not self.__lt__(other)
def __le__(self, other):
return self.__lt__(other) or self.__eq__(other)
def __ge__(self, other):
return self.__gt__(other) or self.__eq__(other)
class _Numeric: | class _Alpha:
raise ValueError
def __le__(self, other):
return self.__lt__(other) or self.__eq__(other)
def __gt__(self, other):
return not self.__le__(other)
def __ge__(self, other):
return not self.__lt__(other)
class _Numeric: |
class _Numeric:
raise ValueError
def __gt__(self, other):
return not self.__lt__(other)
def __le__(self, other):
return self.__lt__(other) or self.__eq__(other)
def __ge__(self, other):
return self.__gt__(other) or self.__eq__(other)
class SemanticVersion(Version): | class _Numeric:
raise ValueError
def __le__(self, other):
return self.__lt__(other) or self.__eq__(other)
def __gt__(self, other):
return not self.__le__(other)
def __ge__(self, other):
return not self.__lt__(other)
class SemanticVersion(Version): |
def test_alpha():
assert _Alpha('b') >= _Alpha('a')
assert _Alpha('b') >= _Alpha('b')
def test_numeric():
assert _Numeric(1) == _Numeric(1) | def test_alpha():
assert _Alpha('b') >= _Alpha('a')
assert _Alpha('b') >= _Alpha('b')
# The following 3*6 tests check that all comparison operators perform
# as expected. DO NOT remove any of them, or reformulate them (to remove
# the explicit `not`)!
assert _Alpha('a') == _Alpha('a')
asse... |
def test_numeric():
assert _Numeric(1) <= _Numeric(2)
assert _Numeric(2) >= _Numeric(1)
assert _Numeric(2) >= _Numeric(2) | def test_numeric():
assert _Numeric(1) <= _Numeric(2)
assert _Numeric(2) >= _Numeric(1)
assert _Numeric(2) >= _Numeric(2)
# The following 3*6 tests check that all comparison operators perform
# as expected. DO NOT remove any of them, or reformulate them (to remove
# the explicit `not`)!
as... |
def fit_generator(model,
elif val_gen:
val_data = validation_data
if isinstance(val_data, Sequence):
val_enqueuer_gen = iter_sequence_infinite(generator)
else:
val_enqueuer_gen = val_data
else: | def fit_generator(model,
elif val_gen:
val_data = validation_data
if isinstance(val_data, Sequence):
val_enqueuer_gen = iter_sequence_infinite(val_data)
validation_steps = validation_steps or len(val_data)
else:
... |
def test_model_methods():
assert trained_batches == list(range(12)) * 5
assert len(val_seq.logs) == 12 * 5
# fit_generator will throw an exception
# if steps is unspecified for regular generator
with pytest.raises(ValueError): | def test_model_methods():
assert trained_batches == list(range(12)) * 5
assert len(val_seq.logs) == 12 * 5
# test for workers = 0
trained_epochs = []
trained_batches = []
val_seq = RandomSequence(4)
out = model.fit_generator(generator=RandomSequence(3),
epochs=... |
class Driver(object):
current_line = ""
current_column = 0
wait_for_nl = False
elif char == ' ':
current_column += 1
elif char == '\t':
current_column += 4
elif char == '\n':
#... | class Driver(object):
current_line = ""
current_column = 0
wait_for_nl = False
elif char in ' \t':
current_column += 1
elif char == '\n':
# unexpected empty line
current_column = 0 |
class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, line_length=ll)
def test_report_verbose(self) -> None:
report = black.Report(verbose=True)
out_lines = [] | class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, line_length=ll)
def test_comment_indentation(self) -> None:
contents_tab = "if 1:\n\tif 2:\n\t\tpass\n\t# comment\n\tpass\n"
contents_spc = "if 1:\n if 2:\n ... |
from thefuck.rules.ls_lah import match, get_new_command
def test_match():
assert match(Mock(script='ls file.py'), None)
assert match(Mock(script='ls /opt'), None)
assert not match(Mock(script='ls -lah /opt'), None)
def test_get_new_command(): | from thefuck.rules.ls_lah import match, get_new_command
def test_match():
assert match(Mock(script='ls'), None)
assert match(Mock(script='ls file.py'), None)
assert match(Mock(script='ls /opt'), None)
assert not match(Mock(script='ls -lah /opt'), None)
assert not match(Mock(script='pacman -S binut... |
def match(command, settings):
return 'ls' in command.script and not ('ls -' in command.script)
def get_new_command(command, settings): | def match(command, settings):
return (command.script == 'ls'
or command.script.startswith('ls ')
and not ('ls -' in command.script))
def get_new_command(command, settings): |
class TestUtil(unittest.TestCase):
self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
self.assertEqual(unified_strdate('1968-12-10'), '19681210')
def test_find_xpath_attr(self):
testxml = '''<root> | class TestUtil(unittest.TestCase):
self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
self.assertEqual(unified_strdate('1968-12-10'), '19681210')
self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0... |
class ArteTVPlus7IE(InfoExtractor):
info = self._download_json(json_url, video_id)
player_info = info['videoJsonPlayer']
info_dict = {
'id': player_info['VID'],
'title': player_info['VTI'],
'description': player_info.get('VDE'),
'upload_date': uni... | class ArteTVPlus7IE(InfoExtractor):
info = self._download_json(json_url, video_id)
player_info = info['videoJsonPlayer']
upload_date_str = player_info.get('shootingDate')
if not upload_date_str:
upload_date_str = player_info.get('VDA', '').split(' ')[0]
info_dict = ... |
def unified_strdate(date_str):
'%d/%m/%Y',
'%d/%m/%y',
'%Y/%m/%d %H:%M:%S',
'%Y-%m-%d %H:%M:%S',
'%d.%m.%Y %H:%M',
'%d.%m.%Y %H.%M', | def unified_strdate(date_str):
'%d/%m/%Y',
'%d/%m/%y',
'%Y/%m/%d %H:%M:%S',
'%d/%m/%Y %H:%M:%S',
'%Y-%m-%d %H:%M:%S',
'%d.%m.%Y %H:%M',
'%d.%m.%Y %H.%M', |
def capfirst(x):
# Set up regular expressions
re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.S)
re_chars = re.compile(r'<.*?>|(.)', re.S)
re_tag = re.compile(r'<(/)?(\S+?)(?:(\s*/)|\s.*?)?>', re.S)
re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines
re_camel_case = re.compile(r'(((?<=[a-z])[A... | def capfirst(x):
# Set up regular expressions
re_words = re.compile(r'<[^>]+?>|([^<>\s]+)', re.S)
re_chars = re.compile(r'<[^>]+?>|(.)', re.S)
re_tag = re.compile(r'<(/)?(\S+?)(?:(\s*/)|\s.*?)?>', re.S)
re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines
re_camel_case = re.compile(r'(((?<=[a-z])[A-Z])|... |
class FunctionTests(SimpleTestCase):
def test_truncate2(self):
self.assertEqual(
truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 4),
'<p>one <a href="#">two - three <br>four …</a></p>',
)
def test_truncate3(self):
self.assertEqual(
... | class FunctionTests(SimpleTestCase):
def test_truncate2(self):
self.assertEqual(
truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 4),
'<p>one <a href="#">two - three …</a></p>',
)
def test_truncate3(self):
self.assertEqual(
t... |
class TestUtilsText(SimpleTestCase):
# lazy strings are handled correctly
self.assertEqual(text.Truncator(lazystr('The quick brown fox')).chars(10), 'The quick…')
def test_truncate_words(self):
truncator = text.Truncator('The quick brown fox jumped over the lazy dog.')
self.assertEq... | class TestUtilsText(SimpleTestCase):
# lazy strings are handled correctly
self.assertEqual(text.Truncator(lazystr('The quick brown fox')).chars(10), 'The quick…')
def test_truncate_chars_html(self):
perf_test_values = [
(('</a' + '\t' * 50000) + '//>', None),
('&' * ... |
class TestUtilsText(SimpleTestCase):
truncator = text.Truncator('<i>Buenos días! ¿Cómo está?</i>')
self.assertEqual('<i>Buenos días! ¿Cómo…</i>', truncator.words(3, html=True))
truncator = text.Truncator('<p>I <3 python, what about you?</p>')
... | class TestUtilsText(SimpleTestCase):
truncator = text.Truncator('<i>Buenos días! ¿Cómo está?</i>')
self.assertEqual('<i>Buenos días! ¿Cómo…</i>', truncator.words(3, html=True))
truncator = text.Truncator('<p>I <3 python, what about you?</p>')
... |
dependency tree to find the noun phrase they are referring to – for example:
$9.4 million --> Net income.
Compatible with: spaCy v2.0.0+
Last tested with: v2.1.0
"""
from __future__ import unicode_literals, print_function
| dependency tree to find the noun phrase they are referring to – for example:
$9.4 million --> Net income.
Compatible with: spaCy v2.0.0+
Last tested with: v2.2.1
"""
from __future__ import unicode_literals, print_function
|
def main(model="en_core_web_sm"):
def filter_spans(spans):
# Filter a sequence of spans so they don't contain overlaps
get_sort_key = lambda span: (span.end - span.start, span.start)
sorted_spans = sorted(spans, key=get_sort_key, reverse=True)
result = []
seen_tokens = set()
for span in sorted_... | def main(model="en_core_web_sm"):
def filter_spans(spans):
# Filter a sequence of spans so they don't contain overlaps
# For spaCy 2.1.4+: this function is available as spacy.util.filter_spans()
get_sort_key = lambda span: (span.end - span.start, -span.start)
sorted_spans = sorted(spans, key=get_sort_k... |
def test_filter_spans(doc):
assert len(filtered[1]) == 5
assert filtered[0].start == 1 and filtered[0].end == 4
assert filtered[1].start == 5 and filtered[1].end == 10 | def test_filter_spans(doc):
assert len(filtered[1]) == 5
assert filtered[0].start == 1 and filtered[0].end == 4
assert filtered[1].start == 5 and filtered[1].end == 10
# Test filtering overlaps with earlier preference for identical length
spans = [doc[1:4], doc[2:5], doc[5:10], doc[7:9], doc[1:4]]
... |
def filter_spans(spans):
spans (iterable): The spans to filter.
RETURNS (list): The filtered spans.
"""
get_sort_key = lambda span: (span.end - span.start, span.start)
sorted_spans = sorted(spans, key=get_sort_key, reverse=True)
result = []
seen_tokens = set() | def filter_spans(spans):
spans (iterable): The spans to filter.
RETURNS (list): The filtered spans.
"""
get_sort_key = lambda span: (span.end - span.start, -span.start)
sorted_spans = sorted(spans, key=get_sort_key, reverse=True)
result = []
seen_tokens = set() |
class InlineParser(ScannerParser):
#: _emphasis_ __strong__
ASTERISK_EMPHASIS = (
r'(\*{1,2})(?=[^\s*])('
r'(?:\\[\\*]|[^*])*'
r'(?:' + ESCAPE_TEXT + r'|[^\s*]))\1'
)
UNDERSCORE_EMPHASIS = (
r'\b(_{1,2})(?=[^\s_])([\s\S]*?' | class InlineParser(ScannerParser):
#: _emphasis_ __strong__
ASTERISK_EMPHASIS = (
r'(\*{1,2})(?=[^\s*])('
r'(?:(?:(?<!\\)(?:\\\\)*\*)|[^*])+'
r')(?<!\\)\1'
)
UNDERSCORE_EMPHASIS = (
r'\b(_{1,2})(?=[^\s_])([\s\S]*?' |
class TestFish(object):
return mock
@pytest.fixture
def environ(self, monkeypatch):
data = {'TF_OVERRIDDEN_ALIASES': 'cd, ls, man, open'}
monkeypatch.setattr('thefuck.shells.fish.os.environ', data)
return data
@pytest.mark.usefixture('environ')
def test_get_overridden_a... | class TestFish(object):
return mock
@pytest.fixture
def tf_overridden(self, monkeypatch, aliases):
monkeypatch.setattr('os.environ', {'TF_OVERRIDDEN_ALIASES': aliases})
@pytest.mark.parametrize('aliases', [
'cut,git,sed',
'cut, git, sed',
' cut,\tgit,sed\n',
... |
from .generic import Generic
class Fish(Generic):
def _get_overridden_aliases(self):
overridden_aliases = os.environ.get('TF_OVERRIDDEN_ALIASES', '').strip()
if overridden_aliases:
return [alias.strip() for alias in overridden_aliases.split(',')]
else:
return ['cd', ... | from .generic import Generic
class Fish(Generic):
def _get_overridden_aliases(self):
default = {'cd', 'grep', 'ls', 'man', 'open'}
for alias in os.environ.get('TF_OVERRIDDEN_ALIASES', '').split(','):
default.add(alias.strip())
return default
def app_alias(self, fuck):
... |
def __str__(self):
class Application:
SOCKTYPES = {
"tcp": socket.SOCK_STREAM,
"udp": socket.SOCK_DGRAM, | def __str__(self):
class Application:
MAX_LENGTH = 128 * 1024
SOCKTYPES = {
"tcp": socket.SOCK_STREAM,
"udp": socket.SOCK_DGRAM, |
def __call__(self, env, start_response):
try:
length = int(env["CONTENT_LENGTH"])
except AttributeError:
length = -1
try:
pr = codec.decode(env["wsgi.input"].read(length))
except codec.ParsingError as e: | def __call__(self, env, start_response):
try:
length = int(env["CONTENT_LENGTH"])
except AttributeError:
raise HTTPException(411, "Length required.")
if length < 0:
raise HTTPException(411, "Length required.")
if length > se... |
def _align_method_FRAME(
def _should_reindex_frame_op(
left: "DataFrame", right, axis, default_axis: int, fill_value, level
) -> bool:
"""
Check if this is an operation between DataFrames that will need to reindex.
"""
assert isinstance(left, ABCDataFrame)
if not isinstance(right, ABCDataFram... | def _align_method_FRAME(
def _should_reindex_frame_op(
left: "DataFrame", right, op, axis, default_axis: int, fill_value, level
) -> bool:
"""
Check if this is an operation between DataFrames that will need to reindex.
"""
assert isinstance(left, ABCDataFrame)
if op is operator.pow or op is r... |
def _arith_method_FRAME(cls, op, special):
@Appender(doc)
def f(self, other, axis=default_axis, level=None, fill_value=None):
if _should_reindex_frame_op(self, other, axis, default_axis, fill_value, level):
return _frame_arith_method_with_reindex(self, other, op)
self, other = _ali... | def _arith_method_FRAME(cls, op, special):
@Appender(doc)
def f(self, other, axis=default_axis, level=None, fill_value=None):
if _should_reindex_frame_op(
self, other, op, axis, default_axis, fill_value, level
):
return _frame_arith_method_with_reindex(self, other, op)
... |
class TestFrameArithmeticUnsorted:
half = ts[::2]
result = ts + half.take(np.random.permutation(len(half)))
tm.assert_frame_equal(result, expected) | class TestFrameArithmeticUnsorted:
half = ts[::2]
result = ts + half.take(np.random.permutation(len(half)))
tm.assert_frame_equal(result, expected)
def test_pow_with_realignment():
# GH#32685 pow has special semantics for operating with null values
left = pd.DataFrame({"A": [0, 1, 2]})... |
import sys
import types
import importlib
from xml.etree import ElementTree
# we do not use this ourselves, but mock methods often want to use this | import sys
import types
import importlib
import imp
from xml.etree import ElementTree
# we do not use this ourselves, but mock methods often want to use this |
def load_module(name):
if os.path.exists(name) and os.path.splitext(name)[1] == '.py':
sys.path.insert(0, os.path.dirname(os.path.abspath(name)))
try:
m = os.path.splitext(os.path.basename(name))[0]
module = importlib.import_module(m)
finally:
sys.path.po... |
def load_module(name):
if os.path.exists(name) and os.path.splitext(name)[1] == '.py':
mod = imp.new_module(os.path.splitext(os.path.basename(name))[0])
with open(name) as f:
exec(f.read(), mod.__dict__, mod.__dict__)
return mod
return importlib.import_module('dbusmock.temp... |
def load(mock, parameters):
self.addCleanup(p_mock.terminate)
self.addCleanup(p_mock.stdout.close)
self.assertEqual(dbus_ultimate.Answer(), 42)
# should appear in introspection | def load(mock, parameters):
self.addCleanup(p_mock.terminate)
self.addCleanup(p_mock.stdout.close)
# ensure that we don't use/write any .pyc files, they are dangerous
# in a world-writable directory like /tmp
self.assertFalse(os.path.exists(my_template.name +... |
from ansible.galaxy.role import GalaxyRole
from ansible.galaxy.token import BasicAuthToken, GalaxyToken, KeycloakToken, NoTokenSentinel
from ansible.module_utils.ansible_release import __version__ as ansible_version
from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.parsing.yaml.loader imp... | from ansible.galaxy.role import GalaxyRole
from ansible.galaxy.token import BasicAuthToken, GalaxyToken, KeycloakToken, NoTokenSentinel
from ansible.module_utils.ansible_release import __version__ as ansible_version
from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.module_utils import six... |
class GalaxyCLI(CLI):
else:
requirements = []
for collection_input in collections:
name, dummy, requirement = collection_input.partition(':')
requirements.append((name, requirement or '*', None))
output_path = GalaxyCLI._re... | class GalaxyCLI(CLI):
else:
requirements = []
for collection_input in collections:
requirement = None
if os.path.isfile(to_bytes(collection_input, errors='surrogate_or_strict')) or \
urlparse(collection_input... |
def _get_collection_info(dep_map, existing_collections, collection, requirement,
if os.path.isfile(to_bytes(collection, errors='surrogate_or_strict')):
display.vvvv("Collection requirement '%s' is a tar artifact" % to_text(collection))
b_tar_path = to_bytes(collection, errors='surrogate_or_strict')
... | def _get_collection_info(dep_map, existing_collections, collection, requirement,
if os.path.isfile(to_bytes(collection, errors='surrogate_or_strict')):
display.vvvv("Collection requirement '%s' is a tar artifact" % to_text(collection))
b_tar_path = to_bytes(collection, errors='surrogate_or_strict')
... |
def test_collection_install_in_collection_dir(collection_install, monkeypatch):
assert mock_install.call_args[0][7] is False
def test_collection_install_name_and_requirements_fail(collection_install):
test_path = collection_install[2]
expected = 'The positional collection_name arg and --requirements-file ... | def test_collection_install_in_collection_dir(collection_install, monkeypatch):
assert mock_install.call_args[0][7] is False
def test_collection_install_with_url(collection_install):
mock_install, dummy, output_dir = collection_install
galaxy_args = ['ansible-galaxy', 'collection', 'install', 'https://fo... |
class ActionBase(with_metaclass(ABCMeta, object)):
Create and return a temporary path on a remote box.
'''
become_unprivileged = self._is_become_unprivileged()
remote_tmp = self.get_shell_option('remote_tmp', default='~/.ansible/tmp')
# deal with tmpdir creation
basefil... | class ActionBase(with_metaclass(ABCMeta, object)):
Create and return a temporary path on a remote box.
'''
# Network connection plugins (network_cli, netconf, etc.) execute on the controller, rather than the remote host.
# As such, we want to avoid using remote_user for paths as remote... |
class ActionBase(with_metaclass(ABCMeta, object)):
elif u'No space left on device' in result['stderr']:
output = result['stderr']
else:
output = ('Authentication or permission failure. '
'In some cases, you may have been able to authentic... | class ActionBase(with_metaclass(ABCMeta, object)):
elif u'No space left on device' in result['stderr']:
output = result['stderr']
else:
output = ('Failed to create temporary directory.'
'In some cases, you may have been able to authentica... |
import random
import re
import time
import ansible.constants as C
from ansible.errors import AnsibleError
from ansible.module_utils.six import text_type
from ansible.module_utils.six.moves import shlex_quote | import random
import re
import time
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.module_utils.six import text_type
from ansible.module_utils.six.moves import shlex_quote |
class ShellBase(AnsiblePlugin):
except KeyError:
pass
def env_prefix(self, **kwargs):
return ' '.join(['%s=%s' % (k, shlex_quote(text_type(v))) for k, v in kwargs.items()])
| class ShellBase(AnsiblePlugin):
except KeyError:
pass
@staticmethod
def _generate_temp_dir_name():
return 'ansible-tmp-%s-%s-%s' % (time.time(), os.getpid(), random.randint(0, 2**48))
def env_prefix(self, **kwargs):
return ' '.join(['%s=%s' % (k, shlex_quote(text_type(v... |
class ShellBase(AnsiblePlugin):
def mkdtemp(self, basefile=None, system=False, mode=0o700, tmpdir=None):
if not basefile:
basefile = 'ansible-tmp-%s-%s' % (time.time(), random.randint(0, 2**48))
# When system is specified we have to create this in a directory where
# other user... | class ShellBase(AnsiblePlugin):
def mkdtemp(self, basefile=None, system=False, mode=0o700, tmpdir=None):
if not basefile:
basefile = self.__class__._generate_temp_dir_name()
# When system is specified we have to create this in a directory where
# other users can read and access... |
class ShellBase(AnsiblePlugin):
# passed in tmpdir if it is valid or the first one from the setting if not.
if system:
tmpdir = tmpdir.rstrip('/')
if tmpdir in self.get_option('system_tmpdirs'):
basetmpdir = tmpdir | class ShellBase(AnsiblePlugin):
# passed in tmpdir if it is valid or the first one from the setting if not.
if system:
if tmpdir:
tmpdir = tmpdir.rstrip('/')
if tmpdir in self.get_option('system_tmpdirs'):
basetmpdir = tmpdir |
class ShellBase(AnsiblePlugin):
basetmp = self.join_path(basetmpdir, basefile)
cmd = 'mkdir -p %s echo %s %s' % (self._SHELL_SUB_LEFT, basetmp, self._SHELL_SUB_RIGHT)
cmd += ' %s echo %s=%s echo %s %s' % (self._SHELL_AND, basefile, self._SHELL_SUB_LEFT, basetmp, self._SHELL_SUB_RIGHT)
... | class ShellBase(AnsiblePlugin):
basetmp = self.join_path(basetmpdir, basefile)
# use mkdir -p to ensure parents exist, but mkdir fullpath to ensure last one is created by us
cmd = 'mkdir -p %s echo %s %s' % (self._SHELL_SUB_LEFT, basetmpdir, self._SHELL_SUB_RIGHT)
cmd += '%s mkdir %s' ... |
class ShellModule(ShellBase):
def mkdtemp(self, basefile=None, system=False, mode=None, tmpdir=None):
# Windows does not have an equivalent for the system temp files, so
# the param is ignored
basefile = self._escape(self._unquote(basefile))
basetmpdir = tmpdir if tmpdir else self.ge... | class ShellModule(ShellBase):
def mkdtemp(self, basefile=None, system=False, mode=None, tmpdir=None):
# Windows does not have an equivalent for the system temp files, so
# the param is ignored
if not basefile:
basefile = self.__class__._generate_temp_dir_name()
basefile =... |
class Function(object):
# (since the outputs of fetches are never returned).
# This requires us to wrap fetches in `identity` ops.
self.fetches = [tf.identity(x) for x in self.fetches]
self.session_kwargs = session_kwargs
if session_kwargs:
raise ValueError('Some keys... | class Function(object):
# (since the outputs of fetches are never returned).
# This requires us to wrap fetches in `identity` ops.
self.fetches = [tf.identity(x) for x in self.fetches]
# self.session_kwargs is used for _legacy_call
self.session_kwargs = session_kwargs.copy()
... |
class Function(object):
callable_opts.fetch.append(x.name)
# Handle updates.
callable_opts.target.append(self.updates_op.name)
# Create callable.
callable_fn = session._make_callable_from_options(callable_opts)
# Cache parameters corresponding to the generated callabl... | class Function(object):
callable_opts.fetch.append(x.name)
# Handle updates.
callable_opts.target.append(self.updates_op.name)
# Handle run_options.
if self.run_options:
callable_opts.run_options.CopyFrom(self.run_options)
# Create callable.
callab... |
class Function(object):
feed_symbols,
symbol_vals,
session)
fetched = self._callable_fn(*array_vals)
return fetched[:len(self.outputs)]
def _legacy_call(self, inputs): | class Function(object):
feed_symbols,
symbol_vals,
session)
if self.run_metadata:
fetched = self._callable_fn(*array_vals, run_metadata=self.run_metadata)
else:
fetched = self._callabl... |
class Function(object):
'supported with sparse inputs.')
return self._legacy_call(inputs)
return self._call(inputs)
else:
if py_any(is_tensor(x) for x in inputs): | class Function(object):
'supported with sparse inputs.')
return self._legacy_call(inputs)
# callable generated by Session._make_callable_from_options accepts
# `run_metadata` keyword argument since TF 1.10
if (self.run_metadata and
... |
class TestBackend(object):
assert output == [21.]
assert K.get_session().run(fetches=[x, y]) == [30., 40.]
@pytest.mark.skipif(K.backend() != 'tensorflow',
reason='Uses the `string` type for a tensor.')
def test_function_tf_string_input(self): | class TestBackend(object):
assert output == [21.]
assert K.get_session().run(fetches=[x, y]) == [30., 40.]
@pytest.mark.skipif(K.backend() != 'tensorflow',
reason='Uses the `options` and `run_metadata` arguments.')
def test_function_tf_run_options_with_run_metadata(self)... |
def create_instance(objcls, settings, crawler, *args, **kwargs):
``*args`` and ``**kwargs`` are forwarded to the constructors.
Raises ``ValueError`` if both ``settings`` and ``crawler`` are ``None``.
"""
if settings is None:
if crawler is None:
raise ValueError("Specify at least one... | def create_instance(objcls, settings, crawler, *args, **kwargs):
``*args`` and ``**kwargs`` are forwarded to the constructors.
Raises ``ValueError`` if both ``settings`` and ``crawler`` are ``None``.
Raises ``TypeError`` if the resulting instance is ``None`` (e.g. if an
extension has not been implemen... |
class UtilsMiscTestCase(unittest.TestCase):
# 2. with from_settings() constructor
# 3. with from_crawler() constructor
# 4. with from_settings() and from_crawler() constructor
spec_sets = ([], ['from_settings'], ['from_crawler'],
['from_settings', 'from_crawler... | class UtilsMiscTestCase(unittest.TestCase):
# 2. with from_settings() constructor
# 3. with from_crawler() constructor
# 4. with from_settings() and from_crawler() constructor
spec_sets = (
['__qualname__'],
['__qualname__', 'from_settings'],
['_... |
class UtilsMiscTestCase(unittest.TestCase):
_test_with_crawler(m, settings, crawler)
# Check adoption of crawler settings
m = mock.MagicMock(spec_set=['from_settings'])
create_instance(m, None, crawler, *args, **kwargs)
m.from_settings.assert_called_once_with(crawler.setting... | class UtilsMiscTestCase(unittest.TestCase):
_test_with_crawler(m, settings, crawler)
# Check adoption of crawler settings
m = mock.MagicMock(spec_set=['__qualname__', 'from_settings'])
create_instance(m, None, crawler, *args, **kwargs)
m.from_settings.assert_called_once_with... |
class UtilsMiscTestCase(unittest.TestCase):
with self.assertRaises(ValueError):
create_instance(m, None, None)
def test_set_environ(self):
assert os.environ.get('some_test_environ') is None
with set_environ(some_test_environ='test_value'): | class UtilsMiscTestCase(unittest.TestCase):
with self.assertRaises(ValueError):
create_instance(m, None, None)
m.from_settings.return_value = None
with self.assertRaises(TypeError):
create_instance(m, settings, None)
def test_set_environ(self):
assert os.env... |
def word_tokenize(self, s):
return self._word_tokenizer_re().findall(s)
_period_context_fmt = r"""
\S* # some word material
%(SentEndChars)s # a potential sentence ending
(?=(?P<after_tok>
%(NonWord)s # either other punct... | def word_tokenize(self, s):
return self._word_tokenizer_re().findall(s)
_period_context_fmt = r"""
%(SentEndChars)s # a potential sentence ending
(?=(?P<after_tok>
%(NonWord)s # either other punctuation |
def debug_decisions(self, text):
See format_debug_decision() to help make this output readable.
"""
for match in self._lang_vars.period_context_re().finditer(text):
decision_text = match.group() + match.group("after_tok")
tokens = self._tokenize_words(decision_text)
... | def debug_decisions(self, text):
See format_debug_decision() to help make this output readable.
"""
for match, decision_text in self._match_potential_end_contexts(text):
tokens = self._tokenize_words(decision_text)
tokens = list(self._annotate_first_pass(tokens))
... |
def sentences_from_text(self, text, realign_boundaries=True):
"""
return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)]
def _slices_from_text(self, text):
last_break = 0
for match in self._lang_vars.period_context_re().finditer(text):
context = matc... | def sentences_from_text(self, text, realign_boundaries=True):
"""
return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)]
def _match_potential_end_contexts(self, text):
"""
Given a text, find the matches of potential sentence breaks,
alongside the context... |
def _set_uid_gid(tarinfo):
return archive_name
def _call_external_zip(base_dir, zip_filename, verbose=False, dry_run=False):
# XXX see if we want to keep an external call here
if verbose:
zipoptions = "-r"
else:
zipoptions = "-rq"
from distutils.errors import DistutilsExecError
... | def _set_uid_gid(tarinfo):
return archive_name
def _call_external_zip(base_dir, zip_filename, verbose, dry_run, logger):
# XXX see if we want to keep an external call here
if verbose:
zipoptions = "-r"
else:
zipoptions = "-rq"
cmd = ["zip", zipoptions, zip_filename, base_dir]
i... |
def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
zipfile = None
if zipfile is None:
_call_external_zip(base_dir, zip_filename, verbose, dry_run)
else:
if logger is not None:
logger.info("creating '%s' and adding '%s' to it", | def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
zipfile = None
if zipfile is None:
_call_external_zip(base_dir, zip_filename, verbose, dry_run, logger)
else:
if logger is not None:
logger.info("creating '%s' and adding '%s' to it", |
def is_safe_url(url, host=None):
url = url.strip()
if not url:
return False
# Chrome treats \ completely as /
url = url.replace('\\', '/')
# Chrome considers any URL with more than two slashes to be absolute, but
# urlparse is not so flexible. Treat any url with three slashes as unsa... | def is_safe_url(url, host=None):
url = url.strip()
if not url:
return False
# Chrome treats \ completely as / in paths but it could be part of some
# basic auth credentials so we need to check both URLs.
return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host)
def ... |
class TestUtilsHttp(unittest.TestCase):
'javascript:alert("XSS")',
'\njavascript:alert(x)',
'\x08//example.com',
'\n'):
self.assertFalse(http.is_safe_url(bad_url, host='testserver'), "%s should be blocked" % bad_... | class TestUtilsHttp(unittest.TestCase):
'javascript:alert("XSS")',
'\njavascript:alert(x)',
'\x08//example.com',
r'http://otherserver\@example.com',
r'http:\\testserver\@example.com',
... |
class TestUtilsHttp(unittest.TestCase):
'https://testserver/',
'HTTPS://testserver/',
'//testserver/',
'/url%20with%20spaces/'):
self.assertTrue(http.is_safe_url(good_url, host='testserver'), "%s should be allowed" % good_ur... | class TestUtilsHttp(unittest.TestCase):
'https://testserver/',
'HTTPS://testserver/',
'//testserver/',
'http://testserver/confirm?email=me@example.com',
'/url%20with%20spaces/'):
self.assertTrue(http.is_... |
logger = None
if getattr(C, 'DEFAULT_LOG_PATH'):
path = C.DEFAULT_LOG_PATH
if path and (os.path.exists(path) and os.access(path, os.W_OK)) or os.access(os.path.dirname(path), os.W_OK):
logging.basicConfig(filename=path, level=logging.DEBUG,
format='%(asctime)s p=%(process)d u... | logger = None
if getattr(C, 'DEFAULT_LOG_PATH'):
path = C.DEFAULT_LOG_PATH
if path and (os.path.exists(path) and os.access(path, os.W_OK)) or os.access(os.path.dirname(path), os.W_OK):
# NOTE: level is kept at INFO to avoid security disclosures caused by certain libraries when using DEBUG
loggin... |
def makeMappingArray(N, data, gamma=1.0):
if (np.diff(x) < 0).any():
raise ValueError("data mapping points must have x in increasing order")
# begin generation of lookup table
x = x * (N - 1)
xind = (N - 1) * np.linspace(0, 1, N) ** gamma
ind = np.searchsorted(x, xind)[1:-1]
distance = ... | def makeMappingArray(N, data, gamma=1.0):
if (np.diff(x) < 0).any():
raise ValueError("data mapping points must have x in increasing order")
# begin generation of lookup table
if N == 1:
# convention: use the y = f(x=1) value for a 1-element lookup table
lut = np.array(y0[-1])
el... |
import matplotlib.pyplot as plt
from matplotlib.testing.decorators import image_comparison
def test_resample():
"""
Github issue #6025 pointed to incorrect ListedColormap._resample; | import matplotlib.pyplot as plt
from matplotlib.testing.decorators import image_comparison
@pytest.mark.parametrize('N, result', [
(5, [1, .6, .2, .1, 0]),
(2, [1, 0]),
(1, [0]),
])
def test_makeMappingArray(N, result):
data = [(0.0, 1.0, 1.0), (0.5, 0.2, 0.2), (1.0, 0.0, 0.0)]
assert_array_almost... |
b 2""",
# datetime64tz is handled correctly in agg_series,
# so is excluded here.
# return the same type (Series) as our caller
cls = dtype.construct_array_type()
result = try_cast_to_ea(cls, result, dtype=dtype)
elif numeric... | b 2""",
# datetime64tz is handled correctly in agg_series,
# so is excluded here.
if len(result) and isinstance(result[0], dtype.type):
cls = dtype.construct_array_type()
result = try_cast_to_ea(cls, result, dtype=dtype)
... |
class BaseGrouper:
if mask.any():
result = result.astype("float64")
result[mask] = np.nan
if kind == "aggregate" and self._filter_empty_groups and not counts.all():
assert result.ndim != 2 | class BaseGrouper:
if mask.any():
result = result.astype("float64")
result[mask] = np.nan
elif (
how == "add"
and is_integer_dtype(orig_values.dtype)
and is_extension_array_dtype(orig_values.dtype)
):
# We need t... |
def test_aggregate_mixed_types():
tm.assert_frame_equal(result, expected)
class TestLambdaMangling:
def test_basic(self):
df = pd.DataFrame({"A": [0, 0, 1, 1], "B": [1, 2, 3, 4]}) | def test_aggregate_mixed_types():
tm.assert_frame_equal(result, expected)
@pytest.mark.xfail(reason="Not implemented.")
def test_aggregate_udf_na_extension_type():
# https://github.com/pandas-dev/pandas/pull/31359
# This is currently failing to cast back to Int64Dtype.
# The presence of the NA causes ... |
def test_series_groupby_categorical_aggregation_getitem():
result = groups["foo"].agg("mean")
expected = groups.agg("mean")["foo"]
tm.assert_series_equal(result, expected) | def test_series_groupby_categorical_aggregation_getitem():
result = groups["foo"].agg("mean")
expected = groups.agg("mean")["foo"]
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize(
"func, expected_values",
[(pd.Series.nunique, [1, 1, 2]), (pd.Series.count, [1, 2, 2])],
)
def test_... |
def test_resample_integerarray():
result = ts.resample("3T").mean()
expected = Series(
[1, 4, 7], index=pd.date_range("1/1/2000", periods=3, freq="3T"), dtype="Int64"
)
tm.assert_series_equal(result, expected)
| def test_resample_integerarray():
result = ts.resample("3T").mean()
expected = Series(
[1, 4, 7],
index=pd.date_range("1/1/2000", periods=3, freq="3T"),
dtype="float64",
)
tm.assert_series_equal(result, expected)
|
def test_resample_categorical_data_with_timedeltaindex():
index=pd.to_timedelta([0, 10], unit="s"),
)
expected = expected.reindex(["Group_obj", "Group"], axis=1)
expected["Group"] = expected["Group_obj"].astype("category")
tm.assert_frame_equal(result, expected)
| def test_resample_categorical_data_with_timedeltaindex():
index=pd.to_timedelta([0, 10], unit="s"),
)
expected = expected.reindex(["Group_obj", "Group"], axis=1)
expected["Group"] = expected["Group_obj"]
tm.assert_frame_equal(result, expected)
|
def any_int_dtype(request):
return request.param
@pytest.fixture(params=ALL_REAL_DTYPES)
def any_real_dtype(request):
""" | def any_int_dtype(request):
return request.param
@pytest.fixture(params=ALL_EA_INT_DTYPES)
def any_nullable_int_dtype(request):
"""
Parameterized fixture for any nullable integer dtype.
* 'UInt8'
* 'Int8'
* 'UInt16'
* 'Int16'
* 'UInt32'
* 'Int32'
* 'UInt64'
* 'Int64'
"... |
from pandas.core.dtypes.missing import isna, notna
from pandas.core import nanops, ops
from pandas.core.algorithms import take
from pandas.core.arrays import ExtensionArray, ExtensionOpsMixin
from pandas.core.ops.common import unpack_zerodim_and_defer
from pandas.core.tools.numeric import to_numeric
| from pandas.core.dtypes.missing import isna, notna
from pandas.core import nanops, ops
from pandas.core.algorithms import take
from pandas.core.arrays import ExtensionArray, ExtensionOpsMixin
from pandas.core.ops import invalid_comparison
from pandas.core.ops.common import unpack_zerodim_and_defer
from pandas.core.tool... |
class IntegerArray(ExtensionArray, ExtensionOpsMixin):
with warnings.catch_warnings():
warnings.filterwarnings("ignore", "elementwise", FutureWarning)
with np.errstate(all="ignore"):
result = op(self._data, other)
# nans propagate
... | class IntegerArray(ExtensionArray, ExtensionOpsMixin):
with warnings.catch_warnings():
warnings.filterwarnings("ignore", "elementwise", FutureWarning)
with np.errstate(all="ignore"):
method = getattr(self._data, f"__{op_name}__")
result... |
class TestComparisonOps(base.BaseComparisonOpsTests):
def _compare_other(self, s, data, op_name, other):
self.check_opname(s, op_name, other)
class TestInterface(base.BaseInterfaceTests):
pass | class TestComparisonOps(base.BaseComparisonOpsTests):
def _compare_other(self, s, data, op_name, other):
self.check_opname(s, op_name, other)
def test_compare_to_string(self, any_nullable_int_dtype):
# GH 28930
s = pd.Series([1, None], dtype=any_nullable_int_dtype)
result = s ==... |
class BarPlot(MPLPlot):
def _decorate_ticks(self, ax, name, ticklabels, start_edge, end_edge):
ax.set_xlim((start_edge, end_edge))
ax.set_xticks(self.tick_pos)
ax.set_xticklabels(ticklabels)
if name is not None and self.use_index:
ax.set_xlabel(name)
| class BarPlot(MPLPlot):
def _decorate_ticks(self, ax, name, ticklabels, start_edge, end_edge):
ax.set_xlim((start_edge, end_edge))
if self.xticks is not None:
ax.set_xticks(np.array(self.xticks))
else:
ax.set_xticks(self.tick_pos)
ax.set_xticklabels(tick... |
class TestSeriesPlots(TestPlotBase):
exp = ["P{i:02d}".format(i=i) for i in [0, 3, 5, 9]]
self._check_text_labels(ax.get_xticklabels(), exp)
def test_custom_business_day_freq(self):
# GH7222
from pandas.tseries.offsets import CustomBusinessDay | class TestSeriesPlots(TestPlotBase):
exp = ["P{i:02d}".format(i=i) for i in [0, 3, 5, 9]]
self._check_text_labels(ax.get_xticklabels(), exp)
def test_xtick_barPlot(self):
# GH28172
s = pd.Series(range(10), index=["P{i:02d}".format(i=i) for i in range(10)])
ax = s.plot.bar(xt... |
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 format_sizeof(num, suffix=''):
Number with Order of Magnitude SI unit postfix.
"""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if abs(num) < 1000.0:
if abs(num) < 100.0:
if abs(num) < 10.0:
return '{0:1.2f}'.format(num) + unit + suffix... | def format_sizeof(num, suffix=''):
Number with Order of Magnitude SI unit postfix.
"""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if abs(num) < 999.95:
if abs(num) < 99.95:
if abs(num) < 9.995:
return '{0:1.2f}'.format(num) + unit + suffi... |
class tqdm(object):
if ascii is None:
ascii = not _supports_unicode(file)
if gui: # pragma: no cover
try:
import matplotlib as mpl
import matplotlib.pyplot as plt | class tqdm(object):
if ascii is None:
ascii = not _supports_unicode(file)
if gui: # pragma: no cover
try:
import matplotlib as mpl
import matplotlib.pyplot as plt |
class tqdm(object):
self.unit_scale = unit_scale
self.gui = gui
if gui: # pragma: no cover
# Initialize the GUI display
if not disable:
file.write('Warning: GUI is experimental/alpha\n') | class tqdm(object):
self.unit_scale = unit_scale
self.gui = gui
if gui: # pragma: no cover
# Initialize the GUI display
if not disable:
file.write('Warning: GUI is experimental/alpha\n') |
class tqdm(object):
self.n = 0
def __len__(self):
return len(self.iterable)
def __iter__(self):
''' Backward-compatibility to use: for x in tqdm(iterable) ''' | class tqdm(object):
self.n = 0
def __len__(self):
return len(self.iterable) if self.iterable else self.total
def __iter__(self):
''' Backward-compatibility to use: for x in tqdm(iterable) ''' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.