buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class Categorical(ExtensionArray, PandasObject): if dtype == self.dtype: return self return self._set_dtype(dtype) if is_integer_dtype(dtype) and self.isna().any(): msg = "Cannot convert float NaN to integer" raise ValueError(msg)
class Categorical(ExtensionArray, PandasObject): if dtype == self.dtype: return self return self._set_dtype(dtype) if is_extension_array_dtype(dtype): return array(self, dtype=dtype, copy=copy) # type: ignore # GH 28770 if is_integer_dtype(dtype) and ...
class TestCasting(base.BaseCastingTests): with pytest.raises((ValueError, TypeError), match=msg): s.astype(int) class TestArithmeticOps(base.BaseArithmeticOpsTests): def test_arith_series_with_scalar(self, data, all_arithmetic_operators):
class TestCasting(base.BaseCastingTests): with pytest.raises((ValueError, TypeError), match=msg): s.astype(int) @pytest.mark.parametrize( "expected", [ pd.Series(["2019", "2020"], dtype="datetime64[ns, UTC]"), pd.Series([0, 0], dtype="timedelta64[ns]"), ...
def test_merge_equal_cat_dtypes2(): tm.assert_frame_equal(result, expected, check_categorical=False) def test_merge_multiindex_columns(): # Issue #28518 # Verify that merging two dataframes give the expected labels
def test_merge_equal_cat_dtypes2(): tm.assert_frame_equal(result, expected, check_categorical=False) def test_merge_on_cat_and_ext_array(): # GH 28668 right = DataFrame( {"a": Series([pd.Interval(0, 1), pd.Interval(1, 2)], dtype="interval")} ) left = right.copy() left["a"] = left["a"]....
def map_obj_to_commands(updates, module, warnings): else: add('protocol unix-socket') if needs_update('state') and not needs_update('vrf'): if want['state'] == 'stopped': add('shutdown') elif want['state'] == 'started':
def map_obj_to_commands(updates, module, warnings): else: add('protocol unix-socket') if needs_update('state'): if want['state'] == 'stopped': add('shutdown') elif want['state'] == 'started':
class TestEosEapiModule(TestEosModule): def test_eos_eapi_vrf(self): set_module_args(dict(vrf='test')) commands = ['management api http-commands', 'vrf test', 'no shutdown'] self.start_unconfigured(changed=True, commands=commands) def test_eos_eapi_change_from_default_vrf(self):
class TestEosEapiModule(TestEosModule): def test_eos_eapi_vrf(self): set_module_args(dict(vrf='test')) commands = ['management api http-commands', 'no shutdown', 'vrf test', 'no shutdown'] self.start_unconfigured(changed=True, commands=commands) def test_eos_eapi_change_from_default_vr...
class TestEosEapiModule(TestEosModule): commands = ['management api http-commands', 'vrf test', 'no shutdown'] self.start_configured(changed=True, commands=commands) def test_eos_eapi_vrf_missing(self): set_module_args(dict(vrf='missing')) self.start_unconfigured(failed=True)
class TestEosEapiModule(TestEosModule): commands = ['management api http-commands', 'vrf test', 'no shutdown'] self.start_configured(changed=True, commands=commands) def test_eos_eapi_default(self): set_module_args(dict()) self.start_configured(changed=False, commands=[]) def t...
from pandas.core.dtypes.cast import ( ) from pandas.core.dtypes.common import ( ensure_platform_int, is_datetime64tz_dtype, is_datetime_or_timedelta_dtype, is_dtype_equal,
from pandas.core.dtypes.cast import ( ) from pandas.core.dtypes.common import ( ensure_platform_int, is_categorical, is_datetime64tz_dtype, is_datetime_or_timedelta_dtype, is_dtype_equal,
from pandas.core.dtypes.generic import ABCSeries from pandas.core.dtypes.missing import isna from pandas._typing import AnyArrayLike from pandas.core.arrays.interval import IntervalArray, _interval_shared_docs import pandas.core.common as com import pandas.core.indexes.base as ibase
from pandas.core.dtypes.generic import ABCSeries from pandas.core.dtypes.missing import isna from pandas._typing import AnyArrayLike from pandas.core.algorithms import take_1d from pandas.core.arrays.interval import IntervalArray, _interval_shared_docs import pandas.core.common as com import pandas.core.indexes.base a...
class IntervalIndex(IntervalMixin, Index): left_indexer = self.left.get_indexer(target_as_index.left) right_indexer = self.right.get_indexer(target_as_index.right) indexer = np.where(left_indexer == right_indexer, left_indexer, -1) elif not is_object_dtype(target_as_index): ...
class IntervalIndex(IntervalMixin, Index): left_indexer = self.left.get_indexer(target_as_index.left) right_indexer = self.right.get_indexer(target_as_index.right) indexer = np.where(left_indexer == right_indexer, left_indexer, -1) elif is_categorical(target_as_index): ...
class TestDataFrameAnalytics: tm.assert_frame_equal(result, expected) # --------------------------------------------------------------------- # Clip
class TestDataFrameAnalytics: tm.assert_frame_equal(result, expected) def test_round_interval_category_columns(self): # GH 30063 columns = pd.CategoricalIndex(pd.interval_range(0, 2)) df = DataFrame([[0.66, 1.1], [0.3, 0.25]], columns=columns) result = df.round() e...
import re import numpy as np import pytest from pandas import Interval, IntervalIndex, Timedelta, date_range, timedelta_range from pandas.core.indexes.base import InvalidIndexError import pandas.util.testing as tm
import re import numpy as np import pytest from pandas import ( CategoricalIndex, Interval, IntervalIndex, Timedelta, date_range, timedelta_range, ) from pandas.core.indexes.base import InvalidIndexError import pandas.util.testing as tm
class TestGetIndexer: expected = np.array([0] * size, dtype="intp") tm.assert_numpy_array_equal(result, expected) @pytest.mark.parametrize( "tuples, closed", [
class TestGetIndexer: expected = np.array([0] * size, dtype="intp") tm.assert_numpy_array_equal(result, expected) @pytest.mark.parametrize( "target", [ IntervalIndex.from_tuples([(7, 8), (1, 2), (3, 4), (0, 1)]), IntervalIndex.from_tuples([(0, 1), (1, 2), (3,...
class Categorical(ExtensionArray, PandasObject): good = self._codes != -1 if not good.all(): if skipna: pointer = self._codes[good].min() else: return np.nan
class Categorical(ExtensionArray, PandasObject): good = self._codes != -1 if not good.all(): if skipna and good.any(): pointer = self._codes[good].min() else: return np.nan
class Categorical(ExtensionArray, PandasObject): good = self._codes != -1 if not good.all(): if skipna: pointer = self._codes[good].max() else: return np.nan
class Categorical(ExtensionArray, PandasObject): good = self._codes != -1 if not good.all(): if skipna and good.any(): pointer = self._codes[good].max() else: return np.nan
class TestCategoricalAnalytics: assert _min == 2 assert _max == 1 @pytest.mark.parametrize("method", ["min", "max"]) def test_deprecate_numeric_only_min_max(self, method): # GH 25303
class TestCategoricalAnalytics: assert _min == 2 assert _max == 1 @pytest.mark.parametrize("function", ["min", "max"]) @pytest.mark.parametrize("skipna", [True, False]) def test_min_max_only_nan(self, function, skipna): # https://github.com/pandas-dev/pandas/issues/33450 ...
import logging from six.moves.urllib.parse import urljoin from scrapy.http import HtmlResponse from scrapy.utils.response import get_meta_refresh from scrapy.utils.python import to_native_str from scrapy.exceptions import IgnoreRequest, NotConfigured logger = logging.getLogger(__name__)
import logging from six.moves.urllib.parse import urljoin from w3lib.url import safe_url_string from scrapy.http import HtmlResponse from scrapy.utils.response import get_meta_refresh from scrapy.exceptions import IgnoreRequest, NotConfigured logger = logging.getLogger(__name__)
class RedirectMiddleware(BaseRedirectMiddleware): if 'Location' not in response.headers or response.status not in allowed_status: return response # HTTP header is ascii or latin1, redirected url will be percent-encoded utf-8 location = to_native_str(response.headers['location'].deco...
class RedirectMiddleware(BaseRedirectMiddleware): if 'Location' not in response.headers or response.status not in allowed_status: return response location = safe_url_string(response.headers['location']) redirected_url = urljoin(request.url, location)
class RedirectMiddlewareTest(unittest.TestCase): latin1_location = u'/ação'.encode('latin1') # HTTP historically supports latin1 resp = Response('http://scrapytest.org/first', headers={'Location': latin1_location}, status=302) req_result = self.mw.process_response(req, resp, self.spider) ...
class RedirectMiddlewareTest(unittest.TestCase): latin1_location = u'/ação'.encode('latin1') # HTTP historically supports latin1 resp = Response('http://scrapytest.org/first', headers={'Location': latin1_location}, status=302) req_result = self.mw.process_response(req, resp, self.spider) ...
def _readInlineImage(self, stream): # left at beginning of ID tmp = stream.read(3) assert tmp[:2] == b_("ID") data = b_("") while True: # Read the inline image, while checking for EI (End Image) operator. tok = stream.read(1) if tok == b_("E"):...
def _readInlineImage(self, stream): # left at beginning of ID tmp = stream.read(3) assert tmp[:2] == b_("ID") data = BytesIO() # Read the inline image, while checking for EI (End Image) operator. while True: # Read 8 kB at a time and check if the chunk contain...
def _readInlineImage(self, stream): stream.seek(-1, 1) break else: stream.seek(-1,1) data += info else: stream.seek(-1, 1) data += tok e...
def _readInlineImage(self, stream): stream.seek(-1, 1) break else: stream.seek(-1, 1) data.write(info) else: stream.seek(-1, 1) data.write(tok) ...
def aesEncrypt(data, key): except ImportError: from Crypto.Cipher import AES def aesEncrypt(data, key): cipher = AES.new(key) data = data + (" " * (16 - (len(data) % 16))) return cipher.encrypt(data) def aesDecrypt(data, key): cipher = AES.new(key) return cipher....
def aesEncrypt(data, key): except ImportError: from Crypto.Cipher import AES from Crypto.Util import Counter def aesEncrypt(data, key): cipher = AES.new(key, AES.MODE_CTR, counter=Counter.new(128, initial_value=0)) return cipher.encrypt(data) def aesDecrypt(d...
def act(fp): self.assertFalse(fp.closed) def test_overrun(self): for file in ["fli_overrun.bin", "sgi_overrun.bin", "pcx_overrun.bin"]: im = Image.open(os.path.join("Tests/images", file)) try: im.load()
def act(fp): self.assertFalse(fp.closed) def test_overrun(self): for file in [ "fli_overrun.bin", "sgi_overrun.bin", "pcx_overrun.bin", "pcx_overrun2.bin", ]: im = Image.open(os.path.join("Tests/images", file)) try:...
class Categorical(ExtensionArray, PandasObject): Only ordered `Categoricals` have a minimum! Raises ------ TypeError
class Categorical(ExtensionArray, PandasObject): Only ordered `Categoricals` have a minimum! .. versionchanged:: 1.0.0 Returns an NA value on empty arrays Raises ------ TypeError
class Categorical(ExtensionArray, PandasObject): min : the minimum of this `Categorical` """ self.check_for_ordered("min") good = self._codes != -1 if not good.all(): if skipna:
class Categorical(ExtensionArray, PandasObject): min : the minimum of this `Categorical` """ self.check_for_ordered("min") if not len(self._codes): return self.dtype.na_value good = self._codes != -1 if not good.all(): if skipna:
class Categorical(ExtensionArray, PandasObject): Only ordered `Categoricals` have a maximum! Raises ------ TypeError
class Categorical(ExtensionArray, PandasObject): Only ordered `Categoricals` have a maximum! .. versionchanged:: 1.0.0 Returns an NA value on empty arrays Raises ------ TypeError
class Categorical(ExtensionArray, PandasObject): max : the maximum of this `Categorical` """ self.check_for_ordered("max") good = self._codes != -1 if not good.all(): if skipna:
class Categorical(ExtensionArray, PandasObject): max : the maximum of this `Categorical` """ self.check_for_ordered("max") if not len(self._codes): return self.dtype.na_value good = self._codes != -1 if not good.all(): if skipna:
import pytest from pandas.compat import PYPY from pandas import Categorical, Index, Series from pandas.api.types import is_scalar import pandas.util.testing as tm class TestCategoricalAnalytics: def test_min_max(self): # unordered cats have no min/max cat = Categorical(["a", "b", "c", "d"], ord...
import pytest from pandas.compat import PYPY from pandas import Categorical, Index, NaT, Series, date_range from pandas.api.types import is_scalar import pandas.util.testing as tm class TestCategoricalAnalytics: @pytest.mark.parametrize("aggregation", ["min", "max"]) def test_min_max_not_ordered_raises(self...
class TestCategoricalAnalytics: assert _min == "d" assert _max == "a" @pytest.mark.parametrize("skipna", [True, False]) def test_min_max_with_nan(self, skipna): # GH 25303
class TestCategoricalAnalytics: assert _min == "d" assert _max == "a" @pytest.mark.parametrize( "categories,expected", [ (list("ABC"), np.NaN), ([1, 2, 3], np.NaN), pytest.param( Series(date_range("2020-01-01", periods=3), dtype="c...
class BlockManager(PandasObject): if len(self.blocks) != len(other.blocks): return False # canonicalize block order, using a tuple combining the type # name and then mgr_locs because there might be unconsolidated # blocks (say, Categorical) which can only be distinguished by...
class BlockManager(PandasObject): if len(self.blocks) != len(other.blocks): return False # canonicalize block order, using a tuple combining the mgr_locs # then type name because there might be unconsolidated # blocks (say, Categorical) which can only be distinguished by ...
def test_make_block_no_pandas_array(): result = make_block(arr.to_numpy(), slice(len(arr)), dtype=arr.dtype) assert result.is_integer is True assert result.is_extension is False
def test_make_block_no_pandas_array(): result = make_block(arr.to_numpy(), slice(len(arr)), dtype=arr.dtype) assert result.is_integer is True assert result.is_extension is False def test_dataframe_not_equal(): # see GH28839 df1 = pd.DataFrame({"a": [1, 2], "b": ["s", "d"]}) df2 = pd.DataFrame(...
def _junos_interfaces_ifconfig(out): pmac = re.compile("curr media .*? ([0-9a-f:]+)") pip = re.compile( r".*?inet\s*(primary)*\s+mtu (\d+)\s+local=[^\d]*(.*?)\s+dest=[^\d]*(.*?)\/([\d]*)\s+bcast=((?:[0-9]{1,3}\.){3}[0-9]{1,3})" ) pip6 = re.compile( r".*?inet6 mtu [^\d]+\s+local=([0-9a-f...
def _junos_interfaces_ifconfig(out): pmac = re.compile("curr media .*? ([0-9a-f:]+)") pip = re.compile( r".*?inet\s*(primary)*\s+mtu" r" (\d+)\s+local=[^\d]*(.*?)\s{0,40}dest=[^\d]*(.*?)\/([\d]*)\s{0,40}bcast=((?:[0-9]{1,3}\.){3}[0-9]{1,3})" ) pip6 = re.compile( r".*?inet6 mtu [...
class TestUtil(unittest.TestCase): "playlist":[{"controls":{"all":null}}] }''') def test_js_to_json_edgecases(self): on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}") self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
class TestUtil(unittest.TestCase): "playlist":[{"controls":{"all":null}}] }''') inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"' json_code = js_to_json(inp) self.assertEqual(json.loads(json_code...
def js_to_json(code): return '"%s"' % v res = re.sub(r'''(?x) "(?:[^"\\]*(?:\\\\|\\")?)*"| '(?:[^'\\]*(?:\\\\|\\')?)*'| [a-zA-Z_][.a-zA-Z_0-9]* ''', fix_kv, code) res = re.sub(r',(\s*\])', lambda m: m.group(1), res)
def js_to_json(code): return '"%s"' % v res = re.sub(r'''(?x) "(?:[^"\\]*(?:\\\\|\\['"nu]))*[^"\\]*"| '(?:[^'\\]*(?:\\\\|\\['"nu]))*[^'\\]*'| [a-zA-Z_][.a-zA-Z_0-9]* ''', fix_kv, code) res = re.sub(r',(\s*\])', lambda m: m.group(1), res)
from waitress.buffers import OverflowableBuffer from waitress.receiver import ChunkedReceiver, FixedStreamReceiver from waitress.utilities import ( BadRequest, RequestEntityTooLarge,
from waitress.buffers import OverflowableBuffer from waitress.receiver import ChunkedReceiver, FixedStreamReceiver from waitress.rfc7230 import HEADER_FIELD_RE, ONLY_DIGIT_RE from waitress.utilities import ( BadRequest, RequestEntityTooLarge,
find_double_newline, ) from .rfc7230 import HEADER_FIELD def unquote_bytes_to_wsgi(bytestring): return unquote_to_bytes(bytestring).decode("latin-1")
find_double_newline, ) def unquote_bytes_to_wsgi(bytestring): return unquote_to_bytes(bytestring).decode("latin-1")
def parse_header(self, header_plus): headers = self.headers for line in lines: header = HEADER_FIELD.match(line) if not header: raise ParsingError("Invalid header")
def parse_header(self, header_plus): headers = self.headers for line in lines: header = HEADER_FIELD_RE.match(line) if not header: raise ParsingError("Invalid header")
def parse_header(self, header_plus): self.connection_close = True if not self.chunked: try: cl = int(headers.get("CONTENT_LENGTH", 0)) except ValueError: raise ParsingError("Content-Length is invalid") self.content_length = cl...
def parse_header(self, header_plus): self.connection_close = True if not self.chunked: cl = headers.get("CONTENT_LENGTH", "0") if not ONLY_DIGIT_RE.match(cl.encode("latin-1")): raise ParsingError("Content-Length is invalid") cl = int(cl) ...
"""Data Chunk Receiver """ from waitress.utilities import BadRequest, find_double_newline
"""Data Chunk Receiver """ from waitress.rfc7230 import CHUNK_EXT_RE, ONLY_HEXDIG_RE from waitress.utilities import BadRequest, find_double_newline
def received(self, s): s = b"" else: self.chunk_end = b"" if pos == 0: # Chop off the terminating CR LF from the chunk s = s[2:]
def received(self, s): s = b"" else: self.chunk_end = b"" if pos == 0: # Chop off the terminating CR LF from the chunk s = s[2:]
def received(self, s): line = s[:pos] s = s[pos + 2 :] self.control_line = b"" line = line.strip() if line: # Begin a new chunk. semi = line.find(b";") ...
def received(self, s): line = s[:pos] s = s[pos + 2 :] self.control_line = b"" if line: # Begin a new chunk. semi = line.find(b";") if semi >= 0: ...
import re WS = "[ \t]" OWS = WS + "{0,}?" RWS = WS + "{1,}?"
import re HEXDIG = "[0-9a-fA-F]" DIGIT = "[0-9]" WS = "[ \t]" OWS = WS + "{0,}?" RWS = WS + "{1,}?"
# ; visible (printing) characters VCHAR = r"\x21-\x7e" # header-field = field-name ":" OWS field-value OWS # field-name = token # field-value = *( field-content / obs-fold )
# ; visible (printing) characters VCHAR = r"\x21-\x7e" # The '\\' between \x5b and \x5d is needed to escape \x5d (']') QDTEXT = "[\t \x21\x23-\x5b\\\x5d-\x7e" + OBS_TEXT + "]" QUOTED_PAIR = r"\\" + "([\t " + VCHAR + OBS_TEXT + "])" QUOTED_STRING = '"(?:(?:' + QDTEXT + ")|(?:" + QUOTED_PAIR + '))*"' ...
# Which allows the field value here to just see if there is even a value in the first place FIELD_VALUE = "(?:" + FIELD_CONTENT + ")?" HEADER_FIELD = re.compile( ( "^(?P<name>" + TOKEN + "):" + OWS + "(?P<value>" + FIELD_VALUE + ")" + OWS + "$" ).encode("latin-1") )
# Which allows the field value here to just see if there is even a value in the first place FIELD_VALUE = "(?:" + FIELD_CONTENT + ")?" # chunk-ext = *( ";" chunk-ext-name [ "=" chunk-ext-val ] ) # chunk-ext-name = token # chunk-ext-val = token / quoted-string CHUNK_EXT_NAME = TOKEN CHUNK_EXT_VAL = "(?:" + TOKEN...
import stat import time from .rfc7230 import OBS_TEXT, VCHAR logger = logging.getLogger("waitress") queue_logger = logging.getLogger("waitress.queue")
import stat import time from .rfc7230 import QUOTED_PAIR_RE, QUOTED_STRING_RE logger = logging.getLogger("waitress") queue_logger = logging.getLogger("waitress.queue")
def parse_http_date(d): return retval # RFC 5234 Appendix B.1 "Core Rules": # VCHAR = %x21-7E # ; visible (printing) characters vchar_re = VCHAR # RFC 7230 Section 3.2.6 "Field Value Components": # quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE # qdtext = HTAB / SP /%x21...
def parse_http_date(d): return retval def undquote(value): if value.startswith('"') and value.endswith('"'): # So it claims to be DQUOTE'ed, let's validate that matches = QUOTED_STRING_RE.match(value) if matches and matches.end() == len(value): # Remove the DQUOTE's from t...
def undquote(value): # Remove all backslashes that are followed by a valid vchar or # obs-text value = quoted_pair.sub(r"\1", value) return value elif not value.startswith('"') and not value.endswith('"'):
def undquote(value): # Remove all backslashes that are followed by a valid vchar or # obs-text value = QUOTED_PAIR_RE.sub(r"\1", value) return value elif not value.startswith('"') and not value.endswith('"'):
def test_chunking_request_without_content(self): self.assertFalse("transfer-encoding" in headers) def test_chunking_request_with_content(self): control_line = b"20;\r\n" # 20 hex = 32 dec s = b"This string has 32 characters.\r\n" expected = s * 12 header = b"GET / HTTP/...
def test_chunking_request_without_content(self): self.assertFalse("transfer-encoding" in headers) def test_chunking_request_with_content(self): control_line = b"20\r\n" # 20 hex = 32 dec s = b"This string has 32 characters.\r\n" expected = s * 12 header = b"GET / HTTP/1...
def test_chunking_request_with_content(self): self.assertFalse("transfer-encoding" in headers) def test_broken_chunked_encoding(self): control_line = b"20;\r\n" # 20 hex = 32 dec s = b"This string has 32 characters.\r\n" to_send = b"GET / HTTP/1.1\r\nTransfer-Encoding: chunked\...
def test_chunking_request_with_content(self): self.assertFalse("transfer-encoding" in headers) def test_broken_chunked_encoding(self): control_line = b"20\r\n" # 20 hex = 32 dec s = b"This string has 32 characters.\r\n" to_send = b"GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r...
def test_broken_chunked_encoding(self): self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_broken_chunked_encoding_missing_chunk_end(self): control_line = b"20;\r\n" # 20 hex = 32 dec s = b"This string has 32 characters.\r\n" ...
def test_broken_chunked_encoding(self): self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_broken_chunked_encoding_invalid_hex(self): control_line = b"0x20\r\n" # 20 hex = 32 dec s = b"This string has 32 characters.\r\n" to_se...
def test_received_chunked_completed_sets_content_length(self): b"Transfer-Encoding: chunked\r\n" b"X-Foo: 1\r\n" b"\r\n" b"1d;\r\n" b"This string has 29 characters\r\n" b"0\r\n\r\n" )
def test_received_chunked_completed_sets_content_length(self): b"Transfer-Encoding: chunked\r\n" b"X-Foo: 1\r\n" b"\r\n" b"1d\r\n" b"This string has 29 characters\r\n" b"0\r\n\r\n" )
def test_parse_header_bad_content_length(self): else: # pragma: nocover self.assertTrue(False) def test_parse_header_multiple_content_length(self): data = b"GET /foobar HTTP/8.4\r\ncontent-length: 10\r\ncontent-length: 20\r\n"
def test_parse_header_bad_content_length(self): else: # pragma: nocover self.assertTrue(False) def test_parse_header_bad_content_length_plus(self): data = b"GET /foobar HTTP/8.4\r\ncontent-length: +10\r\n" try: self.parser.parse_header(data) except ParsingE...
import unittest class TestFixedStreamReceiver(unittest.TestCase): def _makeOne(self, cl, buf):
import unittest import pytest class TestFixedStreamReceiver(unittest.TestCase): def _makeOne(self, cl, buf):
def test_received_multiple_chunks_split(self): self.assertEqual(inst.error, None) class DummyBuffer: def __init__(self, data=None): if data is None:
def test_received_multiple_chunks_split(self): self.assertEqual(inst.error, None) class TestChunkedReceiverParametrized: def _makeOne(self, buf): from waitress.receiver import ChunkedReceiver return ChunkedReceiver(buf) @pytest.mark.parametrize( "invalid_extension", [b"\n", b...
'pytz', 'pyOpenSSL', 'python-dateutil', 'six' ]
'pytz', 'pyOpenSSL', 'python-dateutil', 'defusedxml', 'six' ]
import cElementTree as ElementTree except ImportError: from elementtree import ElementTree root_logger = logging.getLogger(__name__) root_logger.level = logging.NOTSET
import cElementTree as ElementTree except ImportError: from elementtree import ElementTree import defusedxml.ElementTree root_logger = logging.getLogger(__name__) root_logger.level = logging.NOTSET
def create_class_from_xml_string(target_class, xml_string): """ if not isinstance(xml_string, six.binary_type): xml_string = xml_string.encode('utf-8') tree = ElementTree.fromstring(xml_string) return create_class_from_element_tree(target_class, tree)
def create_class_from_xml_string(target_class, xml_string): """ if not isinstance(xml_string, six.binary_type): xml_string = xml_string.encode('utf-8') tree = defusedxml.ElementTree.fromstring(xml_string) return create_class_from_element_tree(target_class, tree)
def loadd(self, ava): def extension_element_from_string(xml_string): element_tree = ElementTree.fromstring(xml_string) return _extension_element_from_element_tree(element_tree)
def loadd(self, ava): def extension_element_from_string(xml_string): element_tree = defusedxml.ElementTree.fromstring(xml_string) return _extension_element_from_element_tree(element_tree)
import cElementTree as ElementTree except ImportError: from elementtree import ElementTree NAMESPACE = "http://schemas.xmlsoap.org/soap/envelope/" FORM_SPEC = """<form method="post" action="%s">
import cElementTree as ElementTree except ImportError: from elementtree import ElementTree import defusedxml.ElementTree NAMESPACE = "http://schemas.xmlsoap.org/soap/envelope/" FORM_SPEC = """<form method="post" action="%s">
def parse_soap_enveloped_saml(text, body_class, header_class=None): :param text: The SOAP object as XML :return: header parts and body as saml.samlbase instances """ envelope = ElementTree.fromstring(text) assert envelope.tag == '{%s}Envelope' % NAMESPACE # print(len(envelope))
def parse_soap_enveloped_saml(text, body_class, header_class=None): :param text: The SOAP object as XML :return: header parts and body as saml.samlbase instances """ envelope = defusedxml.ElementTree.fromstring(text) assert envelope.tag == '{%s}Envelope' % NAMESPACE # print(len(envelope))
except ImportError: #noinspection PyUnresolvedReferences from elementtree import ElementTree logger = logging.getLogger(__name__)
except ImportError: #noinspection PyUnresolvedReferences from elementtree import ElementTree import defusedxml.ElementTree logger = logging.getLogger(__name__)
def parse_soap_enveloped_saml_thingy(text, expected_tags): :param expected_tags: What the tag of the SAML thingy is expected to be. :return: SAML thingy as a string """ envelope = ElementTree.fromstring(text) # Make sure it's a SOAP message assert envelope.tag == '{%s}Envelope' % soapenv.NAMESP...
def parse_soap_enveloped_saml_thingy(text, expected_tags): :param expected_tags: What the tag of the SAML thingy is expected to be. :return: SAML thingy as a string """ envelope = defusedxml.ElementTree.fromstring(text) # Make sure it's a SOAP message assert envelope.tag == '{%s}Envelope' % soa...
def class_instances_from_soap_enveloped_saml_thingies(text, modules): :return: The body and headers as class instances """ try: envelope = ElementTree.fromstring(text) except Exception as exc: raise XmlParseError("%s" % exc)
def class_instances_from_soap_enveloped_saml_thingies(text, modules): :return: The body and headers as class instances """ try: envelope = defusedxml.ElementTree.fromstring(text) except Exception as exc: raise XmlParseError("%s" % exc)
def open_soap_envelope(text): :return: dictionary with two keys "body"/"header" """ try: envelope = ElementTree.fromstring(text) except Exception as exc: raise XmlParseError("%s" % exc)
def open_soap_envelope(text): :return: dictionary with two keys "body"/"header" """ try: envelope = defusedxml.ElementTree.fromstring(text) except Exception as exc: raise XmlParseError("%s" % exc)
import cElementTree as ElementTree except ImportError: from elementtree import ElementTree ITEMS = { NameID: ["""<?xml version="1.0" encoding="utf-8"?>
import cElementTree as ElementTree except ImportError: from elementtree import ElementTree from defusedxml.common import EntitiesForbidden ITEMS = { NameID: ["""<?xml version="1.0" encoding="utf-8"?>
def test_create_class_from_xml_string_wrong_class_spec(): assert kl == None def test_ee_1(): ee = saml2.extension_element_from_string( """<?xml version='1.0' encoding='UTF-8'?><foo>bar</foo>""")
def test_create_class_from_xml_string_wrong_class_spec(): assert kl == None def test_create_class_from_xml_string_xxe(): xml = """<?xml version="1.0"?> <!DOCTYPE lolz [ <!ENTITY lol "lol"> <!ELEMENT lolz (#PCDATA)> <!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;"> ]> ...
def test_ee_7(): assert nid.text.strip() == "http://federationX.org" def test_extension_element_loadd(): ava = {'attributes': {}, 'tag': 'ExternalEntityAttributeAuthority',
def test_ee_7(): assert nid.text.strip() == "http://federationX.org" def test_ee_xxe(): xml = """<?xml version="1.0"?> <!DOCTYPE lolz [ <!ENTITY lol "lol"> <!ELEMENT lolz (#PCDATA)> <!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;"> ]> <lolz>&lol1;</lolz> """ w...
import cElementTree as ElementTree except ImportError: from elementtree import ElementTree import saml2.samlp as samlp from saml2.samlp import NAMESPACE as SAMLP_NAMESPACE NAMESPACE = "http://schemas.xmlsoap.org/soap/envelope/"
import cElementTree as ElementTree except ImportError: from elementtree import ElementTree from defusedxml.common import EntitiesForbidden from pytest import raises import saml2.samlp as samlp from saml2.samlp import NAMESPACE as SAMLP_NAMESPACE from saml2 import soap NAMESPACE = "http://schemas....
def test_make_soap_envelope(): assert len(body) == 1 saml_part = body[0] assert saml_part.tag == '{%s}AuthnRequest' % SAMLP_NAMESPACE
def test_make_soap_envelope(): assert len(body) == 1 saml_part = body[0] assert saml_part.tag == '{%s}AuthnRequest' % SAMLP_NAMESPACE def test_parse_soap_enveloped_saml_thingy_xxe(): xml = """<?xml version="1.0"?> <!DOCTYPE lolz [ <!ENTITY lol "lol"> <!ELEMENT lolz (#PCDATA)> <!ENTITY ...
from future.backports.urllib.parse import parse_qs from future.backports.urllib.parse import urlencode from future.backports.urllib.parse import urlparse from saml2.argtree import add_path from saml2.cert import OpenSSLWrapper
from future.backports.urllib.parse import parse_qs from future.backports.urllib.parse import urlencode from future.backports.urllib.parse import urlparse from pytest import raises from saml2.argtree import add_path from saml2.cert import OpenSSLWrapper
from saml2.authn_context import INTERNETPROTOCOLPASSWORD from saml2.client import Saml2Client from saml2.config import SPConfig from saml2.response import LogoutResponse from saml2.saml import NAMEID_FORMAT_PERSISTENT, EncryptedAssertion, Advice from saml2.saml import NAMEID_FORMAT_TRANSIENT
from saml2.authn_context import INTERNETPROTOCOLPASSWORD from saml2.client import Saml2Client from saml2.config import SPConfig from saml2.pack import parse_soap_enveloped_saml from saml2.response import LogoutResponse from saml2.saml import NAMEID_FORMAT_PERSISTENT, EncryptedAssertion, Advice from saml2.saml import NA...
from saml2.s_utils import factory from saml2.time_util import in_a_while, a_while_ago from fakeIDP import FakeIDP from fakeIDP import unpack_form from pathutils import full_path
from saml2.s_utils import factory from saml2.time_util import in_a_while, a_while_ago from defusedxml.common import EntitiesForbidden from fakeIDP import FakeIDP from fakeIDP import unpack_form from pathutils import full_path
def test_negotiated_post_sso(self): 'http://www.example.com/login' assert ac.authn_context_class_ref.text == INTERNETPROTOCOLPASSWORD # if __name__ == "__main__": # tc = TestClient()
def test_negotiated_post_sso(self): 'http://www.example.com/login' assert ac.authn_context_class_ref.text == INTERNETPROTOCOLPASSWORD def test_parse_soap_enveloped_saml_xxe(): xml = """<?xml version="1.0"?> <!DOCTYPE lolz [ <!ENTITY lol "lol"> <!ELEMENT lolz (#PCDATA)> <!ENTI...
def decode_raw(input_bytes, name=None): r"""Convert raw bytes from input tensor into numeric tensors. The input tensor is interpreted as a sequence of bytes. These bytes are then decoded as numbers in the format specified by `out_type`. >>> tf.io.decode_raw(tf.constant("1"), tf.uint8) <tf.Ten...
def decode_raw(input_bytes, name=None): r"""Convert raw bytes from input tensor into numeric tensors. Every component of the input tensor is interpreted as a sequence of bytes. These bytes are then decoded as numbers in the format specified by `out_type`. >>> tf.io.decode_raw(tf.constant("1"), ...
def decode_raw(input_bytes, >>> tf.io.decode_raw(tf.constant(["1212"]), tf.uint16, fixed_length=4) <tf.Tensor: shape=(1, 2), dtype=uint16, numpy=array([[12849, 12849]], ... Note: There is currently a bug in `fixed_length` that can result in data loss: >>> # truncated to length of type as it matches fixed_leng...
def decode_raw(input_bytes, >>> tf.io.decode_raw(tf.constant(["1212"]), tf.uint16, fixed_length=4) <tf.Tensor: shape=(1, 2), dtype=uint16, numpy=array([[12849, 12849]], ... If the input value is larger than `fixed_length`, it is truncated: >>> x=''.join([chr(1), chr(2), chr(3), chr(4)]) >>> tf.io.decode_raw...
setup( name='sopel_plugins.channelmgnt', version='1.0.2', description='Channelmgnt plugin for Sopel', long_description=readme, long_description_content_type='text/markdown', # This is important!
setup( name='sopel_plugins.channelmgnt', version='1.0.3', description='Channelmgnt plugin for Sopel', long_description=readme, long_description_content_type='text/markdown', # This is important!
def makemodechange(bot, trigger, mode, isusermode=False, isbqmode=False, selfsaf bot.say('Attempting to OP...') bot.say('op ' + trigger.sender, 'ChanServ') time.sleep(1) if isusermode and not trigger.group(2): bot.write(['MODE', trigger.sender, mode, trigger.nick]...
def makemodechange(bot, trigger, mode, isusermode=False, isbqmode=False, selfsaf bot.say('Attempting to OP...') bot.say('op ' + trigger.sender, 'ChanServ') time.sleep(1) if isusermode and not trigger.group(2) and selfsafe: bot.write(['MODE', trigger.sender, mode, ...
def _decryptRecord(self, recordType, b): if self.version >= (3,2): #For TLS 1.1, remove explicit IV b = b[self._readState.encContext.block_size : ] #Check padding paddingGood = True paddingLength = b[-1]
def _decryptRecord(self, recordType, b): if self.version >= (3,2): #For TLS 1.1, remove explicit IV b = b[self._readState.encContext.block_size : ] if len(b) == 0: for result in self._sendError(\ AlertDescription.decryp...
def l2_normalize(x, axis=-1): return x / np.sqrt(y) def binary_crossentropy(target, output, from_logits=False): if not from_logits: output = np.clip(output, 1e-7, 1 - 1e-7)
def l2_normalize(x, axis=-1): return x / np.sqrt(y) def in_top_k(predictions, targets, k): top_k = np.argsort(-predictions)[:, :k] targets = targets.reshape(-1, 1) return np.any(targets == top_k, axis=-1) def binary_crossentropy(target, output, from_logits=False): if not from_logits: out...
class TestBackend(object): check_single_tensor_operation('l2_normalize', (4, 3), WITH_NP, axis=-1) check_single_tensor_operation('l2_normalize', (4, 3), WITH_NP, axis=1) def test_in_top_k(self): batch_size = 20 num_classes = 10
class TestBackend(object): check_single_tensor_operation('l2_normalize', (4, 3), WITH_NP, axis=-1) check_single_tensor_operation('l2_normalize', (4, 3), WITH_NP, axis=1) @pytest.mark.skipif(K.backend() == 'cntk', reason='Bug in CNTK') def test_in_top_k(self): batch_size = 20 num...
class TestBackend(object): # (k == 0 or k > num_classes) does not raise an error # but just return an unmeaningful tensor. for k in range(num_classes + 1): z_list = [b.eval(b.in_top_k(b.variable(predictions, dtype='float32'), b.variable(target...
class TestBackend(object): # (k == 0 or k > num_classes) does not raise an error # but just return an unmeaningful tensor. for k in range(1, num_classes + 1): z_list = [b.eval(b.in_top_k(b.variable(predictions, dtype='float32'), b.variable(tar...
class TestBackend(object): for k in range(1, num_classes + 1): z_list = [b.eval(b.in_top_k(b.variable(predictions, dtype='float32'), b.variable(targets, dtype='int32'), k)) for b in [KTH, KTF]] assert_list_pairwise(z_list) ...
class TestBackend(object): for k in range(1, num_classes + 1): z_list = [b.eval(b.in_top_k(b.variable(predictions, dtype='float32'), b.variable(targets, dtype='int32'), k)) for b in WITH_NP] assert_list_pairwise(z_list) @...
class MultiPartParser: remaining = len(stripped_chunk) % 4 while remaining != 0: over_chunk = field_stream.read(4 - remaining) stripped_chunk += b"".join(over_chunk.split()) ...
class MultiPartParser: remaining = len(stripped_chunk) % 4 while remaining != 0: over_chunk = field_stream.read(4 - remaining) if not over_chunk: ...
class FileUploadTests(TestCase): def test_big_base64_newlines_upload(self): self._test_base64_upload("Big data" * 68000, encode=base64.encodebytes) def test_unicode_file_name(self): with sys_tempfile.TemporaryDirectory() as temp_dir: # This file contains Chinese symbols and an accen...
class FileUploadTests(TestCase): def test_big_base64_newlines_upload(self): self._test_base64_upload("Big data" * 68000, encode=base64.encodebytes) def test_base64_invalid_upload(self): payload = client.FakePayload('\r\n'.join([ '--' + client.BOUNDARY, 'Content-Dispositi...
import socks except (ImportError, AttributeError): socks = None # Build the appropriate socket wrapper for ssl ssl = None
import socks except (ImportError, AttributeError): socks = None from httplib2 import auth from httplib2.error import * # Build the appropriate socket wrapper for ssl ssl = None
ssl_CertificateError = getattr(ssl, "CertificateError", None) def _ssl_wrap_socket( sock, key_file, cert_file, disable_validation, ca_certs, ssl_version, hostname, key_password ): if disable_validation: cert_reqs = ssl.CERT_NONE else:
ssl_CertificateError = getattr(ssl, "CertificateError", None) def _ssl_wrap_socket(sock, key_file, cert_file, disable_validation, ca_certs, ssl_version, hostname, key_password): if disable_validation: cert_reqs = ssl.CERT_NONE else:
def _ssl_wrap_socket( if key_password: raise NotSupportedOnThisPlatform("Certificate with password is not supported.") return ssl.wrap_socket( sock, keyfile=key_file, certfile=cert_file, cert_reqs=cert_reqs, ca_certs=ca_certs, ...
def _ssl_wrap_socket( if key_password: raise NotSupportedOnThisPlatform("Certificate with password is not supported.") return ssl.wrap_socket( sock, keyfile=key_file, certfile=cert_file, cert_reqs=cert_reqs, ca_certs=ca_certs, ssl_version=ssl_version, )
class NotRunningAppEngineEnvironment(HttpLib2Error): DEFAULT_MAX_REDIRECTS = 5 from httplib2 import certs CA_CERTS = certs.where() # Which headers are hop-by-hop headers by default
class NotRunningAppEngineEnvironment(HttpLib2Error): DEFAULT_MAX_REDIRECTS = 5 from httplib2 import certs CA_CERTS = certs.where() # Which headers are hop-by-hop headers by default
def safename(filename): def _normalize_headers(headers): return dict( [ (key.lower(), NORMALIZE_SPACE.sub(value, " ").strip()) for (key, value) in headers.iteritems() ] ) def _parse_cache_control(headers):
def safename(filename): def _normalize_headers(headers): return dict([(key.lower(), NORMALIZE_SPACE.sub(value, " ").strip()) for (key, value) in headers.iteritems()]) def _parse_cache_control(headers):
def _parse_cache_control(headers): if "cache-control" in headers: parts = headers["cache-control"].split(",") parts_with_args = [ tuple([x.strip().lower() for x in part.split("=", 1)]) for part in parts if -1 != part.find("=") ] parts_wo_args = [ ...
def _parse_cache_control(headers): if "cache-control" in headers: parts = headers["cache-control"].split(",") parts_with_args = [ tuple([x.strip().lower() for x in part.split("=", 1)]) for part in parts if -1 != part.find("=") ] parts_wo_args = [(name.strip().lower(), 1) ...
def _parse_cache_control(headers): # Set to true to turn on, usefull for testing servers. USE_WWW_AUTH_STRICT_PARSING = 0 # In regex below: # [^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+ matches a "token" as defined by HTTP # "(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?" matches a "quoted-st...
def _parse_cache_control(headers): # Set to true to turn on, usefull for testing servers. USE_WWW_AUTH_STRICT_PARSING = 0 # TODO: add current time as _entry_disposition argument to avoid sleep in tests def _entry_disposition(response_headers, request_headers):
def _entry_disposition(response_headers, request_headers): cc = _parse_cache_control(request_headers) cc_response = _parse_cache_control(response_headers) if ( "pragma" in request_headers and request_headers["pragma"].lower().find("no-cache") != -1 ): retval = "TRANSPARENT" ...
def _entry_disposition(response_headers, request_headers): cc = _parse_cache_control(request_headers) cc_response = _parse_cache_control(response_headers) if "pragma" in request_headers and request_headers["pragma"].lower().find("no-cache") != -1: retval = "TRANSPARENT" if "cache-control" n...
def _decompressContent(response, new_content): except (IOError, zlib.error): content = "" raise FailedToDecompressContent( _("Content purported to be compressed with %s but failed to decompress.") % response.get("content-encoding"), response, content, ...
def _decompressContent(response, new_content): except (IOError, zlib.error): content = "" raise FailedToDecompressContent( _("Content purported to be compressed with %s but failed to decompress.") % response.get("content-encoding"), response, content, )
def _updateCache(request_headers, response_headers, content, cache, cachekey): def _cnonce(): dig = _md5( "%s:%s" % (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)]) ).hexdigest() return dig[:16] def _wsse_username_token(cnonce, iso_now, password): return base...
def _updateCache(request_headers, response_headers, content, cache, cachekey): def _cnonce(): dig = _md5("%s:%s" % (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)])).hexdigest() return dig[:16] def _wsse_username_token(cnonce, iso_now, password): return base64.b64encode(_sha("%s%...
def _wsse_username_token(cnonce, iso_now, password): class Authentication(object): def __init__( self, credentials, host, request_uri, headers, response, content, http ): (scheme, authority, path, query, fragment) = parse_uri(request_uri) self.path = path self.host = host
def _wsse_username_token(cnonce, iso_now, password): class Authentication(object): def __init__(self, credentials, host, request_uri, headers, response, content, http): (scheme, authority, path, query, fragment) = parse_uri(request_uri) self.path = path self.host = host
def response(self, response, content): class BasicAuthentication(Authentication): def __init__( self, credentials, host, request_uri, headers, response, content, http ): Authentication.__init__( self, credentials, host, request_uri, headers, response, content, http ) d...
def response(self, response, content): class BasicAuthentication(Authentication): def __init__(self, credentials, host, request_uri, headers, response, content, http): Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http) def request(self, method, request_uri...
def request(self, method, request_uri, headers, content, cnonce=None): def response(self, response, content): if "authentication-info" not in response: challenge = _parse_www_authenticate(response, "www-authenticate").get( "digest", {} ) if "true" == chal...
def request(self, method, request_uri, headers, content, cnonce=None): def response(self, response, content): if "authentication-info" not in response: challenge = auth._parse_www_authenticate(response, "www-authenticate").get("digest", {}) if "true" == challenge.get("stale"): ...
class HmacDigestAuthentication(Authentication): __author__ = "Thomas Broyer (t.broyer@ltgt.net)" def __init__( self, credentials, host, request_uri, headers, response, content, http ): Authentication.__init__( self, credentials, host, request_uri, headers, response, content, ht...
class HmacDigestAuthentication(Authentication): __author__ = "Thomas Broyer (t.broyer@ltgt.net)" def __init__(self, credentials, host, request_uri, headers, response, content, http): Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http) challenge = aut...
def __init__( self.challenge["pw-algorithm"] = self.challenge.get("pw-algorithm", "SHA-1") if self.challenge["pw-algorithm"] not in ["SHA-1", "MD5"]: raise UnimplementedHmacDigestAuthOptionError( _( "Unsupported value for pw-algorithm: %s." ...
def __init__( self.challenge["pw-algorithm"] = self.challenge.get("pw-algorithm", "SHA-1") if self.challenge["pw-algorithm"] not in ["SHA-1", "MD5"]: raise UnimplementedHmacDigestAuthOptionError( _("Unsupported value for pw-algorithm: %s." % self.challenge["pw-algorithm"]) ...
def __init__( [ self.credentials[0], ":", self.pwhashmod.new( "".join([self.credentials[1], self.challenge["salt"]]) ) .hexdigest() .lower(), ":", self.challeng...
def __init__( [ self.credentials[0], ":", self.pwhashmod.new("".join([self.credentials[1], self.challenge["salt"]])).hexdigest().lower(), ":", self.challenge["realm"], ]
def request(self, method, request_uri, headers, content): headers_val = "".join([headers[k] for k in keys]) created = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) cnonce = _cnonce() request_digest = "%s:%s:%s:%s:%s" % ( method, request_uri, cnonc...
def request(self, method, request_uri, headers, content): headers_val = "".join([headers[k] for k in keys]) created = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) cnonce = _cnonce() request_digest = "%s:%s:%s:%s:%s" % (method, request_uri, cnonce, self.challenge["snonce"], headers_...