buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
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...
from thefuck.rules.php_s import get_new_command, match from thefuck.types import Command def test_match(): assert match(Command('php -s localhost:8000', '')) @pytest.mark.parametrize('command', [
from thefuck.rules.php_s import get_new_command, match from thefuck.types import Command @pytest.mark.parametrize('command', [ Command('php -s localhost:8000', ''), Command('php -t pub -s 0.0.0.0:8080', '') ]) def test_match(command): assert match(command) @pytest.mark.parametrize('command', [
def test_not_match(command): assert not match(command) def test_get_new_command(): new_command = get_new_command(Command('php -s localhost:8000', '')) assert new_command == 'php -S localhost:8000'
def test_not_match(command): assert not match(command) @pytest.mark.parametrize('command, new_command', [ (Command('php -s localhost:8000', ''), 'php -S localhost:8000'), (Command('php -t pub -s 0.0.0.0:8080', ''), 'php -t pub -S 0.0.0.0:8080') ]) def test_get_new_command(command, new_command): assert...
from thefuck.utils import replace_argument, for_app @for_app('php') def match(command): return "php -s" in command.script def get_new_command(command): return replace_argument(command.script, "-s", "-S") requires_output = False
from thefuck.utils import replace_argument, for_app @for_app('php') def match(command): return " -s " in command.script def get_new_command(command): return replace_argument(command.script, "-s", "-S")
def _find_module_utils(module_name, b_module_data, module_path, module_args, tas # FUTURE: smuggle this back as a dict instead of serializing here; the connection plugin may need to modify it module_json = json.dumps(exec_manifest) b_module_data = exec_wrapper.replace(b"$json_raw = ''", b"$json...
def _find_module_utils(module_name, b_module_data, module_path, module_args, tas # FUTURE: smuggle this back as a dict instead of serializing here; the connection plugin may need to modify it module_json = json.dumps(exec_manifest) # delimit the payload JSON from the wrapper to keep sensitive c...
class ActionModule(ActionBase): exec_data = None # WinRM requires a special wrapper to work with environment variables if self._connection.transport == "winrm": pay = self._connection._create_raw_wrapper_payload(script_cmd, ...
class ActionModule(ActionBase): exec_data = None # WinRM requires a special wrapper to work with environment variables if self._connection.transport == "winrm": pay = self._connection._create_raw_wrapper_payload(script_cmd, env_dict) exec_data = to_byt...
import traceback import json import tempfile import subprocess HAVE_KERBEROS = False try:
import traceback import json import tempfile import subprocess import xml.etree.ElementTree as ET HAVE_KERBEROS = False try:
class Connection(ConnectionBase): return (result.status_code, result.std_out, result.std_err) def is_clixml(self, value): return value.startswith(b"#< CLIXML") # hacky way to get just stdout- not always sure of doc framing here, so use with care def parse_clixml_stream(self, clixml_doc, st...
class Connection(ConnectionBase): return (result.status_code, result.std_out, result.std_err) def is_clixml(self, value): return value.startswith(b"#< CLIXML\r\n") # hacky way to get just stdout- not always sure of doc framing here, so use with care def parse_clixml_stream(self, clixml_doc...
import base64 import os import re import shlex from ansible.errors import AnsibleError from ansible.module_utils._text import to_native, to_text
import base64 import os import re import shlex import pkgutil from ansible.errors import AnsibleError from ansible.module_utils._text import to_native, to_text
begin { # stream JSON including become_pw, ps_module_payload, bin_module_payload, become_payload, write_payload_path, preserve directives # exec runspace, capture output, cleanup, return module output # NB: do not adjust the following line- it is replaced when doing non-streamed module output $json_raw...
begin { # stream JSON including become_pw, ps_module_payload, bin_module_payload, become_payload, write_payload_path, preserve directives # exec runspace, capture output, cleanup, return module output # only init and stream in $json_raw if it wasn't set by the enclosing scope if (-not $(Get-Variable "j...
class ShellModule(ShellBase): return self._encode_script(script) def build_module_command(self, env_string, shebang, cmd, arg_path=None): # pipelining bypass if cmd == '': return '-' # non-pipelining
class ShellModule(ShellBase): return self._encode_script(script) def build_module_command(self, env_string, shebang, cmd, arg_path=None): bootstrap_wrapper = pkgutil.get_data("ansible.executor.powershell", "bootstrap_wrapper.ps1") # pipelining bypass if cmd == '': retur...
class ShellModule(ShellBase): cmd_parts = list(map(to_text, cmd_parts)) if shebang and shebang.lower() == '#!powershell': if not self._unquote(cmd_parts[0]).lower().endswith('.ps1'): cmd_parts[0] = '"%s.ps1"' % self._unquote(cmd_parts[0]) cmd_parts.insert(0, '&') ...
class ShellModule(ShellBase): cmd_parts = list(map(to_text, cmd_parts)) if shebang and shebang.lower() == '#!powershell': if not self._unquote(cmd_parts[0]).lower().endswith('.ps1'): # we're running a module via the bootstrap wrapper cmd_parts[0] = '"%s.ps1"' ...
class StackedRNNCells(Layer): output_dim = cell.state_size[0] else: output_dim = cell.state_size input_shape = (input_shape[0], input_shape[1], output_dim) self.built = True def get_config(self):
class StackedRNNCells(Layer): output_dim = cell.state_size[0] else: output_dim = cell.state_size input_shape = (input_shape[0], output_dim) self.built = True def get_config(self):
def test_minimal_rnn_cell_layer(): super(MinimalRNNCell, self).__init__(**kwargs) def build(self, input_shape): self.kernel = self.add_weight(shape=(input_shape[-1], self.units), initializer='uniform', n...
def test_minimal_rnn_cell_layer(): super(MinimalRNNCell, self).__init__(**kwargs) def build(self, input_shape): # no time axis in the input shape passed to RNN cells assert len(input_shape) == 2 self.kernel = self.add_weight(shape=(input_shape[-1], self.units), ...
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): ...
class _Rolling_and_Expanding(_Rolling): # only default unset pairwise = True if pairwise is None else pairwise other = self._shallow_copy(other) window = self._get_window(other) def _get_corr(a, b): a = a.rolling(
class _Rolling_and_Expanding(_Rolling): # only default unset pairwise = True if pairwise is None else pairwise other = self._shallow_copy(other) window = self._get_window(other) if not self.is_freq_type else self.win_freq def _get_corr(a, b): a = a.rolling(
import warnings import pytest from pandas import DataFrame, Series import pandas._testing as tm from pandas.core.algorithms import safe_sort
import warnings import numpy as np import pytest from pandas import DataFrame, Series, date_range import pandas._testing as tm from pandas.core.algorithms import safe_sort
class TestPairwise: for i, result in enumerate(results): if i > 0: self.compare(result, results[0])
class TestPairwise: for i, result in enumerate(results): if i > 0: self.compare(result, results[0]) def test_corr_freq_memory_error(self): # GH 31789 s = Series(range(5), index=date_range("2020", periods=5)) result = s.rolling("12H").corr(s) expec...
class WrappedRequest(object): """ return self.request.meta.get('is_unverifiable', False) # python3 uses request.unverifiable @property def unverifiable(self): return self.is_unverifiable() def get_origin_req_host(self): return urlparse_cached(self.request).hostname ...
class WrappedRequest(object): """ return self.request.meta.get('is_unverifiable', False) def get_origin_req_host(self): return urlparse_cached(self.request).hostname # python3 uses attributes instead of methods @property def full_url(self): return self.get_full_url() ...
class WrappedRequestTest(TestCase): def test_get_full_url(self): self.assertEqual(self.wrapped.get_full_url(), self.request.url) def test_get_host(self): self.assertEqual(self.wrapped.get_host(), urlparse(self.request.url).netloc) def test_get_type(self): self.assertEqual(self.wra...
class WrappedRequestTest(TestCase): def test_get_full_url(self): self.assertEqual(self.wrapped.get_full_url(), self.request.url) self.assertEqual(self.wrapped.full_url, self.request.url) def test_get_host(self): self.assertEqual(self.wrapped.get_host(), urlparse(self.request.url).netlo...
class WrappedRequestTest(TestCase): def test_get_origin_req_host(self): self.assertEqual(self.wrapped.get_origin_req_host(), 'www.example.com') def test_has_header(self): self.assertTrue(self.wrapped.has_header('content-type'))
class WrappedRequestTest(TestCase): def test_get_origin_req_host(self): self.assertEqual(self.wrapped.get_origin_req_host(), 'www.example.com') self.assertEqual(self.wrapped.origin_req_host, 'www.example.com') def test_has_header(self): self.assertTrue(self.wrapped.has_header('content-...
class StaticFileTest(WebTestCase): self.assertEqual(response.headers.get("Content-Length"), "4") self.assertEqual(response.headers.get("Content-Range"), "bytes 22-25/26") def test_static_invalid_range(self): response = self.get_and_head("/static/robots.txt", headers={"Range": "asdf"}) ...
class StaticFileTest(WebTestCase): self.assertEqual(response.headers.get("Content-Length"), "4") self.assertEqual(response.headers.get("Content-Range"), "bytes 22-25/26") def test_static_with_range_neg_past_start(self): response = self.get_and_head( "/static/robots.txt", headers...
class StaticFileTest(WebTestCase): self.assertEqual(response.code, 416) self.assertEqual(response.headers.get("Content-Range"), "bytes */26") def test_static_head(self): response = self.fetch("/static/robots.txt", method="HEAD") self.assertEqual(response.code, 200)
class StaticFileTest(WebTestCase): self.assertEqual(response.code, 416) self.assertEqual(response.headers.get("Content-Range"), "bytes */26") def test_static_unsatisfiable_range_end_less_than_start(self): response = self.get_and_head( "/static/robots.txt", headers={"Range": "byt...
class StaticFileHandler(RequestHandler): size = self.get_content_size() if request_range: start, end = request_range if (start is not None and start >= size) or end == 0: # As per RFC 2616 14.35.1, a range is not satisfiable only: if # the first re...
class StaticFileHandler(RequestHandler): size = self.get_content_size() if request_range: start, end = request_range if start is not None and start < 0: start += size if start < 0: start = 0 if ( star...
r"""{% if request %} at {{ request.path_info|escape }}{% endif %}</title> <h2>Traceback <span class="commands">{% if not is_email %}<a href="#" onclick="return switchPastebinFriendly(this);"> Switch to copy-and-paste view</a></span>{% endif %} </h2> {% autoescape off %} <div id="browserTraceback"> <ul c...
r"""{% if request %} at {{ request.path_info|escape }}{% endif %}</title> <h2>Traceback <span class="commands">{% if not is_email %}<a href="#" onclick="return switchPastebinFriendly(this);"> Switch to copy-and-paste view</a></span>{% endif %} </h2> <div id="browserTraceback"> <ul class="traceback"> ...
r"""{% if request %} at {{ request.path_info|escape }}{% endif %}</title> <tbody> {% for var in frame.vars|dictsort:0 %} <tr> <td>{{ var.0|force_escape }}</td> <td class="code"><pre>{{ var.1 }}</pre></td> </tr> ...
r"""{% if request %} at {{ request.path_info|escape }}{% endif %}</title> <tbody> {% for var in frame.vars|dictsort:0 %} <tr> <td>{{ var.0 }}</td> <td class="code"><pre>{{ var.1 }}</pre></td> </tr> ...
r"""{% if request %} at {{ request.path_info|escape }}{% endif %}</title> {% endfor %} </ul> </div> {% endautoescape %} <form action="http://dpaste.com/" name="pasteform" id="pasteform" method="post"> {% if not is_email %} <div id="pastebinTraceback" class="pastebin">
r"""{% if request %} at {{ request.path_info|escape }}{% endif %}</title> {% endfor %} </ul> </div> <form action="http://dpaste.com/" name="pasteform" id="pasteform" method="post"> {% if not is_email %} <div id="pastebinTraceback" class="pastebin">
In template {{ template_info.name }}, error at line {{ template_info.line }} Traceback:{% for frame in frames %} {% ifchanged frame.exc_cause %}{% if frame.exc_cause %}{% if frame.exc_cause_explicit %} The above exception ({{ frame.exc_cause }}) was the direct cause of the following exception: {% else %} During handli...
In template {{ template_info.name }}, error at line {{ template_info.line }} Traceback:{% for frame in frames %} {% ifchanged frame.exc_cause %}{% if frame.exc_cause %}{% if frame.exc_cause_explicit %} The above exception ({{ frame.exc_cause|force_escape }}) was the direct cause of the following exception: {% else %} ...
error (raise ... from ...) can't be silenced using NOQA. import sys from django.test import RequestFactory, TestCase from django.views.debug import ExceptionReporter
error (raise ... from ...) can't be silenced using NOQA. import sys from django.test import RequestFactory, TestCase from django.utils.safestring import mark_safe from django.views.debug import ExceptionReporter
class Py3ExceptionReporterTests(TestCase): request = self.rf.get('/test_view/') try: try: raise AttributeError('Top level') except AttributeError as explicit: try: raise ValueError('Second exception') from explicit ...
class Py3ExceptionReporterTests(TestCase): request = self.rf.get('/test_view/') try: try: raise AttributeError(mark_safe('<p>Top level</p>')) except AttributeError as explicit: try: raise ValueError('<p>Second exception</p>') fr...
class Py3ExceptionReporterTests(TestCase): html = reporter.get_traceback_html() # Both messages are twice on page -- one rendered as html, # one as plain text (for pastebin) self.assertEqual(2, html.count(explicit_exc.format("Top level"))) self.assertEqual(2, html.count(implicit_...
class Py3ExceptionReporterTests(TestCase): html = reporter.get_traceback_html() # Both messages are twice on page -- one rendered as html, # one as plain text (for pastebin) self.assertEqual(2, html.count(explicit_exc.format('&lt;p&gt;Top level&lt;/p&gt;'))) self.assertEqual(2, h...
class DatetimeTZDtype(PandasExtensionDtype): tz = timezones.tz_standardize(tz) elif tz is not None: raise pytz.UnknownTimeZoneError(tz) elif tz is None: raise TypeError("A 'tz' is required.") self._unit = unit
class DatetimeTZDtype(PandasExtensionDtype): tz = timezones.tz_standardize(tz) elif tz is not None: raise pytz.UnknownTimeZoneError(tz) if tz is None: raise TypeError("A 'tz' is required.") self._unit = unit
class DatetimeTZDtype(PandasExtensionDtype): """ if isinstance(string, str): msg = "Could not construct DatetimeTZDtype from '{}'" try: match = cls._match.match(string) if match: d = match.groupdict() return ...
class DatetimeTZDtype(PandasExtensionDtype): """ if isinstance(string, str): msg = "Could not construct DatetimeTZDtype from '{}'" match = cls._match.match(string) if match: d = match.groupdict() try: return cls(unit...
class TestDatetimeTZDtype(Base): with pytest.raises(TypeError, match="notatz"): DatetimeTZDtype.construct_from_string("datetime64[ns, notatz]") with pytest.raises(TypeError, match="^Could not construct DatetimeTZDtype$"): DatetimeTZDtype.construct_from_string(["datetime64[ns, no...
class TestDatetimeTZDtype(Base): with pytest.raises(TypeError, match="notatz"): DatetimeTZDtype.construct_from_string("datetime64[ns, notatz]") msg = "^Could not construct DatetimeTZDtype" with pytest.raises(TypeError, match=msg): # list instead of string Dat...
ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4') {'like_count': 190, 'dislike_count': 10})) def test_parse_dfxp_time_expr(self): self.assertEqual(parse_dfxp_time_expr(None), 0.0) self.assertEqual(parse_dfxp_time_expr(''), 0.0) self.assertEqual(parse_dfxp...
ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4') {'like_count': 190, 'dislike_count': 10})) def test_parse_dfxp_time_expr(self): self.assertEqual(parse_dfxp_time_expr(None), None) self.assertEqual(parse_dfxp_time_expr(''), None) self.assertEqual(parse_df...
ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4') <p begin="0" end="1">The following line contains Chinese characters and special symbols</p> <p begin="1" end="2">第二行<br/>♪♪</p> <p begin="2" dur="1"><span>Third<br/>Line</span></p> ...
ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4') <p begin="0" end="1">The following line contains Chinese characters and special symbols</p> <p begin="1" end="2">第二行<br/>♪♪</p> <p begin="2" dur="1"><span>Third<br/>Line</span></p> ...
def match_filter_func(filter_str): def parse_dfxp_time_expr(time_expr): if not time_expr: return 0.0 mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr) if mobj:
def match_filter_func(filter_str): def parse_dfxp_time_expr(time_expr): if not time_expr: return mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr) if mobj:
def dfxp2srt(dfxp_data): raise ValueError('Invalid dfxp/TTML subtitle') for para, index in zip(paras, itertools.count(1)): begin_time = parse_dfxp_time_expr(para.attrib['begin']) end_time = parse_dfxp_time_expr(para.attrib.get('end')) if not end_time: end_time = begin_ti...
def dfxp2srt(dfxp_data): raise ValueError('Invalid dfxp/TTML subtitle') for para, index in zip(paras, itertools.count(1)): begin_time = parse_dfxp_time_expr(para.attrib.get('begin')) end_time = parse_dfxp_time_expr(para.attrib.get('end')) dur = parse_dfxp_time_expr(para.attrib.get('...
def rnn(step_function, inputs, initial_states, tiled_mask_t = tf.tile(mask_t, tf.stack([1, tf.shape(output)[1]])) output = tf.where(tiled_mask_t, output, states[0]) new_states = [tf.where(tiled_mask_t, new_states[i], states[i]) for i...
def rnn(step_function, inputs, initial_states, tiled_mask_t = tf.tile(mask_t, tf.stack([1, tf.shape(output)[1]])) output = tf.where(tiled_mask_t, output, states[0]) new_states = [ tf.where(tf.tile(mask_t, tf.stack...
class TestBackend(object): assert_allclose(outputs_list[i - 1], outputs_list[i], atol=1e-05) assert_allclose(state_list[i - 1], state_list[i], atol=1e-05) def test_rnn_no_states(self): # implement a simple RNN without states input_dim = 8
class TestBackend(object): assert_allclose(outputs_list[i - 1], outputs_list[i], atol=1e-05) assert_allclose(state_list[i - 1], state_list[i], atol=1e-05) def test_rnn_additional_states(self): # implement a simple RNN with an additional state # whose shape is differe...
def _has_sneaky_javascript(self, style): return True if 'expression(' in style: return True if '</noscript' in style: # e.g. '<noscript><style><a title="</noscript><img src=x onerror=alert(1)>">' return True
def _has_sneaky_javascript(self, style): return True if 'expression(' in style: return True if '@import' in style: return True if '</noscript' in style: # e.g. '<noscript><style><a title="</noscript><img src=x onerror=alert(1)>">' retur...
def test_sneaky_js_in_math_style(self): b'<math><style>/* deleted */</style></math>', lxml.html.tostring(clean_html(s))) def test_formaction_attribute_in_button_input(self): # The formaction attribute overrides the form's action and should be # treated as a malicious link at...
def test_sneaky_js_in_math_style(self): b'<math><style>/* deleted */</style></math>', lxml.html.tostring(clean_html(s))) def test_sneaky_import_in_style(self): # Prevent "@@importimport" -> "@import" replacement. style_codes = [ "@@importimport(extstyle.css)", ...
class BaseMemcachedTests(BaseCacheTests): Whilst other backends merely warn, memcached should raise for an invalid key. """ msg = expected_warning.replace(key, ':1:%s' % key) with self.assertRaisesMessage(InvalidCacheKey, msg): cache.set(key, 'value')
class BaseMemcachedTests(BaseCacheTests): Whilst other backends merely warn, memcached should raise for an invalid key. """ msg = expected_warning.replace(key, cache.make_key(key)) with self.assertRaisesMessage(InvalidCacheKey, msg): cache.set(key, 'value')
class inherits(object): self.task_to_inherit = task_to_inherit def __call__(self, task_that_inherits): for param_name, param_obj in self.task_to_inherit.get_params(): if not hasattr(task_that_inherits, param_name): setattr(task_that_inherits, param_name, param_obj) ...
class inherits(object): self.task_to_inherit = task_to_inherit def __call__(self, task_that_inherits): # Get all parameter objects from the underlying task for param_name, param_obj in self.task_to_inherit.get_params(): # Check if the parameter exists in the inheriting task ...
class requires(object): def __call__(self, task_that_requires): task_that_requires = self.inherit_decorator(task_that_requires) # Modify task_that_requres by subclassing it and adding methods @task._task_wraps(task_that_requires) class Wrapped(task_that_requires): def r...
class requires(object): def __call__(self, task_that_requires): task_that_requires = self.inherit_decorator(task_that_requires) # Modify task_that_requres by adding methods def requires(_self): return _self.clone_parent() task_that_requires.requires = requires r...
from helpers import LuigiTestCase, RunOnceTask import luigi import luigi.task from luigi.util import requires class BasicsTest(LuigiTestCase): def test_task_ids_using_requries(self): class ParentTask(luigi.Task): my_param = luigi.Parameter()
from helpers import LuigiTestCase, RunOnceTask import luigi import luigi.task from luigi.util import inherits, requires class BasicsTest(LuigiTestCase): # following tests using inherits decorator def test_task_ids_using_inherits(self): class ParentTask(luigi.Task): my_param = luigi.Parame...
class BasicsTest(LuigiTestCase): ParentTask = self._setup_parent_and_child() self.assertTrue(self.run_locally_split('ParentTask --my-parameter actuallyset')) self.assertEqual(ParentTask.class_variable, 'actuallyset')
class BasicsTest(LuigiTestCase): ParentTask = self._setup_parent_and_child() self.assertTrue(self.run_locally_split('ParentTask --my-parameter actuallyset')) self.assertEqual(ParentTask.class_variable, 'actuallyset') def _setup_requires_inheritence(self): class RequiredTask(luigi.Ta...
class HttpRequest(object): """Return the HTTP host using the environment or request headers.""" host = self._get_raw_host() # There is no hostname validation when DEBUG=True if settings.DEBUG: return host domain, port = split_domain_port(host) if domain and ...
class HttpRequest(object): """Return the HTTP host using the environment or request headers.""" host = self._get_raw_host() # Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True. allowed_hosts = settings.ALLOWED_HOSTS if settings.DEBUG and not allowed_hosts: ...
class CsrfViewMiddlewareTest(SimpleTestCase): self.assertEqual(len(csrf_cookie.value), CSRF_TOKEN_LENGTH) self._check_token_present(resp, csrf_id=csrf_cookie.value) @override_settings(DEBUG=True) def test_https_bad_referer(self): """ Test that a POST HTTPS request with a bad ref...
class CsrfViewMiddlewareTest(SimpleTestCase): self.assertEqual(len(csrf_cookie.value), CSRF_TOKEN_LENGTH) self._check_token_present(resp, csrf_id=csrf_cookie.value) @override_settings(DEBUG=True, ALLOWED_HOSTS=['www.example.com']) def test_https_bad_referer(self): """ Test that ...
class HostValidationTests(SimpleTestCase): self.assertEqual(request.get_port(), '8080') @override_settings(DEBUG=True, ALLOWED_HOSTS=[]) def test_host_validation_disabled_in_debug_mode(self): """If ALLOWED_HOSTS is empty and DEBUG is True, all hosts pass.""" request = HttpRequest() ...
class HostValidationTests(SimpleTestCase): self.assertEqual(request.get_port(), '8080') @override_settings(DEBUG=True, ALLOWED_HOSTS=[]) def test_host_validation_in_debug_mode(self): """ If ALLOWED_HOSTS is empty and DEBUG is True, variants of localhost are allowed. """ ...
"""Basic WSGI Application object for REST server.""" import re import logging from base64 import b64decode
"""Basic WSGI Application object for REST server.""" import re import hmac import logging from base64 import b64decode
class Middleware: credentials = b64decode(request.auth[6:]).decode('utf-8') username, password = credentials.split(':', 1) if (username == config.webservice.admin_user and password == config.webservice.admin_pass): authorized = True if not ...
class Middleware: credentials = b64decode(request.auth[6:]).decode('utf-8') username, password = credentials.split(':', 1) if (username == config.webservice.admin_user and hmac.compare_digest( password, config.webservice.admin_pass)): ...
from thefuck.types import Command @pytest.fixture def output(branch_name): return "fatal: A branch named '{}' already exists.".format(branch_name) @pytest.fixture
from thefuck.types import Command @pytest.fixture def output(src_branch_name): return "fatal: A branch named '{}' already exists.".format(src_branch_name) @pytest.fixture
def new_command(branch_name): 'git branch -D {0} && git checkout -b {0}', 'git checkout {0}']] @pytest.mark.parametrize('script, branch_name', [ ('git branch foo', 'foo'), ('git checkout bar', 'bar')]) def test_match(output, script, branch_name): assert match(Command(script, output)) @pytest.mark.pa...
def new_command(branch_name): 'git branch -D {0} && git checkout -b {0}', 'git checkout {0}']] @pytest.mark.parametrize('script, src_branch_name, branch_name', [ ('git branch foo', 'foo', 'foo'), ('git checkout bar', 'bar', 'bar'), ('git checkout -b "let\'s-push-this"', '"let\'s-push-this"', '"let...
from thefuck.utils import eager @git_support def match(command): return ("fatal: A branch named '" in command.output and " already exists." in command.output) @git_support @eager def get_new_command(command): branch_name = re.findall( r"fatal: A branch named '([^']*)' already exists.", com...
from thefuck.utils import eager @git_support def match(command): return ("fatal: A branch named '" in command.output and "' already exists." in command.output) @git_support @eager def get_new_command(command): branch_name = re.findall( r"fatal: A branch named '(.+)' already exists.", comma...
class TestUtil(unittest.TestCase): def test_str_to_int(self): self.assertEqual(str_to_int('123,456'), 123456) self.assertEqual(str_to_int('123.456'), 123456) def test_url_basename(self): self.assertEqual(url_basename('http://foo.de/'), '')
class TestUtil(unittest.TestCase): def test_str_to_int(self): self.assertEqual(str_to_int('123,456'), 123456) self.assertEqual(str_to_int('123.456'), 123456) self.assertEqual(str_to_int(523), 523) def test_url_basename(self): self.assertEqual(url_basename('http://foo.de/'), '')
def str_or_none(v, default=None): def str_to_int(int_str): """ A more relaxed version of int_or_none """ if int_str is None: return None int_str = re.sub(r'[,\.\+]', '', int_str) return int(int_str)
def str_or_none(v, default=None): def str_to_int(int_str): """ A more relaxed version of int_or_none """ if not isinstance(int_str, compat_str): return int_str int_str = re.sub(r'[,\.\+]', '', int_str) return int(int_str)
class IntervalArray(IntervalMixin, ExtensionArray): msg = f"'value' should be an interval type, got {type(value)} instead." raise TypeError(msg) from err key = check_array_indexer(self, key) # Need to ensure that left and right are updated atomically, so we're # ...
class IntervalArray(IntervalMixin, ExtensionArray): msg = f"'value' should be an interval type, got {type(value)} instead." raise TypeError(msg) from err if needs_float_conversion: raise ValueError("Cannot set float NaN to integer-backed IntervalArray") key ...
class TestSetitem: def test_set_na(self, left_right_dtypes): left, right = left_right_dtypes result = IntervalArray.from_arrays(left, right) result[0] = np.nan expected_left = Index([left._na_value] + list(left[1:]))
class TestSetitem: def test_set_na(self, left_right_dtypes): left, right = left_right_dtypes result = IntervalArray.from_arrays(left, right) if result.dtype.subtype.kind in ["i", "u"]: msg = "Cannot set float NaN to integer-backed IntervalArray" with pytest.raises(Va...
def test_arrow_array_missing(): import pyarrow as pa from pandas.core.arrays._arrow_utils import ArrowIntervalType arr = IntervalArray.from_breaks([0, 1, 2, 3]) arr[1] = None result = pa.array(arr)
def test_arrow_array_missing(): import pyarrow as pa from pandas.core.arrays._arrow_utils import ArrowIntervalType arr = IntervalArray.from_breaks([0.0, 1.0, 2.0, 3.0]) arr[1] = None result = pa.array(arr)
def test_arrow_array_missing(): @pyarrow_skip @pytest.mark.parametrize( "breaks", [[0, 1, 2, 3], pd.date_range("2017", periods=4, freq="D")], ids=["int", "datetime64[ns]"], ) def test_arrow_table_roundtrip(breaks): import pyarrow as pa
def test_arrow_array_missing(): @pyarrow_skip @pytest.mark.parametrize( "breaks", [[0.0, 1.0, 2.0, 3.0], pd.date_range("2017", periods=4, freq="D")], ids=["float", "datetime64[ns]"], ) def test_arrow_table_roundtrip(breaks): import pyarrow as pa
from itertools import product import numpy as np import pytest import pandas as pd import pandas._testing as tm
from itertools import product import numpy as np import pytest from pandas.core.dtypes.common import is_interval_dtype import pandas as pd import pandas._testing as tm
class TestSeriesConvertDtypes: # Test that it is a copy copy = series.copy(deep=True) ns[ns.notna()] = np.nan # Make sure original not changed tm.assert_series_equal(series, copy)
class TestSeriesConvertDtypes: # Test that it is a copy copy = series.copy(deep=True) if is_interval_dtype(ns.dtype) and ns.dtype.subtype.kind in ["i", "u"]: msg = "Cannot set float NaN to integer-backed IntervalArray" with pytest.raises(ValueError, match=msg): ...
# -*- coding: utf-8 -*- # The pam components have been modified to be salty and have been taken from # the pam module under this licence: # (c) 2007 Chris AtLee <chris@atlee.ca>
# The pam components have been modified to be salty and have been taken from # the pam module under this licence: # (c) 2007 Chris AtLee <chris@atlee.ca>
authenticated against. This defaults to `login` """ # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging from ctypes import (
authenticated against. This defaults to `login` """ import logging from ctypes import (
from ctypes import ( ) from ctypes.util import find_library # Import Salt libs import salt.utils.user # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) try:
from ctypes import ( ) from ctypes.util import find_library import salt.utils.user log = logging.getLogger(__name__) try:
class PamMessage(Structure): ] def __repr__(self): return "<PamMessage {0} '{1}'>".format(self.msg_style, self.msg) class PamResponse(Structure):
class PamMessage(Structure): ] def __repr__(self): return "<PamMessage {} '{}'>".format(self.msg_style, self.msg) class PamResponse(Structure):
class PamResponse(Structure): ] def __repr__(self): return "<PamResponse {0} '{1}'>".format(self.resp_retcode, self.resp) CONV_FUNC = CFUNCTYPE(
class PamResponse(Structure): ] def __repr__(self): return "<PamResponse {} '{}'>".format(self.resp_retcode, self.resp) CONV_FUNC = CFUNCTYPE(
def authenticate(username, password): """ service = __opts__.get("auth.pam.service", "login") if isinstance(username, six.text_type): username = username.encode(__salt_system_encoding__) if isinstance(password, six.text_type): password = password.encode(__salt_system_encoding__) if ...
def authenticate(username, password): """ service = __opts__.get("auth.pam.service", "login") if isinstance(username, str): username = username.encode(__salt_system_encoding__) if isinstance(password, str): password = password.encode(__salt_system_encoding__) if isinstance(service, ...
def authenticate(username, password): retval = PAM_AUTHENTICATE(handle, 0) if retval == 0: PAM_ACCT_MGMT(handle, 0) PAM_END(handle, 0) return retval == 0
def authenticate(username, password): retval = PAM_AUTHENTICATE(handle, 0) if retval == 0: retval = PAM_ACCT_MGMT(handle, 0) PAM_END(handle, 0) return retval == 0
Genshi Renderer for Salt """ # pylint: disable=import-error,no-name-in-module try: from genshi.template import MarkupTemplate from genshi.template import NewTextTemplate from genshi.template import OldTextTemplate HAS_LIBS = True except ImportError: HAS_LIBS = False # pylint: enable=import-error,n...
Genshi Renderer for Salt """ try: from genshi.template import MarkupTemplate # pylint: disable=no-name-in-module from genshi.template import NewTextTemplate # pylint: disable=no-name-in-module from genshi.template import OldTextTemplate # pylint: disable=no-name-in-module HAS_LIBS = True except Imp...
def get_next_comment(): def _get_insert_token(token): """Returns either a whitespace or the line breaks from token.""" # See issue484 why line breaks should be preserved. m = re.search(r'((\r\n|\r|\n)+) *$', token.value) if m is not None: return sq...
def get_next_comment(): def _get_insert_token(token): """Returns either a whitespace or the line breaks from token.""" # See issue484 why line breaks should be preserved. # Note: The actual value for a line break is replaced by \n # in SerializerUnicode which will...
def test_strip_comments_multi(self): res = sqlparse.format(sql, strip_comments=True) assert res == 'select (select 2)' def test_strip_ws(self): f = lambda sql: sqlparse.format(sql, strip_whitespace=True) s = 'select\n* from foo\n\twhere ( 1 = 2 )\n'
def test_strip_comments_multi(self): res = sqlparse.format(sql, strip_comments=True) assert res == 'select (select 2)' def test_strip_comments_preserves_linebreak(self): sql = 'select * -- a comment\r\nfrom foo' res = sqlparse.format(sql, strip_comments=True) assert res == '...
class Categorical(ExtensionArray, PandasObject): code_values = code_values[null_mask | (code_values >= 0)] return algorithms.isin(self.codes, code_values) # The Series.cat accessor
class Categorical(ExtensionArray, PandasObject): code_values = code_values[null_mask | (code_values >= 0)] return algorithms.isin(self.codes, code_values) def replace(self, to_replace, value, inplace: bool = False): """ Replaces all instances of one value with another Param...
class CategoricalBlock(ExtensionBlock): ) return result # ----------------------------------------------------------------- # Constructor Helpers
class CategoricalBlock(ExtensionBlock): ) return result def replace( self, to_replace, value, inplace: bool = False, filter=None, regex: bool = False, convert: bool = True, ): inplace = validate_bool_kwarg(inplace, "inplace") ...
def test_isin_cats(): tm.assert_numpy_array_equal(expected, result) @pytest.mark.parametrize("empty", [[], pd.Series(), np.array([])]) def test_isin_empty(empty): s = pd.Categorical(["a", "b"])
def test_isin_cats(): tm.assert_numpy_array_equal(expected, result) @pytest.mark.parametrize( "to_replace, value, result", [("b", "c", ["a", "c"]), ("c", "d", ["a", "b"]), ("b", None, ["a", None])], ) def test_replace(to_replace, value, result): # GH 26988 cat = pd.Categorical(["a", "b"]) expe...
class TestDataFrameReplace: expected = DataFrame(expected) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "df, to_replace, exp", [
class TestDataFrameReplace: expected = DataFrame(expected) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "replace_dict, final_data", [({"a": 1, "b": 1}, [[3, 3], [2, 2]]), ({"a": 1, "b": 2}, [[3, 1], [2, 3]])], ) def test_categorical_replace_with_dict(sel...
class TestSeriesReplace: expected = pd.Series(numeric) tm.assert_series_equal(expected, result, check_dtype=False) def test_replace_with_no_overflowerror(self): # GH 25616 # casts to object without Exception from OverflowError
class TestSeriesReplace: expected = pd.Series(numeric) tm.assert_series_equal(expected, result, check_dtype=False) def test_replace_categorical_single(self): # GH 26988 dti = pd.date_range("2016-01-01", periods=3, tz="US/Pacific") s = pd.Series(dti) c = s.astype("cat...
def get_catalog(self, user_id, tenant_id, metadata=None): class ServiceController(wsgi.Application): def __init__(self): self.catalog_api = Manager() super(ServiceController, self).__init__() # CRUD extensions # NOTE(termie): this OS-KSADM stuff is not very consistent def get_services(s...
def get_catalog(self, user_id, tenant_id, metadata=None): class ServiceController(wsgi.Application): def __init__(self): self.catalog_api = Manager() self.identity_api = identity.Manager() self.policy_api = policy.Manager() self.token_api = token.Manager() super(ServiceContro...
import httplib import json from lxml import etree import nose.exc
import httplib import json import uuid from lxml import etree import nose.exc
def assertValidMultipleChoiceResponse(self, r): def assertValidVersionResponse(self, r): self.assertValidVersion(r.body.get('version')) class XmlTestCase(RestfulTestCase, CoreApiTests): xmlns = 'http://docs.openstack.org/identity/api/v2.0'
def assertValidMultipleChoiceResponse(self, r): def assertValidVersionResponse(self, r): self.assertValidVersion(r.body.get('version')) def test_service_crud_requires_auth(self): """Service CRUD should 401 without an X-Auth-Token (bug 1006822).""" # values here don't matter because we s...
import stat from django.http import ( FileResponse, Http404, HttpResponse, HttpResponseNotModified, HttpResponseRedirect, ) from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils.http import http_date, parse_http_date from django.utils.six.moves.urllib.parse import unquote ...
import stat from django.http import ( FileResponse, Http404, HttpResponse, HttpResponseNotModified, ) from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils._os import safe_join from django.utils.http import http_date, parse_http_date from django.utils.six.moves.urllib.parse im...
def serve(request, path, document_root=None, show_indexes=False): but if you'd like to override it, you can create a template called ``static/directory_index.html``. """ path = posixpath.normpath(unquote(path)) path = path.lstrip('/') newpath = '' for part in path.split('/'): if not ...
def serve(request, path, document_root=None, show_indexes=False): but if you'd like to override it, you can create a template called ``static/directory_index.html``. """ path = posixpath.normpath(unquote(path)).lstrip('/') fullpath = safe_join(document_root, path) if os.path.isdir(fullpath): ...
class StaticTests(SimpleTestCase): def test_index(self): response = self.client.get('/%s/' % self.prefix) self.assertContains(response, 'Index of /') class StaticHelperTest(StaticTests):
class StaticTests(SimpleTestCase): def test_index(self): response = self.client.get('/%s/' % self.prefix) self.assertContains(response, 'Index of ./') class StaticHelperTest(StaticTests):
class TupleParameter(ListParameter): try: # loop required to parse tuple of tuples return tuple(tuple(x) for x in json.loads(x, object_pairs_hook=_FrozenOrderedDict)) except ValueError: return literal_eval(x) # if this causes an error, let that error be raised. cla...
class TupleParameter(ListParameter): try: # loop required to parse tuple of tuples return tuple(tuple(x) for x in json.loads(x, object_pairs_hook=_FrozenOrderedDict)) except (ValueError, TypeError): return tuple(literal_eval(x)) # if this causes an error, let that er...
class TestTaskParameter(LuigiTestCase): self.assertTrue(self.run_locally(['MainTask'])) class NewStyleParameters822Test(LuigiTestCase): """ I bet these tests created at 2015-03-08 are reduntant by now (Oct 2015).
class TestTaskParameter(LuigiTestCase): self.assertTrue(self.run_locally(['MainTask'])) class TestSerializeTupleParameter(LuigiTestCase): def testSerialize(self): the_tuple = (1, 2, 3) self.assertEqual(luigi.TupleParameter().parse(luigi.TupleParameter().serialize(the_tuple)), the_tuple) ...
from .common import ( is_unsigned_integer_dtype, pandas_dtype, ) from .dtypes import DatetimeTZDtype, ExtensionDtype, PeriodDtype from .generic import ( ABCDataFrame, ABCDatetimeArray,
from .common import ( is_unsigned_integer_dtype, pandas_dtype, ) from .dtypes import DatetimeTZDtype, ExtensionDtype, IntervalDtype, PeriodDtype from .generic import ( ABCDataFrame, ABCDatetimeArray,
def infer_dtype_from_scalar(val, pandas_dtype: bool = False): if lib.is_period(val): dtype = PeriodDtype(freq=val.freq) val = val.ordinal return dtype, val
def infer_dtype_from_scalar(val, pandas_dtype: bool = False): if lib.is_period(val): dtype = PeriodDtype(freq=val.freq) val = val.ordinal elif lib.is_interval(val): subtype = infer_dtype_from_scalar(val.left, pandas_dtype=True)[0] dtype = IntervalDtype(sub...
from pandas.core.dtypes.cast import ( ) from pandas.core.dtypes.common import is_dtype_equal from pandas import Categorical, Period, Series, Timedelta, Timestamp, date_range import pandas.util.testing as tm
from pandas.core.dtypes.cast import ( ) from pandas.core.dtypes.common import is_dtype_equal from pandas import ( Categorical, Interval, Period, Series, Timedelta, Timestamp, date_range, ) import pandas.util.testing as tm
def test_infer_from_scalar_tz(tz, pandas_dtype): assert val == exp_val def test_infer_dtype_from_scalar_errors(): msg = "invalid ndarray passed to infer_dtype_from_scalar"
def test_infer_from_scalar_tz(tz, pandas_dtype): assert val == exp_val @pytest.mark.parametrize( "left, right, subtype", [ (0, 1, "int64"), (0.0, 1.0, "float64"), (Timestamp(0), Timestamp(1), "datetime64[ns]"), (Timestamp(0, tz="UTC"), Timestamp(1, tz="UTC"), "datetime64[ns...
class DataFrameGroupBy(GroupBy): result = type(block.values)._from_sequence( result.ravel(), dtype=block.values.dtype ) except ValueError: # reshape to be valid for non-Extension Block ...
class DataFrameGroupBy(GroupBy): result = type(block.values)._from_sequence( result.ravel(), dtype=block.values.dtype ) except (ValueError, TypeError): # reshape to be valid for non-Extension Block ...