buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class TestTimedeltaIndex(DatetimeLike): def test_pickle_compat_construction(self): pass def test_isin(self): index = tm.makeTimedeltaIndex(4)
class TestTimedeltaIndex(DatetimeLike): def test_pickle_compat_construction(self): pass def test_pickle_after_set_freq(self): tdi = timedelta_range("1 day", periods=4, freq="s") tdi = tdi._with_freq(None) res = tm.round_trip_pickle(tdi) tm.assert_index_equal(res, tdi) ...
def _unstack_multiple(data, clocs, fill_value=None): index = data.index clocs = [index._get_level_number(i) for i in clocs] rlocs = [i for i in range(index.nlevels) if i not in clocs]
def _unstack_multiple(data, clocs, fill_value=None): index = data.index # GH 19966 Make sure if MultiIndexed index has tuple name, they will be # recognised as a whole if clocs in index.names: clocs = [clocs] clocs = [index._get_level_number(i) for i in clocs] rlocs = [i for i in rang...
class TestDataFrameReshape: ) tm.assert_frame_equal(result, expected) def test_unstack_preserve_dtypes(self): # Checks fix for #11847 df = pd.DataFrame(
class TestDataFrameReshape: ) tm.assert_frame_equal(result, expected) def test_unstack_tuplename_in_multiindex(self): # GH 19966 idx = pd.MultiIndex.from_product( [["a", "b", "c"], [1, 2, 3]], names=[("A", "a"), ("B", "b")] ) df = pd.DataFrame({"d": [1] *...
import pytest import pandas.util._test_decorators as td import pandas as pd from pandas import DataFrame, MultiIndex, Series import pandas._testing as tm
import pytest import pandas.util._test_decorators as td import pandas as pd from pandas import DataFrame, Series import pandas._testing as tm
class TestSeriesAnalytics: assert s.is_monotonic is False assert s.is_monotonic_decreasing is True def test_unstack(self): index = MultiIndex( levels=[["bar", "foo"], ["one", "three", "two"]], codes=[[1, 1, 0, 0], [0, 1, 0, 2]], ) s = Series(np.aran...
class TestSeriesAnalytics: assert s.is_monotonic is False assert s.is_monotonic_decreasing is True @pytest.mark.parametrize("func", [np.any, np.all]) @pytest.mark.parametrize("kwargs", [dict(keepdims=True), dict(out=object())]) @td.skip_if_np_lt("1.15")
def test_not_match(command): @pytest.mark.parametrize('command, new_command', [ (Command('man read'), ['read --help', 'man 3 read', 'man 2 read']), (Command('man 2 read'), 'man 3 read'), (Command('man 3 read'), 'man 2 read'), (Command('man -s2 read'), 'man -s3 read'),
def test_not_match(command): @pytest.mark.parametrize('command, new_command', [ (Command('man read'), ['man 3 read', 'man 2 read', 'read --help']), (Command('man missing', stderr="No manual entry for missing\n"), ['missing --help']), (Command('man 2 read'), 'man 3 read'), (Command('man 3 read'), 'man ...
def get_new_command(command): if '2' in command.script: return command.script.replace("2", "3") split_cmd2 = command.script_parts split_cmd3 = split_cmd2[:] split_cmd2.insert(1, ' 2 ') split_cmd3.insert(1, ' 3 ') last_arg = command.script_parts[-1] return [ last_arg + ' -...
def get_new_command(command): if '2' in command.script: return command.script.replace("2", "3") last_arg = command.script_parts[-1] help_command = last_arg + ' --help' # If there are no man pages for last_arg, suggest `last_arg --help` instead. # Otherwise, suggest `--help` after suggestin...
def _read_file(filename): package_dir={'': 'src'}, python_requires='>= 3.6', install_requires=[ 'AccessControl >= 4.2', 'Acquisition', 'BTrees', 'Chameleon >= 3.7.0',
def _read_file(filename): package_dir={'': 'src'}, python_requires='>= 3.6', install_requires=[ 'AccessControl >= 5.2', 'Acquisition', 'BTrees', 'Chameleon >= 3.7.0',
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:
class Register(abc.ABCMeta): # We return this in a topologically sorted list of inheritance: this is useful in some cases (#822) reg = OrderedDict() for cls in cls._reg: if cls.run == NotImplemented: continue name = cls.task_family if name in ...
class Register(abc.ABCMeta): # We return this in a topologically sorted list of inheritance: this is useful in some cases (#822) reg = OrderedDict() for cls in cls._reg: name = cls.task_family if name in reg and reg[name] != cls and \
class AmbiguousClass(luigi.Task): pass class NonAmbiguousClass(luigi.ExternalTask): pass class NonAmbiguousClass(luigi.Task): def run(self): NonAmbiguousClass.has_run = True class TaskWithSameName(luigi.Task): def run(self):
class AmbiguousClass(luigi.Task): pass class TaskWithSameName(luigi.Task): def run(self):
class CmdlineTest(unittest.TestCase): def test_cmdline_ambiguous_class(self, logger): self.assertRaises(Exception, luigi.run, ['--local-scheduler', '--no-lock', 'AmbiguousClass']) @mock.patch("logging.getLogger") @mock.patch("warnings.warn") def test_cmdline_non_ambiguous_class(self, warn, logg...
class CmdlineTest(unittest.TestCase): def test_cmdline_ambiguous_class(self, logger): self.assertRaises(Exception, luigi.run, ['--local-scheduler', '--no-lock', 'AmbiguousClass']) @mock.patch("logging.getLogger") @mock.patch("logging.StreamHandler") def test_setup_interface_logging(self, handle...
from datetime import datetime, timedelta import luigi import luigi.task class DummyTask(luigi.Task):
from datetime import datetime, timedelta import luigi import luigi.task from luigi.task_register import load_task class DummyTask(luigi.Task):
class TaskTest(unittest.TestCase): other = DummyTask.from_str_params(original.to_str_params()) self.assertEqual(original, other) def test_id_to_name_and_params(self): task_id = "InputText(date=2014-12-29)" (name, params) = luigi.task.id_to_name_and_params(task_id)
class TaskTest(unittest.TestCase): other = DummyTask.from_str_params(original.to_str_params()) self.assertEqual(original, other) def test_external_tasks_loadable(self): task = load_task("luigi", "ExternalTask", {}) assert(isinstance(task, luigi.ExternalTask)) def test_id_to_nam...
def set_user_password(self, context, user_id, user): def update_user_tenant(self, context, user_id, user): """Update the default tenant.""" # ensure that we're a member of that tenant tenant_id = user.get('tenantId') self.identity_api.add_user_to_tenant(context, tenant_id, user_id)
def set_user_password(self, context, user_id, user): def update_user_tenant(self, context, user_id, user): """Update the default tenant.""" self.assert_admin(context) # ensure that we're a member of that tenant tenant_id = user.get('tenantId') self.identity_api.add_user_to_t...
def test_match(stderr): def test_get_new_command(stderr): assert get_new_command(Command('git push', stderr=stderr))\ == "git push --set-upstream origin master" assert get_new_command(Command('git push -u origin', stderr=stderr))\ == "git push --set-upstream origin master" assert get_new_com...
def test_match(stderr): def test_get_new_command(stderr): assert get_new_command(Command('git push', stderr=stderr))\ == "git push --set-upstream origin master" assert get_new_command(Command('git push -u', stderr=stderr))\ == "git push --set-upstream origin master" assert get_new_command(Co...
def get_new_command(command): pass if upstream_option_index is not -1: command.script_parts.pop(upstream_option_index) command.script_parts.pop(upstream_option_index) push_upstream = command.stderr.split('\n')[-3].strip().partition('git ')[2] return replace_argument(" ".join(command...
def get_new_command(command): pass if upstream_option_index is not -1: command.script_parts.pop(upstream_option_index) try: command.script_parts.pop(upstream_option_index) except IndexError: # This happens for `git push -u` pass push_upstream ...
from six.moves.urllib.parse import urlunparse from scrapy.utils.httpobj import urlparse_cached from scrapy.exceptions import NotConfigured class HttpProxyMiddleware(object):
from six.moves.urllib.parse import urlunparse from scrapy.utils.httpobj import urlparse_cached from scrapy.exceptions import NotConfigured from scrapy.utils.python import to_bytes class HttpProxyMiddleware(object):
class HttpProxyMiddleware(object): proxy_url = urlunparse((proxy_type or orig_type, hostport, '', '', '', '')) if user: user_pass = '%s:%s' % (unquote(user), unquote(password)) creds = base64.b64encode(user_pass).strip() else: creds = None
class HttpProxyMiddleware(object): proxy_url = urlunparse((proxy_type or orig_type, hostport, '', '', '', '')) if user: user_pass = to_bytes('%s:%s' % (unquote(user), unquote(password))) creds = base64.b64encode(user_pass).strip() else: creds = None
class HttpProxyMiddleware(object): creds, proxy = self.proxies[scheme] request.meta['proxy'] = proxy if creds: request.headers['Proxy-Authorization'] = 'Basic ' + creds
class HttpProxyMiddleware(object): creds, proxy = self.proxies[scheme] request.meta['proxy'] = proxy if creds: request.headers['Proxy-Authorization'] = b'Basic ' + creds
class TestDefaultHeadersMiddleware(TestCase): req = Request('http://scrapytest.org') assert mw.process_request(req, spider) is None self.assertEquals(req.meta, {'proxy': 'https://proxy:3128'}) self.assertEquals(req.headers.get('Proxy-Authorization'), 'Basic dXNlcjpwYXNz') def test_p...
class TestDefaultHeadersMiddleware(TestCase): req = Request('http://scrapytest.org') assert mw.process_request(req, spider) is None self.assertEquals(req.meta, {'proxy': 'https://proxy:3128'}) self.assertEquals(req.headers.get('Proxy-Authorization'), b'Basic dXNlcjpwYXNz') def test_...
class TestDefaultHeadersMiddleware(TestCase): req = Request('http://scrapytest.org') assert mw.process_request(req, spider) is None self.assertEquals(req.meta, {'proxy': 'https://proxy:3128'}) self.assertEquals(req.headers.get('Proxy-Authorization'), 'Basic dXNlcjo=') def test_proxy...
class TestDefaultHeadersMiddleware(TestCase): req = Request('http://scrapytest.org') assert mw.process_request(req, spider) is None self.assertEquals(req.meta, {'proxy': 'https://proxy:3128'}) self.assertEquals(req.headers.get('Proxy-Authorization'), b'Basic dXNlcjo=') def test_prox...
class RetryTest(unittest.TestCase): def test_priority_adjust(self): req = Request('http://www.scrapytest.org/503') rsp = Response('http://www.scrapytest.org/503', body='', status=503) req2 = self.mw.process_response(req, rsp, self.spider) assert req2.priority < req.priority def...
class RetryTest(unittest.TestCase): def test_priority_adjust(self): req = Request('http://www.scrapytest.org/503') rsp = Response('http://www.scrapytest.org/503', body=b'', status=503) req2 = self.mw.process_response(req, rsp, self.spider) assert req2.priority < req.priority de...
class RetryTest(unittest.TestCase): def test_503(self): req = Request('http://www.scrapytest.org/503') rsp = Response('http://www.scrapytest.org/503', body='', status=503) # first retry req = self.mw.process_response(req, rsp, self.spider)
class RetryTest(unittest.TestCase): def test_503(self): req = Request('http://www.scrapytest.org/503') rsp = Response('http://www.scrapytest.org/503', body=b'', status=503) # first retry req = self.mw.process_response(req, rsp, self.spider)
def verify_signature(pubkey_path, message, signature): try: return pubkey.verify(digest, signature) except RSA.RSAError as exc: if exc.args[0] == "bad signature": return False raise else: verifier = PKCS1_v1_5.new(pubkey) return ver...
def verify_signature(pubkey_path, message, signature): try: return pubkey.verify(digest, signature) except RSA.RSAError as exc: log.debug("Signature verification failed: %s", exc.args[0]) return False else: verifier = PKCS1_v1_5.new(pubkey) return ...
class AsyncAuth: clear_signature = payload["sig"] payload = salt.payload.loads(clear_signed_data) auth["aes"] = self.verify_master(payload, master_pub="token" in sign_in_payload) if not auth["aes"]: log.critical( "The Salt Master server's public key did not a...
class AsyncAuth: clear_signature = payload["sig"] payload = salt.payload.loads(clear_signed_data) if "pub_key" in payload: auth["aes"] = self.verify_master( payload, master_pub="token" in sign_in_payload ) if not auth["aes"]: l...
import salt.crypt import salt.master import salt.utils.files def test_get_rsa_pub_key_bad_key(tmp_path): """
import salt.crypt import salt.master import salt.utils.files PRIV_KEY = """ -----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEAoAsMPt+4kuIG6vKyw9r3+OuZrVBee/2vDdVetW+Js5dTlgrJ aghWWn3doGmKlEjqh7E4UTa+t2Jd6w8RSLnyHNJ/HpVhMG0M07MF6FMfILtDrrt8 ZX7eDVt8sx5gCEpYI+XG8Y07Ga9i3Hiczt+fu6HYwu96HggmG2pqkOrn3iGfqBvV YVFJzSZYe7e4c1Pe...
def test_cryptical_dumps_invalid_nonce(): assert isinstance(ret, bytes) with pytest.raises(salt.crypt.SaltClientError, match="Nonce verification error"): assert master_crypt.loads(ret, nonce="abcde")
def test_cryptical_dumps_invalid_nonce(): assert isinstance(ret, bytes) with pytest.raises(salt.crypt.SaltClientError, match="Nonce verification error"): assert master_crypt.loads(ret, nonce="abcde") def test_verify_signature(tmpdir): tmpdir.join("foo.pem").write(PRIV_KEY.strip()) tmpdir.join(...
async def test_req_chan_auth_v2_with_master_signing(pki_dir, io_loop): pki_dir.join("minion", "minion_master.pub").read() == pki_dir.join("master", "master.pub").read() )
async def test_req_chan_auth_v2_with_master_signing(pki_dir, io_loop): pki_dir.join("minion", "minion_master.pub").read() == pki_dir.join("master", "master.pub").read() ) async def test_req_chan_auth_v2_new_minion_with_master_pub(pki_dir, io_loop): pki_dir.join("master", "minions", "minion")....
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 django.contrib.postgres.fields import ArrayField, JSONField from django.db.models.aggregates import Aggregate from .mixins import OrderableAggMixin
from django.contrib.postgres.fields import ArrayField, JSONField from django.db.models import Value from django.db.models.aggregates import Aggregate from .mixins import OrderableAggMixin
class JSONBAgg(Aggregate): class StringAgg(OrderableAggMixin, Aggregate): function = 'STRING_AGG' template = "%(function)s(%(distinct)s%(expressions)s, '%(delimiter)s'%(ordering)s)" allow_distinct = True def __init__(self, expression, delimiter, **extra): super().__init__(expression, delimiter...
class JSONBAgg(Aggregate): class StringAgg(OrderableAggMixin, Aggregate): function = 'STRING_AGG' template = '%(function)s(%(distinct)s%(expressions)s %(ordering)s)' allow_distinct = True def __init__(self, expression, delimiter, **extra): delimiter_expr = Value(str(delimiter)) super()...
from django.db.models.expressions import F, OrderBy class OrderableAggMixin: def __init__(self, expression, ordering=(), **extra): if not isinstance(ordering, (list, tuple)): ordering = [ordering] ordering = ordering or []
from django.db.models.expressions import F, OrderBy class OrderableAggMixin: def __init__(self, *expressions, ordering=(), **extra): if not isinstance(ordering, (list, tuple)): ordering = [ordering] ordering = ordering or []
class OrderableAggMixin: (OrderBy(F(o[1:]), descending=True) if isinstance(o, str) and o[0] == '-' else o) for o in ordering ) super().__init__(expression, **extra) self.ordering = self._parse_expressions(*ordering) def resolve_expression(self, *args, **kwargs):
class OrderableAggMixin: (OrderBy(F(o[1:]), descending=True) if isinstance(o, str) and o[0] == '-' else o) for o in ordering ) super().__init__(*expressions, **extra) self.ordering = self._parse_expressions(*ordering) def resolve_expression(self, *args, **kwargs):
class TestGeneralAggregate(PostgreSQLTestCase): with self.assertRaises(TypeError): AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field')) def test_string_agg_charfield(self): values = AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field', delimiter=';'))...
class TestGeneralAggregate(PostgreSQLTestCase): with self.assertRaises(TypeError): AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field')) def test_string_agg_delimiter_escaping(self): values = AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field', delimi...
from django.utils.cache import ( cc_delim_re, get_conditional_response, set_response_etag, ) from django.utils.deprecation import MiddlewareMixin, RemovedInDjango21Warning class CommonMiddleware(MiddlewareMixin):
from django.utils.cache import ( cc_delim_re, get_conditional_response, set_response_etag, ) from django.utils.deprecation import MiddlewareMixin, RemovedInDjango21Warning from django.utils.http import escape_leading_slashes class CommonMiddleware(MiddlewareMixin):
class CommonMiddleware(MiddlewareMixin): POST, PUT, or PATCH. """ new_path = request.get_full_path(force_append_slash=True) if settings.DEBUG and request.method in ('POST', 'PUT', 'PATCH'): raise RuntimeError( "You called this URL via %(method)s, but the URL d...
class CommonMiddleware(MiddlewareMixin): POST, PUT, or PATCH. """ new_path = request.get_full_path(force_append_slash=True) # Prevent construction of scheme relative urls. new_path = escape_leading_slashes(new_path) if settings.DEBUG and request.method in ('POST', 'PUT', ...
from django.core.checks.urls import check_resolver from django.core.exceptions import ImproperlyConfigured from django.utils.datastructures import MultiValueDict from django.utils.functional import cached_property from django.utils.http import RFC3986_SUBDELIMS from django.utils.regex_helper import normalize from djang...
from django.core.checks.urls import check_resolver from django.core.exceptions import ImproperlyConfigured from django.utils.datastructures import MultiValueDict from django.utils.functional import cached_property from django.utils.http import RFC3986_SUBDELIMS, escape_leading_slashes from django.utils.regex_helper imp...
class URLResolver: # safe characters from `pchar` definition of RFC 3986 url = quote(candidate_pat % text_candidate_subs, safe=RFC3986_SUBDELIMS + '/~:@') # Don't allow construction of scheme relative urls. if url.startswith('//'): ...
class URLResolver: # safe characters from `pchar` definition of RFC 3986 url = quote(candidate_pat % text_candidate_subs, safe=RFC3986_SUBDELIMS + '/~:@') # Don't allow construction of scheme relative urls. return escape_leading_slashes(url...
def limited_parse_qsl(qs, keep_blank_values=False, encoding='utf-8', value = unquote(value, encoding=encoding, errors=errors) r.append((name, value)) return r
def limited_parse_qsl(qs, keep_blank_values=False, encoding='utf-8', value = unquote(value, encoding=encoding, errors=errors) r.append((name, value)) return r def escape_leading_slashes(url): """ If redirecting to an absolute path (two leading slashes), a slash must be escaped ...
class CommonMiddlewareTest(SimpleTestCase): self.assertEqual(r.status_code, 301) self.assertEqual(r.url, '/needsquoting%23/') @override_settings(APPEND_SLASH=False, PREPEND_WWW=True) def test_prepend_www(self): request = self.rf.get('/path/')
class CommonMiddlewareTest(SimpleTestCase): self.assertEqual(r.status_code, 301) self.assertEqual(r.url, '/needsquoting%23/') @override_settings(APPEND_SLASH=True) def test_append_slash_leading_slashes(self): """ Paths starting with two slashes are escaped to prevent open redire...
urlpatterns = [ url(r'^noslash$', views.empty_view), url(r'^slash/$', views.empty_view), url(r'^needsquoting#/$', views.empty_view), ]
urlpatterns = [ url(r'^noslash$', views.empty_view), url(r'^slash/$', views.empty_view), url(r'^needsquoting#/$', views.empty_view), # Accepts paths with two leading slashes. url(r'^(.+)/security/$', views.empty_view), ]
from django.utils import http from django.utils.datastructures import MultiValueDict from django.utils.deprecation import RemovedInDjango21Warning from django.utils.http import ( base36_to_int, cookie_date, http_date, int_to_base36, is_safe_url, is_same_domain, parse_etags, parse_http_date, quote_etag, urlencod...
from django.utils import http from django.utils.datastructures import MultiValueDict from django.utils.deprecation import RemovedInDjango21Warning from django.utils.http import ( base36_to_int, cookie_date, escape_leading_slashes, http_date, int_to_base36, is_safe_url, is_same_domain, parse_etags, parse_http_da...
class HttpDateProcessingTests(unittest.TestCase): def test_parsing_asctime(self): parsed = parse_http_date('Sun Nov 6 08:49:37 1994') self.assertEqual(datetime.utcfromtimestamp(parsed), datetime(1994, 11, 6, 8, 49, 37))
class HttpDateProcessingTests(unittest.TestCase): def test_parsing_asctime(self): parsed = parse_http_date('Sun Nov 6 08:49:37 1994') self.assertEqual(datetime.utcfromtimestamp(parsed), datetime(1994, 11, 6, 8, 49, 37)) class EscapeLeadingSlashesTests(unittest.TestCase): def test(self): ...
import threading import time import traceback import math import weakref from tornado.concurrent import Future, is_future, chain_future, future_set_exc_info, future_add_done_callback # noqa: E501 from tornado.log import app_log, gen_log
import threading import time import traceback import math from tornado.concurrent import Future, is_future, chain_future, future_set_exc_info, future_add_done_callback # noqa: E501 from tornado.log import app_log, gen_log
class IOLoop(Configurable): _current = threading.local() # In Python 3, _ioloop_for_asyncio maps from asyncio loops to IOLoops. _ioloop_for_asyncio = weakref.WeakKeyDictionary() @classmethod def configure(cls, impl, **kwargs):
class IOLoop(Configurable): _current = threading.local() # In Python 3, _ioloop_for_asyncio maps from asyncio loops to IOLoops. _ioloop_for_asyncio = dict() @classmethod def configure(cls, impl, **kwargs):
class BaseAsyncIOLoop(IOLoop): self.readers = set() self.writers = set() self.closing = False IOLoop._ioloop_for_asyncio[asyncio_loop] = self super(BaseAsyncIOLoop, self).initialize(**kwargs)
class BaseAsyncIOLoop(IOLoop): self.readers = set() self.writers = set() self.closing = False # If an asyncio loop was closed through an asyncio interface # instead of IOLoop.close(), we'd never hear about it and may # have left a dangling reference in our map. In case an...
class BaseAsyncIOLoop(IOLoop): if all_fds: self.close_fd(fileobj) self.asyncio_loop.close() def add_handler(self, fd, handler, events): fd, fileobj = self.split_fd(fd)
class BaseAsyncIOLoop(IOLoop): if all_fds: self.close_fd(fileobj) self.asyncio_loop.close() del IOLoop._ioloop_for_asyncio[self.asyncio_loop] def add_handler(self, fd, handler, events): fd, fileobj = self.split_fd(fd)
class AsyncIOLoopTest(AsyncTestCase): 42) @unittest.skipIf(asyncio is None, "asyncio module not present") class AnyThreadEventLoopPolicyTest(unittest.TestCase): def setUp(self):
class AsyncIOLoopTest(AsyncTestCase): 42) @unittest.skipIf(asyncio is None, "asyncio module not present") class LeakTest(unittest.TestCase): def setUp(self): # Trigger a cleanup of the mapping so we start with a clean slate. AsyncIOLoop().close() # If we don't clean up after ou...
from django.db import models from django.http import Http404 from django.template.engine import Engine from django.urls import get_mod_func, get_resolver, get_urlconf from django.utils.decorators import method_decorator from django.utils.functional import cached_property from django.utils.inspect import (
from django.db import models from django.http import Http404 from django.template.engine import Engine from django.urls import get_mod_func, get_resolver, get_urlconf from django.utils._os import safe_join from django.utils.decorators import method_decorator from django.utils.functional import cached_property from djan...
class TemplateDetailView(BaseAdminDocsView): else: # This doesn't account for template loaders (#24128). for index, directory in enumerate(default_engine.dirs): template_file = Path(directory) / template if template_file.exists(): templ...
class TemplateDetailView(BaseAdminDocsView): else: # This doesn't account for template loaders (#24128). for index, directory in enumerate(default_engine.dirs): template_file = Path(safe_join(directory, template)) if template_file.exists(): ...
class AdminDocViewTests(TestDataMixin, AdminDocsTestCase): self.assertEqual(response.status_code, 200) @override_settings(TEMPLATES=[{ 'NAME': 'ONE', 'BACKEND': 'django.template.backends.django.DjangoTemplates',
class AdminDocViewTests(TestDataMixin, AdminDocsTestCase): self.assertEqual(response.status_code, 200) @unittest.skipUnless(utils.docutils_is_available, 'no docutils installed.') class AdminDocViewDefaultEngineOnly(TestDataMixin, AdminDocsTestCase): def setUp(self): self.client.force_login(se...
class FileSystemStorage(Storage): directory = os.path.dirname(full_path) try: if self.directory_permissions_mode is not None: # os.makedirs applies the global umask, so we reset it, # for consistency with file_permissions_mode behavior. old_uma...
class FileSystemStorage(Storage): directory = os.path.dirname(full_path) try: if self.directory_permissions_mode is not None: # Set the umask because os.makedirs() doesn't apply the "mode" # argument to intermediate-level directories. old_umask...
import time import unittest from datetime import datetime, timedelta from io import StringIO from urllib.request import urlopen from django.core.cache import cache
import time import unittest from datetime import datetime, timedelta from io import StringIO from pathlib import Path from urllib.request import urlopen from django.core.cache import cache
class FileStoragePermissions(unittest.TestCase): @override_settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765) def test_file_upload_directory_permissions(self): self.storage = FileSystemStorage(self.storage_dir) name = self.storage.save("the_directory/the_file", ContentFile("data")) dir_mo...
class FileStoragePermissions(unittest.TestCase): @override_settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765) def test_file_upload_directory_permissions(self): self.storage = FileSystemStorage(self.storage_dir) name = self.storage.save('the_directory/subdir/the_file', ContentFile('data')) ...
import sys import tempfile import unittest from io import StringIO from unittest import mock from django.conf import settings
import sys import tempfile import unittest from io import StringIO from pathlib import Path from unittest import mock from django.conf import settings
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_permissions(self): call_command('collectstatic', **self.command_params) test_file = os.path.join(settings.STATIC_ROOT, "test.txt") test_dir = os.path.join(settings.STATIC_ROOT, "subdir") file_mod...
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_permissions(self): call_command('collectstatic', **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / 'test.txt' file_mode = test_file.stat().st_mode & 0o777 ...
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_default_permissions(self): call_command('collectstatic', **self.command_params) test_file = os.path.join(settings.STATIC_ROOT, "test.txt") test_dir = os.path.join(settings.STATIC_ROOT, "subdir") ...
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_default_permissions(self): call_command('collectstatic', **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / 'test.txt' file_mode = test_file.stat().st_mode ...
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_subclass_of_static_storage(self): call_command('collectstatic', **self.command_params) test_file = os.path.join(settings.STATIC_ROOT, "test.txt") test_dir = os.path.join(settings.STATIC_ROOT, "subdir") ...
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_subclass_of_static_storage(self): call_command('collectstatic', **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / 'test.txt' file_mode = test_file.stat().s...
def default_urlconf(request): var s = link.getElementsByTagName('span')[0]; var uarr = String.fromCharCode(0x25b6); var darr = String.fromCharCode(0x25bc); s.innerHTML = s.innerHTML == uarr ? darr : uarr; return false; } function switchPastebinFriendly(link) { s1 = "Switch to...
def default_urlconf(request): var s = link.getElementsByTagName('span')[0]; var uarr = String.fromCharCode(0x25b6); var darr = String.fromCharCode(0x25bc); s.textContent = s.textContent == uarr ? darr : uarr; return false; } function switchPastebinFriendly(link) { s1 = "Switc...
from django.utils.encoding import python_2_unicode_compatible class Section(models.Model): """ A simple section that links to articles, to test linking to related items
from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Section(models.Model): """ A simple section that links to articles, to test linking to related items
class Section(models.Model): """ name = models.CharField(max_length=100) @property def name_property(self): """
class Section(models.Model): """ name = models.CharField(max_length=100) def __str__(self): return self.name @property def name_property(self): """
def test_list_editable_popups(self): """ list_editable foreign keys have add/change popups. """ s1 = Section.objects.create(name='Test section') Article.objects.create( content='<p>Middle content</p>', date=datetime.datetime(2008, 3, 18, 11, 54, 58), ...
def test_list_editable_popups(self): """ list_editable foreign keys have add/change popups. """ from selenium.webdriver.support.ui import Select s1 = Section.objects.create(name='Test section') Article.objects.create( title='foo', content='<p>Middl...
def test_list_editable_popups(self): self.wait_for_popup() self.selenium.switch_to.window(self.selenium.window_handles[-1]) self.wait_for_text('#content h1', 'Change section') self.selenium.close() self.selenium.switch_to.window(self.selenium.window_handles[0]) # Add pop...
def test_list_editable_popups(self): self.wait_for_popup() self.selenium.switch_to.window(self.selenium.window_handles[-1]) self.wait_for_text('#content h1', 'Change section') name_input = self.selenium.find_element_by_id('id_name') name_input.clear() name_input.send_keys...
WRONGCERT = data_file("XXXnonexisting.pem") BADKEY = data_file("badkey.pem") NOKIACERT = data_file("nokia.pem") def handle_error(prefix):
WRONGCERT = data_file("XXXnonexisting.pem") BADKEY = data_file("badkey.pem") NOKIACERT = data_file("nokia.pem") NULLBYTECERT = data_file("nullbytecert.pem") def handle_error(prefix):
def test_parse_cert(self): ('DNS', 'projects.forum.nokia.com')) ) def test_DER_to_PEM(self): with open(SVN_PYTHON_ORG_ROOT_CERT, 'r') as f: pem = f.read()
def test_parse_cert(self): ('DNS', 'projects.forum.nokia.com')) ) def test_parse_cert_CVE_2013_4073(self): p = ssl._ssl._test_decode_cert(NULLBYTECERT) if support.verbose: sys.stdout.write("\n" + pprint.pformat(p) + "\n") subject...
def fail(cert, hostname): fail(cert, 'foo.a.com') fail(cert, 'bar.foo.com') # Slightly fake real-world example cert = {'notAfter': 'Jun 26 21:41:46 2011 GMT', 'subject': ((('commonName', 'linuxfrz.org'),),),
def fail(cert, hostname): fail(cert, 'foo.a.com') fail(cert, 'bar.foo.com') # NULL bytes are bad, CVE-2013-4073 cert = {'subject': ((('commonName', 'null.python.org\x00example.org'),),)} ok(cert, 'null.python.org\x00example.org') # or raise an error...
def _preprocess_numpy_input(x, data_format, mode): # Returns Preprocessed Numpy array. """ if mode == 'tf': x /= 127.5 x -= 1.
def _preprocess_numpy_input(x, data_format, mode): # Returns Preprocessed Numpy array. """ x = x.astype(K.floatx()) if mode == 'tf': x /= 127.5 x -= 1.
from keras.layers import Input, Lambda def test_preprocess_input(): # Test image batch x = np.random.uniform(0, 255, (2, 10, 10, 3)) assert utils.preprocess_input(x).shape == x.shape out1 = utils.preprocess_input(x, 'channels_last') out2 = utils.preprocess_input(np.transpose(x, (0, 3, 1, 2)), ...
from keras.layers import Input, Lambda def test_preprocess_input(): # Test image batch with float and int image input x = np.random.uniform(0, 255, (2, 10, 10, 3)) xint = x.astype('int32') assert utils.preprocess_input(x).shape == x.shape assert utils.preprocess_input(xint).shape == xint.shape ...
class TestUtil(unittest.TestCase): unified_strdate('2/2/2015 6:47:40 PM', day_first=False), '20150202') self.assertEqual(unified_strdate('25-09-2014'), '20140925') def test_find_xpath_attr(self): testxml = '''<root>
class TestUtil(unittest.TestCase): unified_strdate('2/2/2015 6:47:40 PM', day_first=False), '20150202') self.assertEqual(unified_strdate('25-09-2014'), '20140925') self.assertEqual(unified_strdate('UNKNOWN DATE FORMAT'), None) def test_find_xpath_attr(self): testxml ...
def unified_strdate(date_str, day_first=True): timetuple = email.utils.parsedate_tz(date_str) if timetuple: upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d') return compat_str(upload_date) def determine_ext(url, default_ext='unknown_video'):
def unified_strdate(date_str, day_first=True): timetuple = email.utils.parsedate_tz(date_str) if timetuple: upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d') if upload_date is not None: return compat_str(upload_date) def determine_ext(url, default_ext='unknown_...
class TFOptimizer(Optimizer): @interfaces.legacy_get_updates_support def get_updates(self, loss, params): grads = self.optimizer.compute_gradients(loss, params) self.updates = [K.update_add(self.iterations, 1)] opt_update = self.optimizer.apply_gradients( grads, global_step=...
class TFOptimizer(Optimizer): @interfaces.legacy_get_updates_support def get_updates(self, loss, params): grads = self.optimizer.compute_gradients(loss, var_list=params) self.updates = [K.update_add(self.iterations, 1)] opt_update = self.optimizer.apply_gradients( grads, glo...
def test_tfoptimizer(): optimizer.from_config(None) if __name__ == '__main__': pytest.main([__file__])
def test_tfoptimizer(): optimizer.from_config(None) @pytest.mark.skipif((K.backend() != 'tensorflow'), reason='Requires TensorFlow backend') def test_tfoptimizer_pass_correct_named_params_to_native_tensorflow_optimizer(): from keras import constraints from tensorflow import train ...
class FileSystemStorage(Storage): directory = os.path.dirname(full_path) try: if self.directory_permissions_mode is not None: # os.makedirs applies the global umask, so we reset it, # for consistency with file_permissions_mode behavior. old_uma...
class FileSystemStorage(Storage): directory = os.path.dirname(full_path) try: if self.directory_permissions_mode is not None: # Set the umask because os.makedirs() doesn't apply the "mode" # argument to intermediate-level directories. old_umask...
class FileStoragePermissions(unittest.TestCase): @override_settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765) def test_file_upload_directory_permissions(self): self.storage = FileSystemStorage(self.storage_dir) name = self.storage.save("the_directory/the_file", ContentFile("data")) dir_mo...
class FileStoragePermissions(unittest.TestCase): @override_settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765) def test_file_upload_directory_permissions(self): self.storage = FileSystemStorage(self.storage_dir) name = self.storage.save('the_directory/subdir/the_file', ContentFile('data')) ...
import sys import tempfile import unittest from io import StringIO from unittest import mock from django.conf import settings
import sys import tempfile import unittest from io import StringIO from pathlib import Path from unittest import mock from django.conf import settings
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_permissions(self): call_command('collectstatic', **self.command_params) test_file = os.path.join(settings.STATIC_ROOT, "test.txt") test_dir = os.path.join(settings.STATIC_ROOT, "subdir") file_mod...
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_permissions(self): call_command('collectstatic', **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / 'test.txt' file_mode = test_file.stat().st_mode & 0o777 ...
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_default_permissions(self): call_command('collectstatic', **self.command_params) test_file = os.path.join(settings.STATIC_ROOT, "test.txt") test_dir = os.path.join(settings.STATIC_ROOT, "subdir") ...
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_default_permissions(self): call_command('collectstatic', **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / 'test.txt' file_mode = test_file.stat().st_mode ...
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_subclass_of_static_storage(self): call_command('collectstatic', **self.command_params) test_file = os.path.join(settings.STATIC_ROOT, "test.txt") test_dir = os.path.join(settings.STATIC_ROOT, "subdir") ...
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_subclass_of_static_storage(self): call_command('collectstatic', **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / 'test.txt' file_mode = test_file.stat().s...
class SparseDataFrame(DataFrame): this, other = self.align(other, join="outer", axis=0, level=level, copy=False) new_data = {} for col, series in this.items(): new_data[col] = func(series.values, other.values) fill_value = self._get_op_result_fill_value(other, func)
class SparseDataFrame(DataFrame): this, other = self.align(other, join="outer", axis=0, level=level, copy=False) new_data = {} for col in this.columns: new_data[col] = func(this[col], other) fill_value = self._get_op_result_fill_value(other, func)
class SparseDataFrame(DataFrame): new_data = {} for col in left.columns: new_data[col] = func(left[col], float(right[col])) return self._constructor( new_data,
class SparseDataFrame(DataFrame): new_data = {} for col in left.columns: new_data[col] = func(left[col], right[col]) return self._constructor( new_data,
class TestSparseDataFrameArithmetic: assert isinstance(res, pd.SparseDataFrame) tm.assert_frame_equal(res.to_dense(), df != 0) @pytest.mark.filterwarnings("ignore:Sparse:FutureWarning") @pytest.mark.filterwarnings("ignore:DataFrame.to_sparse:FutureWarning")
class TestSparseDataFrameArithmetic: assert isinstance(res, pd.SparseDataFrame) tm.assert_frame_equal(res.to_dense(), df != 0) def test_add_series_retains_dtype(self): # SparseDataFrame._combine_match_columns used to incorrectly cast # to float d = {0: [2j, 3j], 1: [0, 1]} ...
jwplayer("mediaplayer").setup({"abouttext":"Visit Indie DB","aboutlink":"http:\/ _TEST_CASES = [ ( # https://github.com/rg3/youtube-dl/issues/13919 'float_duration', 'http://unknown/manifest.mpd', [{ 'manifest_url': ...
jwplayer("mediaplayer").setup({"abouttext":"Visit Indie DB","aboutlink":"http:\/ _TEST_CASES = [ ( # https://github.com/rg3/youtube-dl/issues/13919 # Also tests duplicate representation ids, see # https://github.com/rg3/youtube-dl/issues/15111 ...
class InfoExtractor(object): f['url'] = initialization_url f['fragments'].append({location_key(initialization_url): initialization_url}) f['fragments'].extend(representation_ms_info['fragments']) try:...
class InfoExtractor(object): f['url'] = initialization_url f['fragments'].append({location_key(initialization_url): initialization_url}) f['fragments'].extend(representation_ms_info['fragments']) # Ac...
class APIRouter(routing.Router): include_in_schema=route.include_in_schema, name=route.name, ) def get( self,
class APIRouter(routing.Router): include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route...
import stat import tarfile import zipfile class ArchiveException(Exception): """
import stat import tarfile import zipfile from django.core.exceptions import SuspiciousOperation class ArchiveException(Exception): """
class BaseArchive: return False return True def extract(self): raise NotImplementedError('subclasses of BaseArchive must provide an extract() method')
class BaseArchive: return False return True def target_filename(self, to_path, name): target_path = os.path.abspath(to_path) filename = os.path.abspath(os.path.join(target_path, name)) if not filename.startswith(target_path): raise SuspiciousOperation("Ar...
class TarArchive(BaseArchive): name = member.name if leading: name = self.split_leading_dir(name)[1] filename = os.path.join(to_path, name) if member.isdir(): if filename: os.makedirs(filename, exist_ok=True)
class TarArchive(BaseArchive): name = member.name if leading: name = self.split_leading_dir(name)[1] filename = self.target_filename(to_path, name) if member.isdir(): if filename: os.makedirs(filename, exist_ok=True)
class ZipArchive(BaseArchive): info = self._archive.getinfo(name) if leading: name = self.split_leading_dir(name)[1] filename = os.path.join(to_path, name) if filename.endswith(('/', '\\')): # A directory os.makedirs(filenam...
class ZipArchive(BaseArchive): info = self._archive.getinfo(name) if leading: name = self.split_leading_dir(name)[1] if not name: continue filename = self.target_filename(to_path, name) if name.endswith(('/', '\\')): ...
import sys import tempfile import unittest from django.utils import archive
import sys import tempfile import unittest from django.core.exceptions import SuspiciousOperation from django.test import SimpleTestCase from django.utils import archive
class TestArchive(unittest.TestCase): # A file is readable even if permission data is missing. filepath = os.path.join(tmpdir, 'no_permissions') self.assertEqual(os.stat(filepath).st_mode & mask, 0o666 & ~umask)
class TestArchive(unittest.TestCase): # A file is readable even if permission data is missing. filepath = os.path.join(tmpdir, 'no_permissions') self.assertEqual(os.stat(filepath).st_mode & mask, 0o666 & ~umask) class TestArchiveInvalid(SimpleTestCase): def test_ext...
def nanstd(values, axis=None, skipna=True, ddof=1, mask=None): >>> nanops.nanstd(s) 1.0 """ result = np.sqrt(nanvar(values, axis=axis, skipna=skipna, ddof=ddof, mask=mask)) return _wrap_results(result, values.dtype) @disallow("M8") @bottleneck_switch(ddof=1) def nanvar(values, axis=None, skipna=Tr...
def nanstd(values, axis=None, skipna=True, ddof=1, mask=None): >>> nanops.nanstd(s) 1.0 """ orig_dtype = values.dtype values, mask, dtype, dtype_max, fill_value = _get_values(values, skipna, mask=mask) result = np.sqrt(nanvar(values, axis=axis, skipna=skipna, ddof=ddof, mask=mask)) return _...
class Series(base.IndexOpsMixin, generic.NDFrame): If we have an ndarray as a value, then simply perform the operation, otherwise delegate to the object. """ delegate = self._values if axis is not None:
class Series(base.IndexOpsMixin, generic.NDFrame): If we have an ndarray as a value, then simply perform the operation, otherwise delegate to the object. """ delegate = self._values if axis is not None: