buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class BaseFeatureInitiatingInitializer(object): @cvar feature: tuple of (uri, name) of the stream feature root element. @type feature: tuple of (C{str}, C{str}) @ivar required: whether the stream feature is required to be advertized by the receiving entity. @type required: C{bool} ...
class BaseFeatureInitiatingInitializer(object): @cvar feature: tuple of (uri, name) of the stream feature root element. @type feature: tuple of (C{str}, C{str}) @ivar required: whether the stream feature is required to be advertized by the receiving entity. @type required: C{bool} ...
class TLSInitiatingInitializer(BaseFeatureInitiatingInitializer): set the C{wanted} attribute to False instead of removing it from the list of initializers, so a proper exception L{TLSRequired} can be raised. @cvar wanted: indicates if TLS negotiation is wanted. @type wanted: C{bool} """ featu...
class TLSInitiatingInitializer(BaseFeatureInitiatingInitializer): set the C{wanted} attribute to False instead of removing it from the list of initializers, so a proper exception L{TLSRequired} can be raised. @ivar wanted: indicates if TLS negotiation is wanted. @type wanted: C{bool} """ featu...
class TLSInitiatingInitializer(BaseFeatureInitiatingInitializer): """ self.xmlstream.removeObserver('/failure', self.onFailure) ctx = ssl.CertificateOptions() self.xmlstream.transport.startTLS(ctx) self.xmlstream.reset() self.xmlstream.sendHeader()
class TLSInitiatingInitializer(BaseFeatureInitiatingInitializer): """ self.xmlstream.removeObserver('/failure', self.onFailure) if self._configurationForTLS: ctx = self._configurationForTLS else: ctx = ssl.optionsForClientTLS(self.xmlstream.otherEntity.host) ...
from twisted.words.protocols.jabber import client, error, jid, xmlstream from twisted.words.protocols.jabber.sasl import SASLInitiatingInitializer from twisted.words.xish import utility IQ_AUTH_GET = '/iq[@type="get"]/query[@xmlns="jabber:iq:auth"]' IQ_AUTH_SET = '/iq[@type="set"]/query[@xmlns="jabber:iq:auth"]' NS_BI...
from twisted.words.protocols.jabber import client, error, jid, xmlstream from twisted.words.protocols.jabber.sasl import SASLInitiatingInitializer from twisted.words.xish import utility try: from twisted.internet import ssl except ImportError: ssl = None skipWhenNoSSL = "SSL not available" else: skipWh...
class SessionInitializerTests(InitiatingInitializerHarness, unittest.TestCase): class XMPPAuthenticatorTests(unittest.TestCase): """ Test for both XMPPAuthenticator and XMPPClientFactory. """ def testBasic(self): """ Test basic operations.
class SessionInitializerTests(InitiatingInitializerHarness, unittest.TestCase): class BasicAuthenticatorTests(unittest.TestCase): """ Test for both BasicAuthenticator and basicClientFactory. """ def test_basic(self): """ Authenticator and stream are properly constructed by the factor...
class XMPPAuthenticatorTests(unittest.TestCase): self.assertIsInstance(bind, client.BindInitializer) self.assertIsInstance(session, client.SessionInitializer) self.assertFalse(tls.required) self.assertTrue(sasl.required) self.assertFalse(bind.required) self.assertFalse(s...
class XMPPAuthenticatorTests(unittest.TestCase): self.assertIsInstance(bind, client.BindInitializer) self.assertIsInstance(session, client.SessionInitializer) self.assertTrue(tls.required) self.assertTrue(sasl.required) self.assertTrue(bind.required) self.assertFalse(ses...
from twisted.words.test.test_xmlstream import GenericXmlStreamFactoryTestsMixin from twisted.words.xish import domish from twisted.words.protocols.jabber import error, ijabber, jid, xmlstream NS_XMPP_TLS = 'urn:ietf:params:xml:ns:xmpp-tls'
from twisted.words.test.test_xmlstream import GenericXmlStreamFactoryTestsMixin from twisted.words.xish import domish from twisted.words.protocols.jabber import error, ijabber, jid, xmlstream try: from twisted.internet import ssl except ImportError: ssl = None skipWhenNoSSL = "SSL not available" else: ...
class TLSInitiatingInitializerTests(unittest.TestCase): self.savedSSL = xmlstream.ssl self.authenticator = xmlstream.Authenticator() self.xmlstream = xmlstream.XmlStream(self.authenticator) self.xmlstream.send = self.output.append self.xmlstream.connectionMade()
class TLSInitiatingInitializerTests(unittest.TestCase): self.savedSSL = xmlstream.ssl self.authenticator = xmlstream.ConnectAuthenticator(u'example.com') self.xmlstream = xmlstream.XmlStream(self.authenticator) self.xmlstream.send = self.output.append self.xmlstream.connectionM...
class TLSInitiatingInitializerTests(unittest.TestCase): xmlstream.ssl = self.savedSSL def testWantedSupported(self): """ Test start when TLS is wanted and the SSL library available. """ self.xmlstream.transport = proto_helpers.StringTransport() self.xmlstream.transp...
class TLSInitiatingInitializerTests(unittest.TestCase): xmlstream.ssl = self.savedSSL def test_initRequired(self): """ Passing required sets the instance variable. """ self.init = xmlstream.TLSInitiatingInitializer(self.xmlstream, ...
class TLSInitiatingInitializerTests(unittest.TestCase): d = self.init.start() d.addCallback(self.assertEqual, xmlstream.Reset) starttls = self.output[0] self.assertEqual('starttls', starttls.name) self.assertEqual(NS_XMPP_TLS, starttls.uri) self.xmlstream.dataReceived("<...
class TLSInitiatingInitializerTests(unittest.TestCase): d = self.init.start() d.addCallback(self.assertEqual, xmlstream.Reset) self.assertEqual(2, len(self.output)) starttls = self.output[1] self.assertEqual('starttls', starttls.name) self.assertEqual(NS_XMPP_TLS, startt...
class TLSInitiatingInitializerTests(unittest.TestCase): return d if not xmlstream.ssl: testWantedSupported.skip = "SSL not available" def testWantedNotSupportedNotRequired(self): """ Test start when TLS is wanted and the SSL library available. """ xmlstream.ss...
class TLSInitiatingInitializerTests(unittest.TestCase): return d test_wantedSupported.skip = skipWhenNoSSL def test_certificateVerify(self): """ The server certificate will be verified. """ def fakeStartTLS(contextFactory): self.assertIsInstance(contextFa...
class TLSInitiatingInitializerTests(unittest.TestCase): self.init.wanted = False d = self.init.start() self.assertEqual([], self.output) self.assertFailure(d, xmlstream.TLSRequired) return d def testNotWantedNotRequired(self): """ Test start when TLS is no...
class TLSInitiatingInitializerTests(unittest.TestCase): self.init.wanted = False d = self.init.start() self.assertEqual(1, len(self.output)) self.assertFailure(d, xmlstream.TLSRequired) return d def test_notWantedNotRequired(self): """ No StartTLS is initi...
class TestFish(object): assert not shell.how_to_configure().can_configure_automatically def test_info(self, shell, Popen): Popen.return_value.stdout.read.side_effect = [b'3.5.9'] assert shell.info() == 'Fish Shell 3.5.9'
class TestFish(object): assert not shell.how_to_configure().can_configure_automatically def test_info(self, shell, Popen): Popen.return_value.stdout.read.side_effect = [b'fish, version 3.5.9\n'] assert shell.info() == 'Fish Shell 3.5.9' assert Popen.call_args[0][0] == ['fish', '--ve...
class Fish(Generic): def info(self): """Returns the name and version of the current shell""" proc = Popen(['fish', '-c', 'echo $FISH_VERSION'], stdout=PIPE, stderr=DEVNULL) version = proc.stdout.read().decode('utf-8').strip() return u'Fish Shell {}'.format(versi...
class Fish(Generic): def info(self): """Returns the name and version of the current shell""" proc = Popen(['fish', '--version'], stdout=PIPE, stderr=DEVNULL) version = proc.stdout.read().decode('utf-8').split()[-1] return u'Fish Shell {}'.format(version) de...
def test_osx_proxy_bypass(self): bypass = {'exclude_simple': True, 'exceptions': []} self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass)) def test_basic_auth(self, quote_char='"'): opener = OpenerDirector() password_manager = MockPasswordManager() auth_handler = url...
def test_osx_proxy_bypass(self): bypass = {'exclude_simple': True, 'exceptions': []} self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass)) def check_basic_auth(self, headers, realm): with self.subTest(realm=realm, headers=headers): opener = OpenerDirector() p...
class AbstractBasicAuthHandler: # allow for double- and single-quoted realm values # (single quotes are a violation of the RFC, but appear in the wild) rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+' 'realm=(["\']?)([^"\']*)\\2', re.I) # XXX could pre-emptively send auth info alrea...
class AbstractBasicAuthHandler: # allow for double- and single-quoted realm values # (single quotes are a violation of the RFC, but appear in the wild) rx = re.compile('(?:^|,)' # start of the string or ',' '[ \t]*' # optional whitespaces '([^ \t]+)' # scheme li...
def __init__(self, password_mgr=None): self.passwd = password_mgr self.add_password = self.passwd.add_password def http_error_auth_reqed(self, authreq, host, req, headers): # host may be an authority (without userinfo) or a URL with an # authority # XXX could be multiple hea...
def __init__(self, password_mgr=None): self.passwd = password_mgr self.add_password = self.passwd.add_password def _parse_realm(self, header): # parse WWW-Authenticate header: accept multiple challenges per header found_challenge = False for mo in AbstractBasicAuthHandler.rx...
class Serializer(object): """ A swappable class for serialization. This handles most types of data as well as the following output formats:: * json * jsonp * xml * yaml * html * plist (see http://explorapp.com/biplist/) It was designed to ma...
class Serializer(object): """ A swappable class for serialization. This handles most types of data as well as the following output formats:: * json * jsonp * xml * yaml * html * plist (see http://explorapp.com/biplist/) It was designed to make changing ...
class Serializer(object): 'html': 'text/html', 'plist': 'application/x-plist', } def __init__(self, formats=None, content_types=None, datetime_formatting=None): self.supported_formats = [] self.datetime_formatting = getattr(settings, 'TASTYPIE_DATETIME_FORMATTING', 'iso-8601...
class Serializer(object): 'html': 'text/html', 'plist': 'application/x-plist', } def __init__(self, formats=None, content_types=None, datetime_formatting=None): self.supported_formats = [] self.datetime_formatting = getattr(settings, 'TASTYPIE_DATETIME_FORMATTING', 'iso-8601') ...
def get_mime_for_format(self, format): return self.content_types[format] except KeyError: return 'application/json' def format_datetime(self, data): """ A hook to control how datetimes are formatted. Can be overridden at the ``Serializer`` level ...
def get_mime_for_format(self, format): return self.content_types[format] except KeyError: return 'application/json' def format_datetime(self, data): """ A hook to control how datetimes are formatted. Can be overridden at the ``Serializer`` level (``datetime_...
def deserialize(self, content, format='application/json'): if hasattr(self, "from_%s" % short_format): desired_format = short_format break if desired_format is None: raise UnsupportedFormat("The format indicated '%s' had no available d...
def deserialize(self, content, format='application/json'): if hasattr(self, "from_%s" % short_format): desired_format = short_format break if desired_format is None: raise UnsupportedFormat("The format indicated '%s' had no available deseriali...
def to_simple(self, data, options): """ For a piece of data, attempts to recognize it and provide a simplified form of something complex. This brings complex Python data structures down to native types of the serialization format(s). """
def to_simple(self, data, options): """ For a piece of data, attempts to recognize it and provide a simplified form of something complex. This brings complex Python data structures down to native types of the serialization format(s). """
def from_etree(self, data): return False else: return None def to_json(self, data, options=None): """ Given some Python data, produces JSON output.
def from_etree(self, data): return False else: return None def to_json(self, data, options=None): """ Given some Python data, produces JSON output.
def to_xml(self, data, options=None): Given some Python data, produces XML output. """ options = options or {} if lxml is None: raise ImproperlyConfigured("Usage of the XML aspects requires lxml.") return tostring(self.to_etree(data, options), xml_de...
def to_xml(self, data, options=None): Given some Python data, produces XML output. """ options = options or {} if lxml is None: raise ImproperlyConfigured("Usage of the XML aspects requires lxml.") return tostring(self.to_etree(data, options), xml_declaration=True, ...
def get_type_string(data): Translates a Python data type into a string format. """ data_type = type(data) if data_type in (int, long): return 'integer' elif data_type == float:
def get_type_string(data): Translates a Python data type into a string format. """ data_type = type(data) if data_type in (int, long): return 'integer' elif data_type == float:
from ellipticcurve.utils.compatibility import * from ellipticcurve.privateKey import PrivateKey from ellipticcurve.publicKey import PublicKey from ellipticcurve.signature import Signature from ellipticcurve.utils.file import File from ellipticcurve.ecdsa import Ecdsa
from .utils.compatibility import * from .privateKey import PrivateKey from .publicKey import PublicKey from .signature import Signature from .utils.file import File from .ecdsa import Ecdsa
def verify(cls, message, signature, publicKey, hashfunc=sha256): curve = publicKey.curve r = signature.r s = signature.s inv = Math.inv(s, curve.N) u1 = Math.multiply(curve.G, n=(numberMessage * inv) % curve.N, N=curve.N, A=curve.A, P=curve.P) u2 = Math.multiply(publicKey...
def verify(cls, message, signature, publicKey, hashfunc=sha256): curve = publicKey.curve r = signature.r s = signature.s if not 1 <= r <= curve.N - 1: return False if not 1 <= s <= curve.N - 1: return False inv = Math.inv(s, curve.N) u1 = M...
def delete(self, req, id): raise HTTPForbidden(explanation=msg, request=req, content_type="text/plain") status = 'deleted' try: # The image's location field may be None in the case # of a saving or queued image, therefore don't ask a b...
def delete(self, req, id): raise HTTPForbidden(explanation=msg, request=req, content_type="text/plain") if image['location'] and CONF.delayed_delete: status = 'pending_delete' else: status = 'deleted' try: # Delete...
def request(self, method, url, body=None, headers=None): def getresponse(self): mapper = routes.Mapper() api = context.UnauthenticatedContextMiddleware(rserver.API(mapper)) webob_res = self.req.get_response(api) return utils.FakeHTTPResponse(status=webob_res.status_int,
def request(self, method, url, body=None, headers=None): def getresponse(self): mapper = routes.Mapper() server = rserver.API(mapper) # NOTE(markwash): we need to pass through context auth information if # we have it. if 'X-Auth-Token' in self.req.headers: api = ...
def test_delete_non_exists_image(self): res = req.get_response(self.api) self.assertEquals(res.status_int, webob.exc.HTTPNotFound.code) def test_delete_queued_image(self): """Delete an image in a queued state
def test_delete_non_exists_image(self): res = req.get_response(self.api) self.assertEquals(res.status_int, webob.exc.HTTPNotFound.code) def test_delete_not_allowed(self): # Verify we can get the image data req = webob.Request.blank("/images/%s" % UUID2) req.method = 'GET' ...
def process_request(self, req): 'tenant': tenant, 'roles': roles, 'is_admin': self.is_admin, } req.context = context.RequestContext(**kwargs)
def process_request(self, req): 'tenant': tenant, 'roles': roles, 'is_admin': self.is_admin, 'auth_tok': auth_tok, } req.context = context.RequestContext(**kwargs)
class DatabaseFeatures(BaseDatabaseFeatures): only_supports_unbounded_with_preceding_and_following = True supports_aggregate_filter_clause = True supported_explain_formats = {'JSON', 'TEXT', 'XML', 'YAML'} validates_explain_options = False # A query will error on invalid options. supports_deferrabl...
class DatabaseFeatures(BaseDatabaseFeatures): only_supports_unbounded_with_preceding_and_following = True supports_aggregate_filter_clause = True supported_explain_formats = {'JSON', 'TEXT', 'XML', 'YAML'} supports_deferrable_unique_constraints = True has_json_operators = True json_key_contains_...
from django.db.backends.base.operations import BaseDatabaseOperations class DatabaseOperations(BaseDatabaseOperations): cast_char_field_without_max_length = 'varchar' explain_prefix = 'EXPLAIN' cast_data_types = { 'AutoField': 'integer', 'BigAutoField': 'bigint',
from django.db.backends.base.operations import BaseDatabaseOperations class DatabaseOperations(BaseDatabaseOperations): cast_char_field_without_max_length = 'varchar' explain_prefix = 'EXPLAIN' explain_options = frozenset( [ "ANALYZE", "BUFFERS", "COSTS", ...
class DatabaseOperations(BaseDatabaseOperations): return super().subtract_temporals(internal_type, lhs, rhs) def explain_query_prefix(self, format=None, **options): prefix = super().explain_query_prefix(format) extra = {} if format: extra['FORMAT'] = format if op...
class DatabaseOperations(BaseDatabaseOperations): return super().subtract_temporals(internal_type, lhs, rhs) def explain_query_prefix(self, format=None, **options): extra = {} # Normalize options. if options: options = { name.upper(): "true" if value else...
__all__ = ['Query', 'RawQuery'] # SQL comments are forbidden in column aliases. FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(r"['`\"\]\[;\s]|--|/\*|\*/") def get_field_names_from_opts(opts): return set(chain.from_iterable(
__all__ = ['Query', 'RawQuery'] # SQL comments are forbidden in column aliases. FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(r"['`\"\]\[;\s]|--|/\*|\*/") # Inspired from # https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS EXPLAIN_OPTIONS_PATTERN = _lazy_re_compile(r"[\w\-]+") def g...
class Query(BaseExpression): def explain(self, using, format=None, **options): q = self.clone() q.explain_query = True q.explain_format = format q.explain_options = options
class Query(BaseExpression): def explain(self, using, format=None, **options): q = self.clone() for option_name in options: if ( not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name) or "--" in option_name ): raise ValueError(f"In...
class ExplainTests(TestCase): @skipUnlessDBFeature('validates_explain_options') def test_unknown_options(self): with self.assertRaisesMessage(ValueError, 'Unknown options: test, test2'): Tag.objects.all().explain(test=1, test2=1) def test_unknown_format(self): msg = 'DOES NOT E...
class ExplainTests(TestCase): @skipUnlessDBFeature('validates_explain_options') def test_unknown_options(self): with self.assertRaisesMessage(ValueError, "Unknown options: TEST, TEST2"): Tag.objects.all().explain(**{"TEST": 1, "TEST2": 1}) def test_unknown_format(self): msg = '...
class ExplainTests(TestCase): option = '{} {}'.format(name.upper(), 'true' if value else 'false') self.assertIn(option, captured_queries[0]['sql']) @unittest.skipUnless(connection.vendor == 'mysql', 'MySQL specific') def test_mysql_text_to_traditional(self): # En...
class ExplainTests(TestCase): option = '{} {}'.format(name.upper(), 'true' if value else 'false') self.assertIn(option, captured_queries[0]['sql']) def test_option_sql_injection(self): qs = Tag.objects.filter(name="test") options = {"SUMMARY true) SELECT 1; -...
class DataFrame(NDFrame): for k1, k2 in zip(key, value.columns): self[k1] = value[k2] else: indexer = self.loc._get_listlike_indexer( key, axis=1, raise_missing=False )[1]
class DataFrame(NDFrame): for k1, k2 in zip(key, value.columns): self[k1] = value[k2] else: self.loc._ensure_listlike_indexer(key, axis=1) indexer = self.loc._get_listlike_indexer( key, axis=1, raise_missing=False ...
from pandas.errors import AbstractMethodError from pandas.util._decorators import Appender from pandas.core.dtypes.common import ( is_integer, is_iterator, is_list_like,
from pandas.errors import AbstractMethodError from pandas.util._decorators import Appender from pandas.core.dtypes.common import ( is_hashable, is_integer, is_iterator, is_list_like,
class _LocationIndexer(_NDFrameIndexerBase): """ Convert a potentially-label-based key into a positional indexer. """ if self.axis is not None: return self._convert_tuple(key, is_setter=True)
class _LocationIndexer(_NDFrameIndexerBase): """ Convert a potentially-label-based key into a positional indexer. """ if self.name == "loc": self._ensure_listlike_indexer(key) if self.axis is not None: return self._convert_tuple(key, is_setter=True)
class _LocationIndexer(_NDFrameIndexerBase): raise raise IndexingError(key) from e def __setitem__(self, key, value): if isinstance(key, tuple): key = tuple(com.apply_if_callable(x, self.obj) for x in key)
class _LocationIndexer(_NDFrameIndexerBase): raise raise IndexingError(key) from e def _ensure_listlike_indexer(self, key, axis=None): """ Ensure that a list-like of column labels are all present by adding them if they do not already exist. Parameters ...
class TestDataFrameIndexing: expected = Series(tuples, index=float_frame.index, name="tuples") tm.assert_series_equal(result, expected) def test_setitem_multi_index(self): # GH7655, test that assigning to a sub-frame of a frame # with multi-index columns aligns both rows and columns
class TestDataFrameIndexing: expected = Series(tuples, index=float_frame.index, name="tuples") tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "columns,box,expected", [ ( ["A", "B", "C", "D"], 7, pd.DataF...
class TestDataFrameIndexing: float_frame["col6"] = series tm.assert_series_equal(series, float_frame["col6"], check_names=False) msg = ( r"\"None of \[Float64Index\(\[.*dtype='float64'\)\] are in the " r"\[columns\]\"" ) with pytest.raises(KeyError, match...
class TestDataFrameIndexing: float_frame["col6"] = series tm.assert_series_equal(series, float_frame["col6"], check_names=False) # set ndarray arr = np.random.randn(len(float_frame)) float_frame["col9"] = arr
Region_1,Site_2,3977723089,A,5/20/2015 8:33,5/20/2015 9:09,Yes,No""" assert is_scalar(result) and result == "Z" def test_loc_coercion(self): # 12411
Region_1,Site_2,3977723089,A,5/20/2015 8:33,5/20/2015 9:09,Yes,No""" assert is_scalar(result) and result == "Z" @pytest.mark.parametrize( "index,box,expected", [ ( ([0, 2], ["A", "B", "C", "D"]), 7, pd.DataFrame( ...
except ImportError: # pragma: nocover from pydantic.fields import Field as ModelField # type: ignore async def serialize_response( *, field: ModelField = None,
except ImportError: # pragma: nocover from pydantic.fields import Field as ModelField # type: ignore def _prepare_response_content( res: Any, *, by_alias: bool = True, exclude_unset: bool ) -> Any: if isinstance(res, BaseModel): if PYDANTIC_1: return res.dict(by_alias=by_alias, exclu...
async def serialize_response( ) -> Any: if field: errors = [] if exclude_unset and isinstance(response_content, BaseModel): if PYDANTIC_1: response_content = response_content.dict(exclude_unset=exclude_unset) else: response_content = response_c...
async def serialize_response( ) -> Any: if field: errors = [] response_content = _prepare_response_content( response_content, by_alias=by_alias, exclude_unset=exclude_unset ) if is_coroutine: value, errors_ = field.validate(response_content, {}, loc=("response...
def test_version_exposed(self): "version number does not match", ) if __name__ == "__main__": unittest.main()
def test_version_exposed(self): "version number does not match", ) def test_invalid_typecode(self): s = b";\x2f\x7f" with self.assertRaises(ValueError): rencode.loads(s) if __name__ == "__main__": unittest.main()
from youtube_dl.utils import ( DateRange, encodeFilename, find_xpath_attr, get_meta_content, orderedSet, parse_duration,
from youtube_dl.utils import ( DateRange, encodeFilename, find_xpath_attr, fix_xml_ampersands, get_meta_content, orderedSet, parse_duration,
class TestUtil(unittest.TestCase): self.assertEqual(parse_duration('9:12:43'), 33163) self.assertEqual(parse_duration('x:y'), None) if __name__ == '__main__': unittest.main()
class TestUtil(unittest.TestCase): self.assertEqual(parse_duration('9:12:43'), 33163) self.assertEqual(parse_duration('x:y'), None) def test_fix_xml_ampersands(self): self.assertEqual( fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a') self.assertEqual( fi...
import re from .common import InfoExtractor from ..utils import ( find_xpath_attr, fix_xml_all_ampersand, )
import re from .common import InfoExtractor from ..utils import ( find_xpath_attr, fix_xml_ampersands )
class ClipsyndicateIE(InfoExtractor): pdoc = self._download_xml( 'http://eplayer.clipsyndicate.com/osmf/playlist?%s' % flvars, video_id, u'Downloading video info', transform_source=fix_xml_all_ampersand) track_doc = pdoc.find('trackList/track') def find_para...
class ClipsyndicateIE(InfoExtractor): pdoc = self._download_xml( 'http://eplayer.clipsyndicate.com/osmf/playlist?%s' % flvars, video_id, u'Downloading video info', transform_source=fix_xml_ampersands) track_doc = pdoc.find('trackList/track') def find_param(na...
import re from .common import InfoExtractor from ..utils import ( fix_xml_all_ampersand, )
import re from .common import InfoExtractor from ..utils import ( fix_xml_ampersands, )
class MetacriticIE(InfoExtractor): webpage = self._download_webpage(url, video_id) # The xml is not well formatted, there are raw '&' info = self._download_xml('http://www.metacritic.com/video_data?video=' + video_id, video_id, 'Downloading info xml', transform_source=fix_xml_all_amp...
class MetacriticIE(InfoExtractor): webpage = self._download_webpage(url, video_id) # The xml is not well formatted, there are raw '&' info = self._download_xml('http://www.metacritic.com/video_data?video=' + video_id, video_id, 'Downloading info xml', transform_source=fix_xml_ampersa...
from .common import InfoExtractor from ..utils import ( compat_urllib_parse, ExtractorError, ) def _media_xml_tag(tag):
from .common import InfoExtractor from ..utils import ( compat_urllib_parse, ExtractorError, fix_xml_ampersands, ) def _media_xml_tag(tag):
class MTVServicesInfoExtractor(InfoExtractor): video_id = self._id_from_uri(uri) data = compat_urllib_parse.urlencode({'uri': uri}) def fix_ampersand(s): """ Fix unencoded ampersand in XML """ return s.replace(u'& ', '&amp; ') idoc = self._download_xml( ...
class MTVServicesInfoExtractor(InfoExtractor): video_id = self._id_from_uri(uri) data = compat_urllib_parse.urlencode({'uri': uri}) idoc = self._download_xml( self._FEED_URL + '?' + data, video_id, u'Downloading info', transform_source=fix_xml_ampersands) return ...
def month_by_name(name): return None def fix_xml_all_ampersand(xml_str): """Replace all the '&' by '&amp;' in XML""" return xml_str.replace(u'&', u'&amp;') def setproctitle(title):
def month_by_name(name): return None def fix_xml_ampersands(xml_str): """Replace all the '&' by '&amp;' in XML""" return re.sub( r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)', u'&amp;', xml_str) def setproctitle(title):
""" import logging import OFS.interfaces from AccessControl import safe_builtins
""" import logging import warnings import OFS.interfaces from AccessControl import safe_builtins
def boboAwareZopeTraverse(object, path_items, econtext): while path_items: name = path_items.pop() if OFS.interfaces.ITraversable.providedBy(object): object = object.restrictedTraverse(name) else:
def boboAwareZopeTraverse(object, path_items, econtext): while path_items: name = path_items.pop() if name == '_': warnings.warn('Traversing to the name `_` is deprecated ' 'and will be removed in Zope 6.', DeprecationWarning) ...
"""``chameleon.tales`` expressions.""" from ast import NodeTransformer from ast import parse
"""``chameleon.tales`` expressions.""" import warnings from ast import NodeTransformer from ast import parse
def traverse(cls, base, request, path_items): while path_items: name = path_items.pop() if ITraversable.providedBy(base): base = getattr(base, cls.traverseMethod)(name) else: base = traversePathElement(base, name, path_items, ...
def traverse(cls, base, request, path_items): while path_items: name = path_items.pop() if name == '_': warnings.warn('Traversing to the name `_` is deprecated ' 'and will be removed in Zope 6.', DeprecationWar...
from ..expression import getEngine from . import testHTMLTests
import unittest from ..expression import getEngine from . import testHTMLTests
def setUp(self): # expressions (e.g. the ``zope.tales`` ``not`` expression # returns ``int``, that of ``chameleon.tales`` ``bool`` PREFIX = "CH_"
def setUp(self): # expressions (e.g. the ``zope.tales`` ``not`` expression # returns ``int``, that of ``chameleon.tales`` ``bool`` PREFIX = "CH_" @unittest.skip('The test in the base class relies on a Zope context with' ' the "random" module available in expressions') def tes...
import unittest from AccessControl import safe_builtins from zope.component.testing import PlacelessSetup
import unittest import warnings from AccessControl import safe_builtins from zExceptions import NotFound from zope.component.testing import PlacelessSetup
def test_evaluate_alternative_first_missing(self): self.assertTrue(ec.evaluate('x | nothing') is None) def test_evaluate_dict_key_as_underscore(self): ec = self._makeContext() self.assertEqual(ec.evaluate('d/_'), 'under') def test_evaluate_dict_with_key_from_expansion(self): ec...
def test_evaluate_alternative_first_missing(self): self.assertTrue(ec.evaluate('x | nothing') is None) def test_evaluate_dict_key_as_underscore(self): # Traversing to the name `_` will raise a DeprecationWarning # because it will go away in Zope 6. ec = self._makeContext() w...
def test_list_in_path_expr(self): ec = self._makeContext() self.assertIs(ec.evaluate('nocall: list'), safe_builtins["list"]) class TrustedEngineTests(EngineTestsBase, unittest.TestCase):
def test_list_in_path_expr(self): ec = self._makeContext() self.assertIs(ec.evaluate('nocall: list'), safe_builtins["list"]) def test_underscore_traversal(self): # Prevent traversal to names starting with an underscore (_) ec = self._makeContext() with self.assertRaises(Not...
DefaultUnicodeEncodingConflictResolver from Products.PageTemplates.unicodeconflictresolver import \ PreferredCharsetResolver from zope.component import provideUtility from zope.traversing.adapters import DefaultTraversable
DefaultUnicodeEncodingConflictResolver from Products.PageTemplates.unicodeconflictresolver import \ PreferredCharsetResolver from zExceptions import NotFound from zope.component import provideUtility from zope.traversing.adapters import DefaultTraversable
def testPathNothing(self): def testPathAlt(self): self.assert_expected(self.folder.t, 'CheckPathAlt.html') def testBatchIteration(self): self.assert_expected(self.folder.t, 'CheckBatchIteration.html')
def testPathNothing(self): def testPathAlt(self): self.assert_expected(self.folder.t, 'CheckPathAlt.html') def testPathTraverse(self): # need to perform this test with a "real" folder from OFS.Folder import Folder f = self.folder self.folder = Folder() self.folde...
def test_unicode_conflict_resolution(self): provideUtility(PreferredCharsetResolver) t = PageTemplate() self.assert_expected(t, 'UnicodeResolution.html')
def test_unicode_conflict_resolution(self): provideUtility(PreferredCharsetResolver) t = PageTemplate() self.assert_expected(t, 'UnicodeResolution.html') def test_underscore_traversal(self): t = self.folder.t t.write('<p tal:define="p context/__class__" />') with se...
class TestUtil(unittest.TestCase): self.assertEqual(unified_strdate('8/7/2009'), '20090708') self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214') self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011') def test_find_xpath_attr(self): testxml = u'''<root>
class TestUtil(unittest.TestCase): self.assertEqual(unified_strdate('8/7/2009'), '20090708') 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 unified_strdate(date_str): """Return a string with the date in the format YYYYMMDD""" upload_date = None #Replace commas date_str = date_str.replace(',',' ') # %z (UTC offset) is only supported in python>=3.2 date_str = re.sub(r' ?(\+|-)[0-9:]*$', '', date_str) format_expressions = [ ...
def unified_strdate(date_str): """Return a string with the date in the format YYYYMMDD""" upload_date = None #Replace commas date_str = date_str.replace(',', ' ') # %z (UTC offset) is only supported in python>=3.2 date_str = re.sub(r' ?(\+|-)[0-9]{2}:?[0-9]{2}$', '', date_str) format_express...
class TestFormatSelection(unittest.TestCase): def test_format_selection_string_ops(self): formats = [ {'format_id': 'abc-cba', 'ext': 'mp4', 'url': TEST_URL}, ] info_dict = _make_result(formats)
class TestFormatSelection(unittest.TestCase): def test_format_selection_string_ops(self): formats = [ {'format_id': 'abc-cba', 'ext': 'mp4', 'url': TEST_URL}, {'format_id': 'zxc-cxz', 'ext': 'webm', 'url': TEST_URL}, ] info_dict = _make_result(formats)
class TestFormatSelection(unittest.TestCase): # does not equal (!=) ydl = YDL({'format': '[format_id!=abc-cba]'}) self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy()) # starts with (^=)
class TestFormatSelection(unittest.TestCase): # does not equal (!=) ydl = YDL({'format': '[format_id!=abc-cba]'}) ydl.process_ie_result(info_dict.copy()) downloaded = ydl.downloaded_info_dicts[0] self.assertEqual(downloaded['format_id'], 'zxc-cxz') ydl = YDL({'format': ...
class TestFormatSelection(unittest.TestCase): self.assertEqual(downloaded['format_id'], 'abc-cba') # does not start with (!^=) ydl = YDL({'format': '[format_id!^=abc-cba]'}) self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy()) # ends with ($=)
class TestFormatSelection(unittest.TestCase): self.assertEqual(downloaded['format_id'], 'abc-cba') # does not start with (!^=) ydl = YDL({'format': '[format_id!^=abc]'}) ydl.process_ie_result(info_dict.copy()) downloaded = ydl.downloaded_info_dicts[0] self.assertEqual(do...
class TestFormatSelection(unittest.TestCase): self.assertEqual(downloaded['format_id'], 'abc-cba') # does not end with (!$=) ydl = YDL({'format': '[format_id!$=abc-cba]'}) self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy()) # contains (*=) ydl = Y...
class TestFormatSelection(unittest.TestCase): self.assertEqual(downloaded['format_id'], 'abc-cba') # does not end with (!$=) ydl = YDL({'format': '[format_id!$=cba]'}) ydl.process_ie_result(info_dict.copy()) downloaded = ydl.downloaded_info_dicts[0] self.assertEqual(down...
class YoutubeDL(object): comparison_value = m.group('value') str_op = STR_OPERATORS[m.group('op')] if m.group('negation'): op = lambda attr, value: not str_op else: op = str_op
class YoutubeDL(object): comparison_value = m.group('value') str_op = STR_OPERATORS[m.group('op')] if m.group('negation'): op = lambda attr, value: not str_op(attr, value) else: op = str_op
from django.utils.translation import gettext, gettext_lazy as _ UserModel = get_user_model() class ReadOnlyPasswordHashWidget(forms.Widget): template_name = 'auth/widgets/read_only_password_hash.html' read_only = True
from django.utils.translation import gettext, gettext_lazy as _ UserModel = get_user_model() def _unicode_ci_compare(s1, s2): """ Perform case-insensitive comparison of two identifiers, using the recommended algorithm from Unicode Technical Report 36, section 2.11.2(B)(2). """ return unicodeda...
class PasswordResetForm(forms.Form): that prevent inactive users and users with unusable passwords from resetting their password. """ active_users = UserModel._default_manager.filter(**{ '%s__iexact' % UserModel.get_email_field_name(): email, 'is_active': True, ...
class PasswordResetForm(forms.Form): that prevent inactive users and users with unusable passwords from resetting their password. """ email_field_name = UserModel.get_email_field_name() active_users = UserModel._default_manager.filter(**{ '%s__iexact' % email_field_na...
class PasswordResetForm(forms.Form): user. """ email = self.cleaned_data["email"] for user in self.get_users(email): if not domain_override: current_site = get_current_site(request)
class PasswordResetForm(forms.Form): user. """ email = self.cleaned_data["email"] email_field_name = UserModel.get_email_field_name() for user in self.get_users(email): if not domain_override: current_site = get_current_site(request)
class PasswordResetForm(forms.Form): domain = current_site.domain else: site_name = domain = domain_override context = { 'email': email, 'domain': domain, 'site_name': site_name, 'uid': urlsafe_base64...
class PasswordResetForm(forms.Form): domain = current_site.domain else: site_name = domain = domain_override user_email = getattr(user, email_field_name) context = { 'email': user_email, 'domain': domain, ...
class PasswordResetForm(forms.Form): } self.send_mail( subject_template_name, email_template_name, context, from_email, email, html_email_template_name=html_email_template_name, )
class PasswordResetForm(forms.Form): } self.send_mail( subject_template_name, email_template_name, context, from_email, user_email, html_email_template_name=html_email_template_name, )
class PasswordResetFormTest(TestDataMixin, TestCase): self.assertFalse(form.is_valid()) self.assertEqual(form['email'].errors, [_('Enter a valid email address.')]) def test_nonexistent_email(self): """ Test nonexistent email address. This should not fail because it would
class PasswordResetFormTest(TestDataMixin, TestCase): self.assertFalse(form.is_valid()) self.assertEqual(form['email'].errors, [_('Enter a valid email address.')]) def test_user_email_unicode_collision(self): User.objects.create_user('mike123', 'mike@example.org', 'test123') User.ob...
class Request: :rtype: str """ # Full URL SERVER_NAME can only be handled in app.url_for if "//" in self.app.config.SERVER_NAME: return self.app.url_for(view_name, _external=True, **kwargs) scheme = self.scheme host = self.server_name
class Request: :rtype: str """ # Full URL SERVER_NAME can only be handled in app.url_for try: if "//" in self.app.config.SERVER_NAME: return self.app.url_for(view_name, _external=True, **kwargs) except AttributeError: pass scheme =...
async def test_endpoint_blueprint_asgi(): request, response = await app.asgi_client.get("/bp") assert request.endpoint == "named.my_blueprint.bp_root"
async def test_endpoint_blueprint_asgi(): request, response = await app.asgi_client.get("/bp") assert request.endpoint == "named.my_blueprint.bp_root" def test_url_for_without_server_name(app): @app.route("/sample") def sample(request): return json({"url": request.url_for("url_for")}) @a...
def read_fixed_bytes(self, num_bytes: int) -> bytes: """ read_bytes = self.read(num_bytes) if len(read_bytes) < num_bytes: raise EOFError(read_bytes) return read_bytes def read_pascal_bytes(self, string_length_size: int) -> bytes:
def read_fixed_bytes(self, num_bytes: int) -> bytes: """ read_bytes = self.read(num_bytes) if len(read_bytes) < num_bytes: raise EOFError("Fewer than 'num_bytes' bytes remaining in the " "underlying bytestream") return read_bytes def read_pascal_bytes...
class Axes(_AxesBase): @_preprocess_data(replace_names=["y", "xmin", "xmax", "colors"], label_namer="y") def hlines(self, y, xmin, xmax, colors='k', linestyles='solid', label='', **kwargs): """ Plot horizontal lines at each *y* from *xmin* to *xmax*.
class Axes(_AxesBase): @_preprocess_data(replace_names=["y", "xmin", "xmax", "colors"], label_namer="y") def hlines(self, y, xmin, xmax, colors=None, linestyles='solid', label='', **kwargs): """ Plot horizontal lines at each *y* from *xmin* to *xmax*.
class Axes(_AxesBase): Respective beginning and end of each line. If scalars are provided, all lines will have same length. colors : list of colors, default: 'k' linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, optional
class Axes(_AxesBase): Respective beginning and end of each line. If scalars are provided, all lines will have same length. colors : list of colors, default: :rc:`lines.color` linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, optional
class Axes(_AxesBase): @_preprocess_data(replace_names=["x", "ymin", "ymax", "colors"], label_namer="x") def vlines(self, x, ymin, ymax, colors='k', linestyles='solid', label='', **kwargs): """ Plot vertical lines.
class Axes(_AxesBase): @_preprocess_data(replace_names=["x", "ymin", "ymax", "colors"], label_namer="x") def vlines(self, x, ymin, ymax, colors=None, linestyles='solid', label='', **kwargs): """ Plot vertical lines.
class Axes(_AxesBase): Respective beginning and end of each line. If scalars are provided, all lines will have same length. colors : list of colors, default: 'k' linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, optional
class Axes(_AxesBase): Respective beginning and end of each line. If scalars are provided, all lines will have same length. colors : list of colors, default: :rc:`lines.color` linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, optional
def hist2d( # Autogenerated by boilerplate.py. Do not edit as changes will be lost. @_copy_docstring_and_deprecators(Axes.hlines) def hlines( y, xmin, xmax, colors='k', linestyles='solid', label='', *, data=None, **kwargs): return gca().hlines( y, xmin, xmax, colors=colors, linestyles=lines...
def hist2d( # Autogenerated by boilerplate.py. Do not edit as changes will be lost. @_copy_docstring_and_deprecators(Axes.hlines) def hlines( y, xmin, xmax, colors=None, linestyles='solid', label='', *, data=None, **kwargs): return gca().hlines( y, xmin, xmax, colors=colors, linestyles=line...
def violinplot( # Autogenerated by boilerplate.py. Do not edit as changes will be lost. @_copy_docstring_and_deprecators(Axes.vlines) def vlines( x, ymin, ymax, colors='k', linestyles='solid', label='', *, data=None, **kwargs): return gca().vlines( x, ymin, ymax, colors=colors, linestyles=l...
def violinplot( # Autogenerated by boilerplate.py. Do not edit as changes will be lost. @_copy_docstring_and_deprecators(Axes.vlines) def vlines( x, ymin, ymax, colors=None, linestyles='solid', label='', *, data=None, **kwargs): return gca().vlines( x, ymin, ymax, colors=colors, linestyles=...
def test_vlines(): ax5.set_xlim(0, 15) @image_comparison(['hlines_basic', 'hlines_with_nan', 'hlines_masked'], extensions=['png']) def test_hlines():
def test_vlines(): ax5.set_xlim(0, 15) def test_vlines_default(): fig, ax = plt.subplots() with mpl.rc_context({'lines.color': 'red'}): lines = ax.vlines(0.5, 0, 1) assert mpl.colors.same_color(lines.get_color(), 'red') @image_comparison(['hlines_basic', 'hlines_with_nan', 'hlines_masked...
def test_hlines(): ax5.set_ylim(0, 15) @pytest.mark.parametrize('data', [[1, 2, 3, np.nan, 5], np.ma.masked_equal([1, 2, 3, 4, 5], 4)]) @check_figures_equal(extensions=["png"])
def test_hlines(): ax5.set_ylim(0, 15) def test_hlines_default(): fig, ax = plt.subplots() with mpl.rc_context({'lines.color': 'red'}): lines = ax.hlines(0.5, 0, 1) assert mpl.colors.same_color(lines.get_color(), 'red') @pytest.mark.parametrize('data', [[1, 2, 3, np.nan, 5], ...
import json from django import forms from django.conf import settings from django.core.exceptions import ValidationError from django.db.models.deletion import CASCADE from django.urls import reverse from django.urls.exceptions import NoReverseMatch
import json from django import forms from django.conf import settings from django.core.exceptions import ValidationError from django.core.validators import URLValidator from django.db.models.deletion import CASCADE from django.urls import reverse from django.urls.exceptions import NoReverseMatch
class AdminEmailInputWidget(forms.EmailInput): class AdminURLFieldWidget(forms.URLInput): template_name = 'admin/widgets/url.html' def __init__(self, attrs=None): super().__init__(attrs={'class': 'vURLField', **(attrs or {})}) def get_context(self, name, value, attrs): context = super().ge...
class AdminEmailInputWidget(forms.EmailInput): class AdminURLFieldWidget(forms.URLInput): template_name = 'admin/widgets/url.html' def __init__(self, attrs=None, validator_class=URLValidator): super().__init__(attrs={'class': 'vURLField', **(attrs or {})}) self.validator = validator_class() ...
class AdminSplitDateTimeWidgetTest(SimpleTestCase): class AdminURLWidgetTest(SimpleTestCase): def test_render(self): w = widgets.AdminURLFieldWidget() self.assertHTMLEqual(
class AdminSplitDateTimeWidgetTest(SimpleTestCase): class AdminURLWidgetTest(SimpleTestCase): def test_get_context_validates_url(self): w = widgets.AdminURLFieldWidget() for invalid in ['', '/not/a/full/url/', 'javascript:alert("Danger XSS!")']: with self.subTest(url=invalid): ...
class AdminURLWidgetTest(SimpleTestCase): VALUE_RE = re.compile('value="([^"]+)"') TEXT_RE = re.compile('<a[^>]+>([^>]+)</a>') w = widgets.AdminURLFieldWidget() output = w.render('test', 'http://example.com/<sometag>some text</sometag>') self.assertEqual( HREF_RE.sear...
class AdminURLWidgetTest(SimpleTestCase): VALUE_RE = re.compile('value="([^"]+)"') TEXT_RE = re.compile('<a[^>]+>([^>]+)</a>') w = widgets.AdminURLFieldWidget() output = w.render('test', 'http://example.com/<sometag>some-text</sometag>') self.assertEqual( HREF_RE.sear...
def dump_to_file(*output: str) -> str: import tempfile with tempfile.NamedTemporaryFile( mode="w", prefix="blk_", suffix=".log", delete=False ) as f: for lines in output: f.write(lines)
def dump_to_file(*output: str) -> str: import tempfile with tempfile.NamedTemporaryFile( mode="w", prefix="blk_", suffix=".log", delete=False, encoding="utf8" ) as f: for lines in output: f.write(lines)
class BlackTestCase(unittest.TestCase): tmp_file = Path(black.dump_to_file(source)) try: self.assertTrue(ff(tmp_file, write_back=black.WriteBack.YES)) with open(tmp_file) as f: actual = f.read() finally: os.unlink(tmp_file)
class BlackTestCase(unittest.TestCase): tmp_file = Path(black.dump_to_file(source)) try: self.assertTrue(ff(tmp_file, write_back=black.WriteBack.YES)) with open(tmp_file, encoding="utf8") as f: actual = f.read() finally: os.unlink(tmp_file)
def diff(arr, n: int, axis: int = 0): dtype = arr.dtype is_timedelta = False if needs_i8_conversion(arr): dtype = np.float64 arr = arr.view("i8")
def diff(arr, n: int, axis: int = 0): dtype = arr.dtype is_timedelta = False is_bool = False if needs_i8_conversion(arr): dtype = np.float64 arr = arr.view("i8")