buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
print
print "cgi output"
'''
class PythonScript(twcgi.FilteredScript):
filter = sys.executable
| print
print "cgi output"
'''
HEADER_OUTPUT_CGI = '''\
import json
import os
print("")
print("")
vals = {x:y for x,y in os.environ.items() if x.startswith("HTTP_")}
print(json.dumps(vals))
'''
class PythonScript(twcgi.FilteredScript):
filter = sys.executable
|
class CGITests(unittest.TestCase):
return factory.deferred
def test_duplicateHeaderCGI(self):
"""
If a CGI script emits two instances of the same header, both are sent in | class CGITests(unittest.TestCase):
return factory.deferred
def test_noProxyPassthrough(self):
"""
The CGI script is never called with the Proxy header passed through.
"""
cgiFilename = self.writeCGI(HEADER_OUTPUT_CGI)
portnum = self.startServer(cgiFilename)
... |
class CGIScript(resource.Resource):
# Propagate HTTP headers
for title, header in request.getAllHeaders().items():
envname = title.replace('-', '_').upper()
if title not in ('content-type', 'content-length'):
envname = "HTTP_" + envname
env[envname] = ... | class CGIScript(resource.Resource):
# Propagate HTTP headers
for title, header in request.getAllHeaders().items():
envname = title.replace('-', '_').upper()
if title not in ('content-type', 'content-length', 'proxy'):
envname = "HTTP_" + envname
env[en... |
def _normalize(table, normalize, margins, margins_name="All"):
table = table.fillna(0)
elif margins is True:
column_margin = table.loc[:, margins_name].drop(margins_name)
index_margin = table.loc[margins_name, :].drop(margins_name)
table = table.drop(margins_name, axis=1).drop(marg... | def _normalize(table, normalize, margins, margins_name="All"):
table = table.fillna(0)
elif margins is True:
# keep index and column of pivoted table
table_index = table.index
table_columns = table.columns
# check if margin name is in (for MI cases) or equal to last
... |
def _normalize(table, normalize, margins, margins_name="All"):
column_margin = column_margin / column_margin.sum()
table = concat([table, column_margin], axis=1)
table = table.fillna(0)
elif normalize == "index":
index_margin = index_margin / index_margin.sum()
... | def _normalize(table, normalize, margins, margins_name="All"):
column_margin = column_margin / column_margin.sum()
table = concat([table, column_margin], axis=1)
table = table.fillna(0)
table.columns = table_columns
elif normalize == "index":
index_ma... |
def _normalize(table, normalize, margins, margins_name="All"):
table = table.append(index_margin)
table = table.fillna(0)
else:
raise ValueError("Not a valid normalize argument")
table.index.names = table_index_names
table.columns.names = table_columns_name... | def _normalize(table, normalize, margins, margins_name="All"):
table = table.append(index_margin)
table = table.fillna(0)
table.index = table_index
table.columns = table_columns
else:
raise ValueError("Not a valid normalize argument")
else:
... |
class TestCrosstab:
[[1, 0, 0], [0, 1, 0], [0, 0, 1]], index=e_idx, columns=e_columns
)
tm.assert_frame_equal(result, expected) | class TestCrosstab:
[[1, 0, 0], [0, 1, 0], [0, 0, 1]], index=e_idx, columns=e_columns
)
tm.assert_frame_equal(result, expected)
def test_margin_normalize(self):
# GH 27500
df = pd.DataFrame(
{
"A": ["foo", "foo", "foo", "foo", "foo", "bar", "b... |
class TestUtil(unittest.TestCase):
self.assertEqual(unified_timestamp('25-09-2014'), 1411603200)
self.assertEqual(unified_timestamp('27.02.2016 17:30'), 1456594200)
self.assertEqual(unified_timestamp('UNKNOWN DATE FORMAT'), None)
def test_determine_ext(self):
self.assertEqual(determ... | class TestUtil(unittest.TestCase):
self.assertEqual(unified_timestamp('25-09-2014'), 1411603200)
self.assertEqual(unified_timestamp('27.02.2016 17:30'), 1456594200)
self.assertEqual(unified_timestamp('UNKNOWN DATE FORMAT'), None)
self.assertEqual(unified_timestamp('May 16, 2016 11:15 PM'... |
def unified_timestamp(date_str, day_first=True):
date_str = date_str.replace(',', ' ')
pm_delta = datetime.timedelta(hours=12 if re.search(r'(?i)PM', date_str) else 0)
timezone, date_str = extract_timezone(date_str)
# Remove AM/PM + timezone | def unified_timestamp(date_str, day_first=True):
date_str = date_str.replace(',', ' ')
pm_delta = 12 if re.search(r'(?i)PM', date_str) else 0
timezone, date_str = extract_timezone(date_str)
# Remove AM/PM + timezone |
def unified_timestamp(date_str, day_first=True):
for expression in date_formats(day_first):
try:
dt = datetime.datetime.strptime(date_str, expression) - timezone + pm_delta
return calendar.timegm(dt.timetuple())
except ValueError:
pass
timetuple = email.utils... | def unified_timestamp(date_str, day_first=True):
for expression in date_formats(day_first):
try:
dt = datetime.datetime.strptime(date_str, expression) - timezone + datetime.timedelta(hours=pm_delta)
return calendar.timegm(dt.timetuple())
except ValueError:
pass
... |
class TestUtil(unittest.TestCase):
"1":{"src":"skipped", "type": "application/vnd.apple.mpegURL"}
}''')
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):
"1":{"src":"skipped", "type": "application/vnd.apple.mpegURL"}
}''')
inp = '''{"foo":101}'''
self.assertEqual(js_to_json(inp), '''{"foo":101}''')
def test_js_to_json_edgecases(self):
on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
... |
def js_to_json(code):
'(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
/\*.*?\*/|,(?=\s*[\]}])|
[a-zA-Z_][.a-zA-Z_0-9]*|
(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:\s*:)?|
[0-9]+(?=\s*:)
''', fix_kv, code)
| def js_to_json(code):
'(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
/\*.*?\*/|,(?=\s*[\]}])|
[a-zA-Z_][.a-zA-Z_0-9]*|
\b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:\s*:)?|
[0-9]+(?=\s*:)
''', fix_kv, code)
|
class Index(IndexOpsMixin, PandasObject):
pass
# Return an actual float index.
return Float64Index(data, copy=copy, dtype=dtype, name=name)
elif inferred == "string":
pass | class Index(IndexOpsMixin, PandasObject):
pass
# Return an actual float index.
return Float64Index(data, copy=copy, name=name)
elif inferred == "string":
pass |
from pandas.core.dtypes.common import (
is_float_dtype,
is_integer_dtype,
is_scalar,
needs_i8_conversion,
pandas_dtype,
) | from pandas.core.dtypes.common import (
is_float_dtype,
is_integer_dtype,
is_scalar,
is_signed_integer_dtype,
is_unsigned_integer_dtype,
needs_i8_conversion,
pandas_dtype,
) |
from pandas.core.dtypes.generic import (
)
from pandas.core.dtypes.missing import isna
from pandas.core import algorithms
import pandas.core.common as com
from pandas.core.indexes.base import Index, InvalidIndexError, _index_shared_docs | from pandas.core.dtypes.generic import (
)
from pandas.core.dtypes.missing import isna
from pandas._typing import Dtype
from pandas.core import algorithms
import pandas.core.common as com
from pandas.core.indexes.base import Index, InvalidIndexError, _index_shared_docs |
class NumericIndex(Index):
_is_numeric_dtype = True
def __new__(cls, data=None, dtype=None, copy=False, name=None, fastpath=None):
if fastpath is not None:
warnings.warn(
"The 'fastpath' keyword is deprecated, and will be " | class NumericIndex(Index):
_is_numeric_dtype = True
def __new__(cls, data=None, dtype=None, copy=False, name=None, fastpath=None):
cls._validate_dtype(dtype)
if fastpath is not None:
warnings.warn(
"The 'fastpath' keyword is deprecated, and will be " |
class NumericIndex(Index):
name = data.name
return cls._simple_new(subarr, name=name)
@Appender(_index_shared_docs["_maybe_cast_slice_bound"])
def _maybe_cast_slice_bound(self, label, side, kind):
assert kind in ["ix", "loc", "getitem", None] | class NumericIndex(Index):
name = data.name
return cls._simple_new(subarr, name=name)
@classmethod
def _validate_dtype(cls, dtype: Dtype) -> None:
if dtype is None:
return
validation_metadata = {
"int64index": (is_signed_integer_dtype, "signed integer... |
from pandas.util._decorators import Appender, cache_readonly
from pandas.core.dtypes.common import (
ensure_platform_int,
ensure_python_int,
is_int64_dtype,
is_integer,
is_integer_dtype,
is_list_like, | from pandas.util._decorators import Appender, cache_readonly
from pandas.core.dtypes.common import (
ensure_platform_int,
ensure_python_int,
is_integer,
is_integer_dtype,
is_list_like, |
class RangeIndex(Int64Index):
# --------------------------------------------------------------------
@staticmethod
def _validate_dtype(dtype):
""" require dtype to be None or int64 """
if not (dtype is None or is_int64_dtype(dtype)):
raise TypeError("Invalid to pass a non-int64... | class RangeIndex(Int64Index):
# --------------------------------------------------------------------
@cache_readonly
def _constructor(self):
""" return the class to use for construction """ |
class TestFloat64Index(Numeric):
result = Index(np.array([np.nan]))
assert pd.isna(result.values).all()
def test_constructor_invalid(self):
# invalid | class TestFloat64Index(Numeric):
result = Index(np.array([np.nan]))
assert pd.isna(result.values).all()
@pytest.mark.parametrize(
"index, dtype",
[
(pd.Int64Index, "float64"),
(pd.UInt64Index, "categorical"),
(pd.Float64Index, "datetime64"),
... |
class TestRangeIndex(Numeric):
result = RangeIndex(index)
tm.assert_index_equal(result, index, exact=True)
with pytest.raises(TypeError):
RangeIndex(index, dtype="float64")
def test_constructor_range(self): | class TestRangeIndex(Numeric):
result = RangeIndex(index)
tm.assert_index_equal(result, index, exact=True)
with pytest.raises(
ValueError,
match="Incorrect `dtype` passed: expected signed integer, received float64",
):
RangeIndex(index, dtype="float64... |
class TestRangeIndex(Numeric):
expected = RangeIndex(1, 5, 2)
tm.assert_index_equal(result, expected, exact=True)
with pytest.raises(TypeError):
Index(range(1, 5, 2), dtype="float64")
msg = r"^from_range\(\) got an unexpected keyword argument"
with pytest.raises(Type... | class TestRangeIndex(Numeric):
expected = RangeIndex(1, 5, 2)
tm.assert_index_equal(result, expected, exact=True)
with pytest.raises(
ValueError,
match="Incorrect `dtype` passed: expected signed integer, received float64",
):
Index(range(1, 5, 2), dty... |
class TestRangeIndex(Numeric):
RangeIndex(1.1, 10.2, 1.3)
# invalid passed type
with pytest.raises(TypeError):
RangeIndex(1, 5, dtype="float64")
@pytest.mark.parametrize( | class TestRangeIndex(Numeric):
RangeIndex(1.1, 10.2, 1.3)
# invalid passed type
with pytest.raises(
ValueError,
match="Incorrect `dtype` passed: expected signed integer, received float64",
):
RangeIndex(1, 5, dtype="float64")
@pytest.mark.par... |
def test_get():
1764.0,
1849.0,
1936.0,
],
dtype="object",
),
)
| def test_get():
1764.0,
1849.0,
1936.0,
]
),
)
|
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import cPickle
from PyQt5.Qt import (
Qt, QListWidget, QListWidgetItem, QItemSelectionModel, QAction, | __license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import json
from PyQt5.Qt import (
Qt, QListWidget, QListWidgetItem, QItemSelectionModel, QAction, |
def pos_key(b):
self.edited.emit(bm)
def bm_to_item(self, bm):
return bytearray(cPickle.dumps(bm, -1))
def item_to_bm(self, item):
return cPickle.loads(bytes(item.data(Qt.UserRole)))
def get_bookmarks(self):
return list(self) | def pos_key(b):
self.edited.emit(bm)
def bm_to_item(self, bm):
return bm.copy()
def item_to_bm(self, item):
return item.data(Qt.UserRole).copy()
def get_bookmarks(self):
return list(self) |
def get_bookmarks(self):
def export_bookmarks(self):
filename = choose_save_file(
self, 'export-viewer-bookmarks', _('Export bookmarks'),
filters=[(_('Saved bookmarks'), ['pickle'])], all_files=False, initial_filename='bookmarks.pickle')
if filename:
with open(fil... | def get_bookmarks(self):
def export_bookmarks(self):
filename = choose_save_file(
self, 'export-viewer-bookmarks', _('Export bookmarks'),
filters=[(_('Saved bookmarks'), ['calibre-bookmarks'])], all_files=False, initial_filename='bookmarks.calibre-bookmarks')
if filename:
... |
from calibre.srv.routes import endpoint, json
from calibre.srv.utils import get_library_data, get_use_roman
from calibre.utils.config import prefs, tweaks
from calibre.utils.icu import sort_key
from calibre.utils.localization import get_lang
from calibre.utils.search_query_parser import ParseException
| from calibre.srv.routes import endpoint, json
from calibre.srv.utils import get_library_data, get_use_roman
from calibre.utils.config import prefs, tweaks
from calibre.utils.icu import sort_key, numeric_sort_key
from calibre.utils.localization import get_lang
from calibre.utils.search_query_parser import ParseException... |
def field_names(ctx, rd, field):
Optional: ?library_id=<default library>
'''
db, library_id = get_library_data(ctx, rd)[:2]
return tuple(db.all_field_names(field)) | def field_names(ctx, rd, field):
Optional: ?library_id=<default library>
'''
db, library_id = get_library_data(ctx, rd)[:2]
return tuple(sorted(db.all_field_names(field), key=numeric_sort_key)) |
def _recast_datetimelike_result(result: DataFrame) -> DataFrame:
result = result.copy()
obj_cols = [
idx for idx in range(len(result.columns)) if is_object_dtype(result.dtypes[idx])
]
# See GH#26285 | def _recast_datetimelike_result(result: DataFrame) -> DataFrame:
result = result.copy()
obj_cols = [
idx
for idx in range(len(result.columns))
if is_object_dtype(result.dtypes.iloc[idx])
]
# See GH#26285 |
def test_apply_with_mixed_types():
result = g.apply(lambda x: x / x.sum())
tm.assert_frame_equal(result, expected) | def test_apply_with_mixed_types():
result = g.apply(lambda x: x / x.sum())
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"group_column_dtlike",
[datetime.today(), datetime.today().date(), datetime.today().time()],
)
def test_apply_datetime_issue(group_column_dtlike):
# GH-2824... |
'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 format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='',
# sign
sign = ''
if isinstance(number, Decimal):
str_number = '{:f}'.format(number)
else:
str_number = str(number)
if str_number[0] == '-': | def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='',
# sign
sign = ''
if isinstance(number, Decimal):
# Format values with more than 200 digits (an arbitrary cutoff) using
# scientific notation to avoid high memory usage in {:f}'.format().
_, digits, exponen... |
class TestNumberFormat(TestCase):
)
self.assertEqual(nformat(Decimal('3.'), '.'), '3')
self.assertEqual(nformat(Decimal('3.0'), '.'), '3.0')
def test_decimal_subclass(self):
class EuroDecimal(Decimal): | class TestNumberFormat(TestCase):
)
self.assertEqual(nformat(Decimal('3.'), '.'), '3')
self.assertEqual(nformat(Decimal('3.0'), '.'), '3.0')
# Very large & small numbers.
tests = [
('9e9999', None, '9e+9999'),
('9e9999', 3, '9.000e+9999'),
('9e... |
import os
import salt.payload
import salt.utils.files
import salt.utils.path
from salt.ext import six
log = logging.getLogger(__name__) | import os
import salt.payload
import salt.utils.files
import salt.utils.path
import salt.utils.verify
from salt.ext import six
log = logging.getLogger(__name__) |
def get_token(opts, tok):
:returns: Token data if successful. Empty dict if failed.
"""
t_path = os.path.join(opts["token_dir"], tok)
if not os.path.isfile(t_path):
return {}
serial = salt.payload.Serial(opts) | def get_token(opts, tok):
:returns: Token data if successful. Empty dict if failed.
"""
t_path = os.path.join(opts["token_dir"], tok)
if not salt.utils.verify.clean_path(opts["token_dir"], t_path):
return {}
if not os.path.isfile(t_path):
return {}
serial = salt.payload.Serial(op... |
from __future__ import absolute_import, print_function, unicode_literals
import errno
import logging
# Import python libs
import os
import re
import socket | from __future__ import absolute_import, print_function, unicode_literals
import errno
import logging
import os
import re
import socket |
import stat
import sys
import salt.defaults.exitcodes
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.user
from salt.exceptions import CommandExecutionError, SaltClientError, SaltSystemExit
# Import salt libs
from salt.log import is_console_configured
from salt.log.setup im... | import stat
import sys
import salt.defaults.exitcodes
import salt.ext.six
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.user
from salt.exceptions import CommandExecutionError, SaltClientError, SaltSystemExit
from salt.log import is_console_configured
from salt.log.setup im... |
def check_max_open_files(opts):
log.log(level=level, msg=msg)
def clean_path(root, path, subdir=False):
"""
Accepts the root the path needs to be under and verifies that the path is
under said root. Pass in subdir=True if the path can result in a
subdirectory of the root instead of having to resid... | def check_max_open_files(opts):
log.log(level=level, msg=msg)
def _realpath_darwin(path):
base = ""
for part in path.split(os.path.sep)[1:]:
if base != "":
if os.path.islink(os.path.sep.join([base, part])):
base = os.readlink(os.path.sep.join([base, part]))
... |
def update_config(file_name, yaml_contents):
__opts__["config_dir"], os.path.dirname(__opts__["default_include"])
)
try:
yaml_out = salt.utils.yaml.safe_dump(yaml_contents, default_flow_style=False)
if not os.path.exists(dir_path):
log.debug("Creating directory %s", dir_path... | def update_config(file_name, yaml_contents):
__opts__["config_dir"], os.path.dirname(__opts__["default_include"])
)
try:
yaml_out = salt.utils.yaml.safe_dump(yaml_contents, default_flow_style=False,)
if not os.path.exists(dir_path):
log.debug("Creating directory %s", dir_pat... |
def find(path, saltenv="base"):
return ret
for root in __opts__["file_roots"][saltenv]:
full = os.path.join(root, path)
if os.path.isfile(full):
# Add it to the dict
with salt.utils.files.fopen(full, "rb") as fp_: | def find(path, saltenv="base"):
return ret
for root in __opts__["file_roots"][saltenv]:
full = os.path.join(root, path)
if not salt.utils.verify.clean_path(root, full):
continue
if os.path.isfile(full):
# Add it to the dict
with salt.utils.files.fo... |
def write(data, path, saltenv="base", index=0):
return (
"The path passed in {0} is not relative to the environment " "{1}"
).format(path, saltenv)
dest = os.path.join(__opts__["file_roots"][saltenv][index], path)
dest_dir = os.path.dirname(dest)
if not os.path.isdir(dest_dir):
... | def write(data, path, saltenv="base", index=0):
return (
"The path passed in {0} is not relative to the environment " "{1}"
).format(path, saltenv)
root = __opts__["file_roots"][saltenv][index]
dest = os.path.join(root, path)
if not salt.utils.verify.clean_path(root, dest, subdir... |
class ClearFuncsPubTestCase(TestCase):
ret_evt = raw
break
assert not os.path.exists(self.tmpfile), "Evil file created" | class ClearFuncsPubTestCase(TestCase):
ret_evt = raw
break
assert not os.path.exists(self.tmpfile), "Evil file created"
class ClearFuncsConfigTest(TestCase):
def setUp(self):
master_opts = AdaptedConfigurationTestCaseMixin.get_config("master")
self.conf_dir ... |
class BadTestModuleNamesTestCase(TestCase):
"integration.logging.test_jid_logging",
"integration.logging.handlers.test_logstash_mod",
"integration.master.test_event_return",
"integration.minion.test_blackout",
"integration.minion.test_executor",
"i... | class BadTestModuleNamesTestCase(TestCase):
"integration.logging.test_jid_logging",
"integration.logging.handlers.test_logstash_mod",
"integration.master.test_event_return",
"integration.master.test_clear_funcs",
"integration.minion.test_blackout",
... |
class BadTestModuleNamesTestCase(TestCase):
"integration.reactor.test_reactor",
"integration.returners.test_noop_return",
"integration.runners.test_runner_returns",
"unit.utils.scheduler.test_error",
"unit.utils.scheduler.test_eval",
"unit.utils.sc... | class BadTestModuleNamesTestCase(TestCase):
"integration.reactor.test_reactor",
"integration.returners.test_noop_return",
"integration.runners.test_runner_returns",
"integration.scheduler.test_error",
"integration.scheduler.test_eval",
"integration... |
class BadTestModuleNamesTestCase(TestCase):
"integration.ssh.test_raw",
"integration.ssh.test_saltcheck",
"integration.ssh.test_state",
"integration.ssh.test_pre_flight",
"integration.states.test_compiler",
"integration.states.test_handle_error",
... | class BadTestModuleNamesTestCase(TestCase):
"integration.ssh.test_raw",
"integration.ssh.test_saltcheck",
"integration.ssh.test_state",
"integration.states.test_compiler",
"integration.states.test_handle_error",
"integration.states.test_handle_iord... |
Test the verification routines
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import getpass
import os
import shutil | Test the verification routines
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import ctypes
import getpass
import os
import shutil |
from salt.ext.six.moves import range # pylint: disable=import-error,redefined-b
from salt.utils.verify import (
check_max_open_files,
check_user,
log,
valid_id,
verify_env, | from salt.ext.six.moves import range # pylint: disable=import-error,redefined-b
from salt.utils.verify import (
check_max_open_files,
check_user,
clean_path,
log,
valid_id,
verify_env, |
from salt.utils.verify import (
from tests.support.helpers import TstSuiteLoggingHandler, requires_network
from tests.support.mock import MagicMock, patch
# Import Salt Testing libs
from tests.support.runtests import RUNTIME_VARS
from tests.support.unit import TestCase, skipIf | from salt.utils.verify import (
from tests.support.helpers import TstSuiteLoggingHandler, requires_network
from tests.support.mock import MagicMock, patch
# Import Salt Testing libs
# Import Salt Testing libs
from tests.support.runtests import RUNTIME_VARS
from tests.support.unit import TestCase, skipIf |
else:
import resource
class TestVerify(TestCase):
"""
Verify module tests | else:
import resource
# Import third party libs
if sys.platform.startswith("win"):
import win32file
else:
import resource
class TestVerify(TestCase):
"""
Verify module tests |
class TestVerifyLog(TestCase):
self.assertFalse(os.path.exists(path))
verify_log_files([path], getpass.getuser())
self.assertTrue(os.path.exists(path)) | class TestVerifyLog(TestCase):
self.assertFalse(os.path.exists(path))
verify_log_files([path], getpass.getuser())
self.assertTrue(os.path.exists(path))
class TestCleanPath(TestCase):
"""
salt.utils.clean_path works as expected
"""
def setUp(self):
self.tmpdir = tempfil... |
def test_getproxies_environment_keep_no_proxies(self):
self.assertTrue(urllib.proxy_bypass_environment('anotherdomain.com:8888'))
self.assertTrue(urllib.proxy_bypass_environment('newdomain.com:1234'))
def test_proxy_bypass_environment_host_match(self):
bypass = urllib.proxy_bypass_environme... | def test_getproxies_environment_keep_no_proxies(self):
self.assertTrue(urllib.proxy_bypass_environment('anotherdomain.com:8888'))
self.assertTrue(urllib.proxy_bypass_environment('newdomain.com:1234'))
def test_proxy_cgi_ignore(self):
try:
self.env.set('HTTP_PROXY', 'http://somew... |
def getproxies_environment():
If you need a different way, you can pass a proxies dictionary to the
[Fancy]URLopener constructor.
"""
proxies = {}
for name, value in os.environ.items():
name = name.lower()
if value and name[-6:] == '_proxy':
proxies[name[:-6]] = value
... | def getproxies_environment():
If you need a different way, you can pass a proxies dictionary to the
[Fancy]URLopener constructor.
"""
# Get all variables
proxies = {}
for name, value in os.environ.items():
name = name.lower()
if value and name[-6:] == '_proxy':
proxie... |
class Axis(martist.Artist):
the top for the y-axis; the "inverse" direction is increasing to the
left for the x-axis and to the bottom for the y-axis.
"""
a, b = self.get_view_interval()
if inverted:
self.set_view_interval(max(a, b), min(a, b), ignore=True)
el... | class Axis(martist.Artist):
the top for the y-axis; the "inverse" direction is increasing to the
left for the x-axis and to the bottom for the y-axis.
"""
# Currently, must be implemented in subclasses using set_xlim/set_ylim
# rather than generically using set_view_interval, so ... |
class XAxis(Axis):
def get_minpos(self):
return self.axes.dataLim.minposx
def set_default_intervals(self):
# docstring inherited
xmin, xmax = 0., 1. | class XAxis(Axis):
def get_minpos(self):
return self.axes.dataLim.minposx
def set_inverted(self, inverted):
# docstring inherited
a, b = self.get_view_interval()
self.axes.set_xlim(sorted((a, b), reverse=inverted), auto=None)
def set_default_intervals(self):
# docst... |
class YAxis(Axis):
def get_minpos(self):
return self.axes.dataLim.minposy
def set_default_intervals(self):
# docstring inherited
ymin, ymax = 0., 1. | class YAxis(Axis):
def get_minpos(self):
return self.axes.dataLim.minposy
def set_inverted(self, inverted):
# docstring inherited
a, b = self.get_view_interval()
self.axes.set_ylim(sorted((a, b), reverse=inverted), auto=None)
def set_default_intervals(self):
# docst... |
def test_inverted_cla():
ax.cla()
ax.imshow(img)
plt.autoscale()
assert not(ax.xaxis_inverted())
assert ax.yaxis_inverted()
# 5. two shared axes. Clearing the master axis should bring axes in shared
# axes back to normal
ax0 = plt.subplot(211)
ax1 = plt.subplot(212, sharey=ax0)
... | def test_inverted_cla():
ax.cla()
ax.imshow(img)
plt.autoscale()
assert not ax.xaxis_inverted()
assert ax.yaxis_inverted()
# 5. two shared axes. Inverting the master axis should invert the shared
# axes; clearing the master axis should bring axes in shared
# axes back to normal.
ax0... |
from django.utils.six.moves.urllib.parse import (
urlparse,
)
ETAG_MATCH = re.compile(r'(?:W/)?"((?:\\.|[^"])*)"')
MONTHS = 'jan feb mar apr may jun jul aug sep oct nov dec'.split() | from django.utils.six.moves.urllib.parse import (
urlparse,
)
if six.PY2:
from urlparse import (
ParseResult, SplitResult, _splitnetloc, _splitparams, scheme_chars,
uses_params,
)
_coerce_args = None
else:
from urllib.parse import (
ParseResult, SplitResult, _coerce_args, _s... |
def is_safe_url(url, host=None):
return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host)
def _is_safe_url(url, host):
# 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 unsafe.
if url.starts... | def is_safe_url(url, host=None):
return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host)
# Copied from urllib.parse.urlparse() but uses fixed urlsplit() function.
def _urlparse(url, scheme='', allow_fragments=True):
"""Parse a URL into 6 components:
<scheme>://<netloc>/<path>;<params... |
class TestUtilsHttp(unittest.TestCase):
r'http://testserver\me:pass@example.com',
r'http://testserver\@example.com',
r'http:\\testserver\confirm\me@example.com',
'\n'):
self.assertFalse(http.is_safe_url(bad_url, ... | class TestUtilsHttp(unittest.TestCase):
r'http://testserver\me:pass@example.com',
r'http://testserver\@example.com',
r'http:\\testserver\confirm\me@example.com',
'http:999999999',
'ftp:9999999999',
... |
class TestUtilsHttp(unittest.TestCase):
'HTTPS://testserver/',
'//testserver/',
'http://testserver/confirm?email=me@example.com',
'/url%20with%20spaces/'):
self.assertTrue(http.is_safe_url(good_url, host='testserver'), "%s s... | class TestUtilsHttp(unittest.TestCase):
'HTTPS://testserver/',
'//testserver/',
'http://testserver/confirm?email=me@example.com',
'/url%20with%20spaces/',
'path/http:2222222222'):
self.assertTrue(http.is... |
def _get_spider_loader(settings):
'Please use SPIDER_LOADER_CLASS.',
category=ScrapyDeprecationWarning, stacklevel=2
)
cls_path = settings.get('SPIDER_LOADER_CLASS',
settings.get('SPIDER_MANAGER_CLASS'))
loader_cls = load_object(cls_path)
verifyCla... | def _get_spider_loader(settings):
'Please use SPIDER_LOADER_CLASS.',
category=ScrapyDeprecationWarning, stacklevel=2
)
cls_path = settings.get('SPIDER_MANAGER_CLASS',
settings.get('SPIDER_LOADER_CLASS'))
loader_cls = load_object(cls_path)
verifyCla... |
from zope.interface.verify import DoesNotImplement
from scrapy.crawler import Crawler, CrawlerRunner
from scrapy.settings import Settings, default_settings
from scrapy.utils.spider import DefaultSpider
from scrapy.utils.misc import load_object
| from zope.interface.verify import DoesNotImplement
from scrapy.crawler import Crawler, CrawlerRunner
from scrapy.settings import Settings, default_settings
from scrapy.spiderloader import SpiderLoader
from scrapy.utils.spider import DefaultSpider
from scrapy.utils.misc import load_object
|
class SpiderLoaderWithWrongInterface(object):
pass
class CrawlerRunnerTestCase(unittest.TestCase):
def test_spider_manager_verify_interface(self): | class SpiderLoaderWithWrongInterface(object):
pass
class CustomSpiderLoader(SpiderLoader):
pass
class CrawlerRunnerTestCase(unittest.TestCase):
def test_spider_manager_verify_interface(self): |
class CrawlerRunnerTestCase(unittest.TestCase):
self.assertIn("CrawlerRunner.spider_loader", str(w[0].message))
sl_cls = load_object(runner.settings['SPIDER_LOADER_CLASS'])
self.assertIsInstance(spiders, sl_cls) | class CrawlerRunnerTestCase(unittest.TestCase):
self.assertIn("CrawlerRunner.spider_loader", str(w[0].message))
sl_cls = load_object(runner.settings['SPIDER_LOADER_CLASS'])
self.assertIsInstance(spiders, sl_cls)
def test_spidermanager_deprecation(self):
with warnings.cat... |
options:
name:
description:
- Zone name.
type: str
required: true
path: | options:
name:
description:
- Zone name.
- A zone name must be unique name.
- A zone name must begin with an alpha-numeric character.
- The name can contain alpha-numeric characters, underbars I(_), hyphens I(-), and periods I(.).
- The name cannot be longer than 64 characters.
t... |
EXAMPLES = '''
import os
import platform
import tempfile
import time
| EXAMPLES = '''
import os
import platform
import re
import tempfile
import time
|
class Zone(object):
if int(self.os_minor) < 10:
self.module.fail_json(msg='This module requires Solaris 10 or later')
def configure(self):
if not self.path:
self.module.fail_json(msg='Missing required argument: path') | class Zone(object):
if int(self.os_minor) < 10:
self.module.fail_json(msg='This module requires Solaris 10 or later')
match = re.match('^[a-zA-Z0-9][-_.a-zA-Z0-9]{0,62}$', self.name)
if not match:
self.module.fail_json(msg="Provided zone name is not a valid zone name. "
... |
def url_has_any_extension(url, extensions):
def _safe_ParseResult(parts, encoding='utf8', path_encoding='utf8'):
return (
to_native_str(parts.scheme),
to_native_str(parts.netloc.encode('idna')),
# default encoding for path component SHOULD be UTF-8
quote(to_bytes(parts.path, path_... | def url_has_any_extension(url, extensions):
def _safe_ParseResult(parts, encoding='utf8', path_encoding='utf8'):
# IDNA encoding can fail for too long labels (>63 characters)
# or missing labels (e.g. http://.example.com)
try:
netloc = parts.netloc.encode('idna')
except UnicodeError:
n... |
class CanonicalizeUrlTest(unittest.TestCase):
# without encoding, already canonicalized URL is canonicalized identically
self.assertEqual(canonicalize_url(canonicalized), canonicalized)
class AddHttpIfNoScheme(unittest.TestCase):
| class CanonicalizeUrlTest(unittest.TestCase):
# without encoding, already canonicalized URL is canonicalized identically
self.assertEqual(canonicalize_url(canonicalized), canonicalized)
def test_canonicalize_url_idna_exceptions(self):
# missing DNS label
self.assertEqual(
... |
# -*- coding: utf-8 -*-
# The pam components have been modified to be salty and have been taken from
# the pam module under this licence:
# (c) 2007 Chris AtLee <chris@atlee.ca> | # The pam components have been modified to be salty and have been taken from
# the pam module under this licence:
# (c) 2007 Chris AtLee <chris@atlee.ca> |
authenticated against. This defaults to `login`
"""
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
from ctypes import ( | authenticated against. This defaults to `login`
"""
import logging
from ctypes import ( |
from ctypes import (
)
from ctypes.util import find_library
# Import Salt libs
import salt.utils.user
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin
log = logging.getLogger(__name__)
try: | from ctypes import (
)
from ctypes.util import find_library
import salt.utils.user
log = logging.getLogger(__name__)
try: |
class PamMessage(Structure):
]
def __repr__(self):
return "<PamMessage {0} '{1}'>".format(self.msg_style, self.msg)
class PamResponse(Structure): | class PamMessage(Structure):
]
def __repr__(self):
return "<PamMessage {} '{}'>".format(self.msg_style, self.msg)
class PamResponse(Structure): |
class PamResponse(Structure):
]
def __repr__(self):
return "<PamResponse {0} '{1}'>".format(self.resp_retcode, self.resp)
CONV_FUNC = CFUNCTYPE( | class PamResponse(Structure):
]
def __repr__(self):
return "<PamResponse {} '{}'>".format(self.resp_retcode, self.resp)
CONV_FUNC = CFUNCTYPE( |
def authenticate(username, password):
"""
service = __opts__.get("auth.pam.service", "login")
if isinstance(username, six.text_type):
username = username.encode(__salt_system_encoding__)
if isinstance(password, six.text_type):
password = password.encode(__salt_system_encoding__)
if ... | def authenticate(username, password):
"""
service = __opts__.get("auth.pam.service", "login")
if isinstance(username, str):
username = username.encode(__salt_system_encoding__)
if isinstance(password, str):
password = password.encode(__salt_system_encoding__)
if isinstance(service, ... |
def authenticate(username, password):
retval = PAM_AUTHENTICATE(handle, 0)
if retval == 0:
PAM_ACCT_MGMT(handle, 0)
PAM_END(handle, 0)
return retval == 0
| def authenticate(username, password):
retval = PAM_AUTHENTICATE(handle, 0)
if retval == 0:
retval = PAM_ACCT_MGMT(handle, 0)
PAM_END(handle, 0)
return retval == 0
|
import salt.utils.json
import salt.utils.stringutils
import salt.utils.url
import salt.utils.yaml
from jinja2 import BaseLoader, Markup, TemplateNotFound, nodes
from jinja2.environment import TemplateModule
from jinja2.exceptions import TemplateRuntimeError
from jinja2.ext import Extension | import salt.utils.json
import salt.utils.stringutils
import salt.utils.url
import salt.utils.yaml
from jinja2 import BaseLoader, TemplateNotFound, nodes
from jinja2.environment import TemplateModule
from jinja2.exceptions import TemplateRuntimeError
from jinja2.ext import Extension |
from salt.utils.decorators.jinja import jinja_filter, jinja_global, jinja_test
from salt.utils.odict import OrderedDict
from salt.utils.versions import LooseVersion
log = logging.getLogger(__name__)
__all__ = ["SaltCacheLoader", "SerializerExtension"] | from salt.utils.decorators.jinja import jinja_filter, jinja_global, jinja_test
from salt.utils.odict import OrderedDict
from salt.utils.versions import LooseVersion
try:
from markupsafe import Markup
except ImportError:
# jinja < 3.1
from jinja2 import Markup
log = logging.getLogger(__name__)
__all__ = [... |
def method_call(obj, f_name, *f_args, **f_kwargs):
return getattr(obj, f_name, lambda *args, **kwargs: None)(*f_args, **f_kwargs)
@jinja2.contextfunction
def show_full_context(ctx):
return salt.utils.data.simple_types_filter(
{key: value for key, value in ctx.items()} | def method_call(obj, f_name, *f_args, **f_kwargs):
return getattr(obj, f_name, lambda *args, **kwargs: None)(*f_args, **f_kwargs)
try:
contextfunction = jinja2.contextfunction
except AttributeError:
contextfunction = jinja2.pass_context
@contextfunction
def show_full_context(ctx):
return salt.utils.... |
class Series(base.IndexOpsMixin, generic.NDFrame):
else:
return self.iloc[key]
if isinstance(key, list):
# handle the dup indexing case GH#4246
return self.loc[key]
return self.reindex(key)
def _get_values_tuple(self, key):
# mpl hackaro... | class Series(base.IndexOpsMixin, generic.NDFrame):
else:
return self.iloc[key]
# handle the dup indexing case GH#4246
return self.loc[key]
def _get_values_tuple(self, key):
# mpl hackaround |
def test_getitem_boolean_empty():
# GH5877
# indexing with empty series
s = Series(["A", "B"])
expected = Series(np.nan, index=["C"], dtype=object)
result = s[Series(["C"], dtype=object)]
tm.assert_series_equal(result, expected)
s = Series(["A", "B"])
expected = Series(dtype=object, in... | def test_getitem_boolean_empty():
# GH5877
# indexing with empty series
s = Series(["A", "B"])
expected = Series(dtype=object, index=Index([], dtype="int64"))
result = s[Series([], dtype=object)] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.