buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
def _connect_tls_proxy(self, hostname, conn): self.ca_cert_dir, self.ca_cert_data, ) # If no cert was provided, use only the default options for server # certificate validation
def _connect_tls_proxy(self, hostname, conn): self.ca_cert_dir, self.ca_cert_data, ) # By default urllib3's SSLContext disables `check_hostname` and uses # a custom check. For proxies we're good with relying on the default # verification. ssl_context.check...
def no_san_server(tmp_path_factory): yield cfg @pytest.fixture def ip_san_server(tmp_path_factory): tmpdir = tmp_path_factory.mktemp("certs")
def no_san_server(tmp_path_factory): yield cfg @pytest.fixture def no_localhost_san_server(tmp_path_factory): tmpdir = tmp_path_factory.mktemp("certs") ca = trustme.CA() # non localhost common name server_cert = ca.issue_cert(u"example.com") with run_server_in_thread("https", "localhost",...
def test_basic_ipv6_proxy(self): r = http.request("GET", "%s/" % self.https_url) assert r.status == 200
def test_basic_ipv6_proxy(self): r = http.request("GET", "%s/" % self.https_url) assert r.status == 200 class TestHTTPSProxyVerification: @onlyPy3 def test_https_proxy_hostname_verification(self, no_localhost_san_server): bad_server = no_localhost_san_server bad_proxy_...
class TimedeltaIndex( "represent unambiguous timedelta values durations." ) if isinstance(data, TimedeltaArray): if copy: data = data.copy() return cls._simple_new(data, name=name, freq=freq)
class TimedeltaIndex( "represent unambiguous timedelta values durations." ) if isinstance(data, TimedeltaArray) and freq is None: if copy: data = data.copy() return cls._simple_new(data, name=name, freq=freq)
class TestTimedeltaIndex: # GH#23789 TimedeltaArray(tdi, freq="D") def test_dt64_data_invalid(self): # GH#23539 # passing tz-aware DatetimeIndex raises, naive or ndarray[datetime64]
class TestTimedeltaIndex: # GH#23789 TimedeltaArray(tdi, freq="D") with pytest.raises(ValueError, match=msg): TimedeltaIndex(tdi._data, freq="D") with pytest.raises(ValueError, match=msg): TimedeltaArray(tdi._data, freq="D") def test_dt64_data_inval...
def load(klass): for path in klass.CONF_PATHS: if os.path.exists(path): with open(path, 'r') as conf: config.configure(yaml.load(conf)) return config def configure(self, conf={}):
def load(klass): for path in klass.CONF_PATHS: if os.path.exists(path): with open(path, 'r') as conf: config.configure(yaml.safe_load(conf)) return config def configure(self, conf={}):
# tests.conf_tests # Testing the configuration module for Confire # # Author: Benjamin Bengfort <benjamin@bengfort.com>
# tests.test_conf # Testing the configuration module for Confire # # Author: Benjamin Bengfort <benjamin@bengfort.com>
# Copyright (C) 2014 Bengfort.com # For license information, see LICENSE.txt # # ID: conf_tests.py [] benjamin@bengfort.com $ """ Testing the configuration module for Confire
# Copyright (C) 2014 Bengfort.com # For license information, see LICENSE.txt # # ID: test_conf.py [] benjamin@bengfort.com $ """ Testing the configuration module for Confire
# tests.descriptors_tests # Implements a base SettingsDescriptor for advanced configurations # # Author: Benjamin Bengfort <benjamin@bengfort.com>
# tests.test_descriptors # Implements a base SettingsDescriptor for advanced configurations # # Author: Benjamin Bengfort <benjamin@bengfort.com>
# Copyright (C) 2015 Bengfort.com # For license information, see LICENSE.txt # # ID: descriptors_tests.py [] benjamin@bengfort.com $ """ Implements a base SettingsDescriptor for advanced configurations
# Copyright (C) 2015 Bengfort.com # For license information, see LICENSE.txt # # ID: test_descriptors.py [] benjamin@bengfort.com $ """ Implements a base SettingsDescriptor for advanced configurations
# tests.environ_tests # Tests the environment configuration ability # # Author: Benjamin Bengfort <benjamin@bengfort.com>
# tests.test_environ # Tests the environment configuration ability # # Author: Benjamin Bengfort <benjamin@bengfort.com>
# Copyright (C) 2014 Bengfort.com # For license information, see LICENSE.txt # # ID: environ_tests.py [] benjamin@bengfort.com $ """ Tests the environment configuration ability
# Copyright (C) 2014 Bengfort.com # For license information, see LICENSE.txt # # ID: test_environ.py [] benjamin@bengfort.com $ """ Tests the environment configuration ability
# tests.paths_tests # Testing the paths descriptor # # Author: Benjamin Bengfort <benjamin@bengfort.com>
# tests.test_paths # Testing the paths descriptor # # Author: Benjamin Bengfort <benjamin@bengfort.com>
# Copyright (C) 2014 Bengfort.com # For license information, see LICENSE.txt # # ID: paths_tests.py [] benjamin@bengfort.com $ """ Testing the paths descriptor
# Copyright (C) 2014 Bengfort.com # For license information, see LICENSE.txt # # ID: test_paths.py [] benjamin@bengfort.com $ """ Testing the paths descriptor
from youtube_dl.utils import ( parse_iso8601, strip_jsonp, uppercase_escape, )
from youtube_dl.utils import ( parse_iso8601, strip_jsonp, uppercase_escape, limit_length, )
class TestUtil(unittest.TestCase): self.assertEqual(uppercase_escape('aä'), 'aä') self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐') if __name__ == '__main__': unittest.main()
class TestUtil(unittest.TestCase): self.assertEqual(uppercase_escape('aä'), 'aä') self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐') def test_limit_length(self): self.assertEqual(limit_length(None, 12), None) self.assertEqual(limit_length('foo', 12), 'foo') self.assertT...
from ..utils import ( compat_urllib_parse, compat_urllib_request, urlencode_postdata, ExtractorError, )
from ..utils import ( compat_urllib_parse, compat_urllib_request, urlencode_postdata, ExtractorError, limit_length, )
class FacebookIE(InfoExtractor): 'duration': 38, 'title': 'Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam fin...', } }, { 'url': 'https://www.facebook.com/video.php?v=10204634152394104', 'only_matching': True,
class FacebookIE(InfoExtractor): 'duration': 38, 'title': 'Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam fin...', } }, { 'note': 'Video without discernible title', 'url': 'https://www.facebook.com/video.php?v=274175099429670', 'i...
class FacebookIE(InfoExtractor): video_title = self._html_search_regex( r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>', webpage, 'alternative title', default=None) if len(video_title) > 80 + 3: ...
class FacebookIE(InfoExtractor): video_title = self._html_search_regex( r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>', webpage, 'alternative title', default=None) video_title = limit_length(video_title, 8...
except AttributeError: if ret: raise subprocess.CalledProcessError(ret, p.args, output=output) return output
except AttributeError: if ret: raise subprocess.CalledProcessError(ret, p.args, output=output) return output def limit_length(s, length): """ Add ellipses to overly long strings """ if s is None: return None ELLIPSES = '...' if len(s) > length: return s[:len...
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...
class Connection(ConnectionBase): # starting a new interpreter to save on time b_command = base64.b64decode(cmd.split(" ")[-1]) script = to_text(b_command, 'utf-16-le') display.vvv("PSRP: EXEC %s" % script, host=self._psrp_host) else: # in other cases ...
class Connection(ConnectionBase): # starting a new interpreter to save on time b_command = base64.b64decode(cmd.split(" ")[-1]) script = to_text(b_command, 'utf-16-le') in_data = to_text(in_data, errors="surrogate_or_strict", nonstring="passthru") display.vvv(...
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_text
import base64 import os import re import shlex import pkgutil from ansible.errors import AnsibleError from ansible.module_utils._text import 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...
namespace AnsibleBecome $become_exec_wrapper = { chcp.com 65001 > $null $ProgressPreference = "SilentlyContinue" $exec_wrapper_str = [System.Console]::In.ReadToEnd() $exec_wrapper = [ScriptBlock]::Create($exec_wrapper_str) &$exec_wrapper } $exec_wrapper = {
namespace AnsibleBecome $become_exec_wrapper = { chcp.com 65001 > $null $ProgressPreference = "SilentlyContinue" $raw = [System.Console]::In.ReadToEnd() $split_parts = $raw.Split(@("`0`0`0`0"), 0) If (-not $split_parts.Length -eq 2) { throw "invalid payload" } $json_raw = $split_parts[1] &([...
$exec_wrapper = { # 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. Do not change this as it is set become before being passed to the # become process. $json_ra...
$exec_wrapper = { # 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. Do not change this as it is set become before being passed to the # become process. if (-no...
Function Run($payload) { # wrapper which calls our read wrapper passed through stdin. Cannot use 'powershell -' as # the $ErrorActionPreference is always set to Stop and cannot be changed $payload_string = $payload | ConvertTo-Json -Depth 99 -Compress $exec_wrapper = $exec_wrapper.ToString().Replace('$j...
Function Run($payload) { # wrapper which calls our read wrapper passed through stdin. Cannot use 'powershell -' as # the $ErrorActionPreference is always set to Stop and cannot be changed $payload_string = $payload | ConvertTo-Json -Depth 99 -Compress $exec_wrapper = $exec_wrapper.ToString() + "`0`0`0`0...
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"' ...
from itertools import cycle as itertools_cycle, groupby from django.conf import settings from django.utils import timezone from django.utils.html import conditional_escape, format_html from django.utils.lorem_ipsum import paragraphs, words from django.utils.safestring import mark_safe
from itertools import cycle as itertools_cycle, groupby from django.conf import settings from django.utils import timezone from django.utils.html import conditional_escape, escape, format_html from django.utils.lorem_ipsum import paragraphs, words from django.utils.safestring import mark_safe
class CycleNode(Node): class DebugNode(Node): def render(self, context): from pprint import pformat output = [pformat(val) for val in context] output.append('\n\n') output.append(pformat(sys.modules)) return ''.join(output)
class CycleNode(Node): class DebugNode(Node): def render(self, context): if not settings.DEBUG: return '' from pprint import pformat output = [escape(pformat(val)) for val in context] output.append('\n\n') output.append(escape(pformat(sys.modules))) retu...
import sys from django.contrib.auth.models import Group from django.template import Context, Engine, TemplateSyntaxError from django.template.base import UNKNOWN_SOURCE from django.test import SimpleTestCase, override_settings
import sys from django.template import Context, Engine, TemplateSyntaxError from django.template.base import UNKNOWN_SOURCE from django.test import SimpleTestCase, override_settings
class TemplateTests(SimpleTestCase): with self.assertRaises(NoReverseMatch): t.render(Context()) def test_debug_tag_non_ascii(self): """ #23060 -- Test non-ASCII model representation in debug output. """ group = Group(name="清風") c1 = Context({"objs": [gro...
class TemplateTests(SimpleTestCase): with self.assertRaises(NoReverseMatch): t.render(Context()) def test_extends_generic_template(self): """ #24338 -- Allow extending django.template.backends.django.Template
def read_user_choice(var_name, options): )) user_choice = click.prompt( prompt, type=click.Choice(choices), default=default ) return choice_map[user_choice]
def read_user_choice(var_name, options): )) user_choice = click.prompt( prompt, type=click.Choice(choices), default=default, show_choices=False ) return choice_map[user_choice]
def test_click_invocation(mocker, user_choice, expected_value): prompt.assert_called_once_with( EXPECTED_PROMPT, type=click.Choice(OPTIONS), default='1' )
def test_click_invocation(mocker, user_choice, expected_value): prompt.assert_called_once_with( EXPECTED_PROMPT, type=click.Choice(OPTIONS), default='1', show_choices=False )
def get_grouper( return False try: return gpr is obj[gpr.name] except (KeyError, IndexError): return False for i, (gpr, level) in enumerate(zip(keys, levels)):
def get_grouper( return False try: return gpr is obj[gpr.name] except (KeyError, IndexError, ValueError): # TODO: ValueError: Given date string not likely a datetime. # should be KeyError? return False for i, (gpr, level) in enumerate(zip(...
import numpy as np import pytest from pandas import DataFrame, Index, Series import pandas._testing as tm
import numpy as np import pytest from pandas import DataFrame, Index, PeriodIndex, Series import pandas._testing as tm
def test_size_groupby_all_null(): result = df.groupby("A").size() expected = Series(dtype="int64", index=Index([], name="A")) tm.assert_series_equal(result, expected)
def test_size_groupby_all_null(): result = df.groupby("A").size() expected = Series(dtype="int64", index=Index([], name="A")) tm.assert_series_equal(result, expected) def test_size_period_index(): # https://github.com/pandas-dev/pandas/issues/34010 ser = Series([1], index=PeriodIndex(["2000"], nam...
class ErrorInAsyncOpenHandler(TestWebSocketHandler): raise Exception("boom") class WebSocketBaseTestCase(AsyncHTTPTestCase): @gen.coroutine def ws_connect(self, path, **kwargs):
class ErrorInAsyncOpenHandler(TestWebSocketHandler): raise Exception("boom") class NoDelayHandler(TestWebSocketHandler): def open(self): self.set_nodelay(True) self.write_message("hello") class WebSocketBaseTestCase(AsyncHTTPTestCase): @gen.coroutine def ws_connect(self, path, **...
class WebSocketTest(WebSocketBaseTestCase): ), ("/error_in_open", ErrorInOpenHandler), ("/error_in_async_open", ErrorInAsyncOpenHandler), ], template_loader=DictLoader({"message.html": "<b>{{ message }}</b>"}), )
class WebSocketTest(WebSocketBaseTestCase): ), ("/error_in_open", ErrorInOpenHandler), ("/error_in_async_open", ErrorInAsyncOpenHandler), ("/nodelay", NoDelayHandler), ], template_loader=DictLoader({"message.html": "<b>{{ message }}...
class WebSocketTest(WebSocketBaseTestCase): res = yield ws.read_message() self.assertIsNone(res) class NativeCoroutineOnMessageHandler(TestWebSocketHandler): def initialize(self, **kwargs):
class WebSocketTest(WebSocketBaseTestCase): res = yield ws.read_message() self.assertIsNone(res) @gen_test def test_nodelay(self): ws = yield self.ws_connect("/nodelay") res = yield ws.read_message() self.assertEqual(res, "hello") class NativeCoroutineOnMessageHand...
class WebSocketHandler(tornado.web.RequestHandler): .. versionadded:: 3.1 """ assert self.stream is not None self.stream.set_nodelay(value) def on_connection_close(self) -> None: if self.ws_connection:
class WebSocketHandler(tornado.web.RequestHandler): .. versionadded:: 3.1 """ assert self.ws_connection is not None self.ws_connection.set_nodelay(value) def on_connection_close(self) -> None: if self.ws_connection:
class WebSocketProtocol(abc.ABC): async def _receive_frame_loop(self) -> None: raise NotImplementedError() class _PerMessageDeflateCompressor(object): def __init__(
class WebSocketProtocol(abc.ABC): async def _receive_frame_loop(self) -> None: raise NotImplementedError() @abc.abstractmethod def set_nodelay(self, x: bool) -> None: raise NotImplementedError() class _PerMessageDeflateCompressor(object): def __init__(
class WebSocketProtocol13(WebSocketProtocol): self.write_ping(b"") self.last_ping = now class WebSocketClientConnection(simple_httpclient._HTTPConnection): """WebSocket client connection.
class WebSocketProtocol13(WebSocketProtocol): self.write_ping(b"") self.last_ping = now def set_nodelay(self, x: bool) -> None: self.stream.set_nodelay(x) class WebSocketClientConnection(simple_httpclient._HTTPConnection): """WebSocket client connection.
import time import traceback import math from tornado.concurrent import TracebackFuture, is_future from tornado.log import app_log, gen_log from tornado.platform.auto import set_close_exec, Waker from tornado import stack_context
import time import traceback import math from tornado.concurrent import TracebackFuture, is_future, chain_future from tornado.log import app_log, gen_log from tornado.platform.auto import set_close_exec, Waker from tornado import stack_context
class IOLoop(Configurable): from tornado.process import cpu_count self._executor = ThreadPoolExecutor(max_workers=(cpu_count() * 5)) executor = self._executor return executor.submit(func, *args) def set_default_executor(self, executor): """Sets the defau...
class IOLoop(Configurable): from tornado.process import cpu_count self._executor = ThreadPoolExecutor(max_workers=(cpu_count() * 5)) executor = self._executor c_future = executor.submit(func, *args) # Concurrent Futures are not usable with await. Wrap this in ...
class TestIOLoopFutures(AsyncTestCase): event1 = threading.Event() event2 = threading.Event() def callback(self_event, other_event): self_event.set() time.sleep(0.01) self.assertTrue(other_event.is_set()) return self_event res = yield [ ...
class TestIOLoopFutures(AsyncTestCase): event1 = threading.Event() event2 = threading.Event() def sync_func(self_event, other_event): self_event.set() other_event.wait() # Note that return value doesn't actually do anything, # it is just passed th...
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): ...
import hashlib import json import random import string import sys import tempfile
import hashlib import json import random import stat import string import sys import tempfile
def build(self): cache_file = os.path.join( tempfile.gettempdir(), "rply-%s-%s-%s.json" % (self.VERSION, self.cache_id, self.compute_grammar_hash(g)) ) table = None if os.path.exists(cache_file): with open(cache_file) as f: data = json...
def build(self): cache_file = os.path.join( tempfile.gettempdir(), "rply-%s-%s-%s-%s.json" % (self.VERSION, os.getuid(), self.cache_id, self.compute_grammar_hash(g)) ) table = None if os.path.exists(cache_file): with open(cache_file) as f: ...
def yaml_msg_str(type_, yaml_str, filename=None): if yaml_str.strip() == '': msg_dict = {} else: msg_dict = yaml.load(yaml_str) if not isinstance(msg_dict, dict): if filename: raise ValueError("yaml file [%s] does not contain a dictionary" % filename)
def yaml_msg_str(type_, yaml_str, filename=None): if yaml_str.strip() == '': msg_dict = {} else: msg_dict = yaml.safe_load(yaml_str) if not isinstance(msg_dict, dict): if filename: raise ValueError("yaml file [%s] does not contain a dictionary" % filename)
def yaml_msgs_str(type_, yaml_str, filename=None): @type filename: str """ import yaml yaml_doc = yaml.load(yaml_str) msgs = [] for msg_dict in yaml_doc: if not isinstance(msg_dict, dict):
def yaml_msgs_str(type_, yaml_str, filename=None): @type filename: str """ import yaml yaml_doc = yaml.safe_load(yaml_str) msgs = [] for msg_dict in yaml_doc: if not isinstance(msg_dict, dict):
from django.db.models.sql.where import ( ) from django.utils.deprecation import RemovedInDjango40Warning from django.utils.functional import cached_property from django.utils.tree import Node __all__ = ['Query', 'RawQuery'] def get_field_names_from_opts(opts): return set(chain.from_iterable(
from django.db.models.sql.where import ( ) from django.utils.deprecation import RemovedInDjango40Warning from django.utils.functional import cached_property from django.utils.regex_helper import _lazy_re_compile from django.utils.tree import Node __all__ = ['Query', 'RawQuery'] # Quotation marks ('"`[]), whitespace c...
class Query(BaseExpression): alias = seen[int_model] = join_info.joins[-1] return alias or seen[None] def add_annotation(self, annotation, alias, is_summary=False, select=True): """Add a single annotation expression to the Query.""" annotation = annotation.resolve_expression(sel...
class Query(BaseExpression): alias = seen[int_model] = join_info.joins[-1] return alias or seen[None] def check_alias(self, alias): if FORBIDDEN_ALIAS_PATTERN.search(alias): raise ValueError( "Column aliases cannot contain whitespace characters, quotation mar...
class Query(BaseExpression): else: param_iter = iter([]) for name, entry in select.items(): entry = str(entry) entry_params = [] pos = entry.find("%s")
class Query(BaseExpression): else: param_iter = iter([]) for name, entry in select.items(): self.check_alias(name) entry = str(entry) entry_params = [] pos = entry.find("%s")
class AggregateTestCase(TestCase): ('Stuart Russell', 1), ('Peter Norvig', 2), ], lambda a: (a.name, a.contact_count), ordered=False)
class AggregateTestCase(TestCase): ('Stuart Russell', 1), ('Peter Norvig', 2), ], lambda a: (a.name, a.contact_count), ordered=False) def test_alias_sql_injection(self): crafted_alias = """injected_name" from "aggregation_author"; --""" msg = ( "Column al...
class NonAggregateAnnotationTestCase(TestCase): {'name': 'Wesley J. Chun', 'max_pages': 0}, ]) class AliasTests(TestCase): @classmethod
class NonAggregateAnnotationTestCase(TestCase): {'name': 'Wesley J. Chun', 'max_pages': 0}, ]) def test_alias_sql_injection(self): crafted_alias = """injected_name" from "annotations_book"; --""" msg = ( "Column aliases cannot contain whitespace characters, quotation...
class AliasTests(TestCase): with self.subTest(operation=operation): with self.assertRaisesMessage(FieldError, msg): getattr(qs, operation)('rating_alias')
class AliasTests(TestCase): with self.subTest(operation=operation): with self.assertRaisesMessage(FieldError, msg): getattr(qs, operation)('rating_alias') def test_alias_sql_injection(self): crafted_alias = """injected_name" from "annotations_book"; --""" ...
class ValuesExpressionsTests(TestCase): [{'salary': 10}, {'salary': 20}, {'salary': 30}], ) def test_values_expression_group_by(self): # values() applies annotate() first, so values selected are grouped by # id, not firstname.
class ValuesExpressionsTests(TestCase): [{'salary': 10}, {'salary': 20}, {'salary': 30}], ) def test_values_expression_alias_sql_injection(self): crafted_alias = """injected_name" from "expressions_company"; --""" msg = ( "Column aliases cannot contain whitespace cha...
class Queries5Tests(TestCase): 'bar %s' ) class SelectRelatedTests(TestCase): def test_tickets_3045_3288(self):
class Queries5Tests(TestCase): 'bar %s' ) def test_extra_select_alias_sql_injection(self): crafted_alias = """injected_name" from "queries_note"; --""" msg = ( "Column aliases cannot contain whitespace characters, quotation marks, " "semicolons, or SQL co...
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 test_register(self): # Test registering a viewer that is not a class ImageShow.register("not a class") def test_show(self): class TestViewer: methodCalled = False
def test_register(self): # Test registering a viewer that is not a class ImageShow.register("not a class") # Restore original state ImageShow._viewers.pop() def test_show(self): class TestViewer: methodCalled = False
def show(self, image, title=None, **options): self.assertTrue(ImageShow.show(im)) self.assertTrue(viewer.methodCalled) def test_viewer(self): viewer = ImageShow.Viewer()
def show(self, image, title=None, **options): self.assertTrue(ImageShow.show(im)) self.assertTrue(viewer.methodCalled) # Restore original state ImageShow._viewers.pop(0) def test_viewer(self): viewer = ImageShow.Viewer()
def test_viewer(self): self.assertRaises(NotImplementedError, viewer.get_command, None) if __name__ == '__main__': unittest.main()
def test_viewer(self): self.assertRaises(NotImplementedError, viewer.get_command, None) def test_viewers(self): for viewer in ImageShow._viewers: viewer.get_command('test.jpg') if __name__ == '__main__': unittest.main()
from PIL import Image import os import sys if sys.version_info.major >= 3: from shlex import quote
from PIL import Image import os import sys import subprocess import tempfile if sys.version_info.major >= 3: from shlex import quote
def get_command(self, file, **options): quote(file)) return command register(MacViewer) else:
def get_command(self, file, **options): quote(file)) return command def show_file(self, file, **options): """Display given file""" f, path = tempfile.mkstemp() f.write(file) f.close() ...
class UnixViewer(Viewer): format = "PNG" options = {'compress_level': 1} def show_file(self, file, **options): command, executable = self.get_command_ex(file, **options) command = "(%s %s; rm -f %s)&" % (command, quote(file), ...
class UnixViewer(Viewer): format = "PNG" options = {'compress_level': 1} def get_command(self, file, **options): command = self.get_command_ex(file, **options)[0] return "(%s %s; rm -f %s)&" % (command, quote(file), quote(file)) def show_file(self, file, **optio...
default 'raise' """ from pandas import DataFrame sarray = fields.build_isocalendar_sarray(self.asi8) iso_calendar_df = DataFrame( sarray, columns=["year", "week", "day"], dtype="UInt32" )
default 'raise' """ from pandas import DataFrame if self.tz is not None and not timezones.is_utc(self.tz): values = self._local_timestamps() else: values = self.asi8 sarray = fields.build_isocalendar_sarray(values) iso_calendar_df = DataFrame( ...
def test_iter_readonly(): arr.setflags(write=False) dti = pd.to_datetime(arr) list(dti)
def test_iter_readonly(): arr.setflags(write=False) dti = pd.to_datetime(arr) list(dti) def test_isocalendar_returns_correct_values_close_to_new_year_with_tz(): # GH 6538: Check that DatetimeIndex and its TimeStamp elements # return the same weekofyear accessor close to new year w/ tz dates = ...
def assert_series_equal( check_exact=False, check_datetimelike_compat=False, check_categorical=True, obj="Series", ): """
def assert_series_equal( check_exact=False, check_datetimelike_compat=False, check_categorical=True, check_category_order=True, obj="Series", ): """
def assert_series_equal( Compare datetime-like which is comparable ignoring dtype. check_categorical : bool, default True Whether to compare internal Categorical exactly. obj : str, default 'Series' Specify object name being compared, internally used to show appropriate assertion...
def assert_series_equal( Compare datetime-like which is comparable ignoring dtype. check_categorical : bool, default True Whether to compare internal Categorical exactly. check_category_order : bool, default True Whether to compare category order of internal Categoricals .. vers...
def assert_series_equal( if check_categorical: if is_categorical_dtype(left) or is_categorical_dtype(right): assert_categorical_equal(left.values, right.values, obj=f"{obj} category") # This could be refactored to use the NDFrame.equals method
def assert_series_equal( if check_categorical: if is_categorical_dtype(left) or is_categorical_dtype(right): assert_categorical_equal( left.values, right.values, obj=f"{obj} category", check_category_order=check_category_order, ...
class Categorical(ExtensionArray, PandasObject): """ inplace = validate_bool_kwarg(inplace, "inplace") cat = self if inplace else self.copy() if to_replace in cat.categories: if isna(value): cat.remove_categories(to_replace, inplace=True) else: ...
class Categorical(ExtensionArray, PandasObject): """ inplace = validate_bool_kwarg(inplace, "inplace") cat = self if inplace else self.copy() # build a dict of (to replace -> value) pairs if is_list_like(to_replace): # if to_replace is list-like and value is scalar ...
def capfirst(x): # Set up regular expressions re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.S) re_chars = re.compile(r'<.*?>|(.)', re.S) re_tag = re.compile(r'<(/)?([^ ]+?)(?:(\s*/)| .*?)?>', re.S) re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines re_camel_case = re.compile(r'(((?<=[a-z])[A-...
def capfirst(x): # Set up regular expressions re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.S) re_chars = re.compile(r'<.*?>|(.)', re.S) re_tag = re.compile(r'<(/)?(\S+?)(?:(\s*/)|\s.*?)?>', re.S) re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines re_camel_case = re.compile(r'(((?<=[a-z])[A-Z...
class TestUtilsText(SimpleTestCase): truncator = text.Truncator('<p>I &lt;3 python, what about you?</p>') self.assertEqual('<p>I &lt;3 python...</p>', truncator.words(3, '...', html=True)) def test_wrap(self): digits = '1234 67 9' self.assertEqual(text.wrap(digits, 100), '1234 67 9'...
class TestUtilsText(SimpleTestCase): truncator = text.Truncator('<p>I &lt;3 python, what about you?</p>') self.assertEqual('<p>I &lt;3 python...</p>', truncator.words(3, '...', html=True)) re_tag_catastrophic_test = ('</a' + '\t' * 50000) + '//>' truncator = text.Truncator(re_tag_catast...
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): ...
def _make_result(formats, **kwargs): 'id': 'testid', 'title': 'testttitle', 'extractor': 'testex', } res.update(**kwargs) return res
def _make_result(formats, **kwargs): 'id': 'testid', 'title': 'testttitle', 'extractor': 'testex', 'extractor_key': 'TestEx', } res.update(**kwargs) return res
class TestYoutubeDL(unittest.TestCase): '_type': 'url_transparent', 'url': 'foo2:', 'ie_key': 'Foo2', 'title': 'foo1 title' } class Foo2IE(InfoExtractor):
class TestYoutubeDL(unittest.TestCase): '_type': 'url_transparent', 'url': 'foo2:', 'ie_key': 'Foo2', 'title': 'foo1 title', 'id': 'foo1_id', } class Foo2IE(InfoExtractor):
class TestYoutubeDL(unittest.TestCase): downloaded = ydl.downloaded_info_dicts[0] self.assertEqual(downloaded['url'], TEST_URL) self.assertEqual(downloaded['title'], 'foo1 title') if __name__ == '__main__':
class TestYoutubeDL(unittest.TestCase): downloaded = ydl.downloaded_info_dicts[0] self.assertEqual(downloaded['url'], TEST_URL) self.assertEqual(downloaded['title'], 'foo1 title') self.assertEqual(downloaded['id'], 'testid') self.assertEqual(downloaded['extractor'], 'testex') ...
class YoutubeDL(object): force_properties = dict( (k, v) for k, v in ie_result.items() if v is not None) for f in ('_type', 'url', 'ie_key'): if f in force_properties: del force_properties[f] new_result = info.copy()
class YoutubeDL(object): force_properties = dict( (k, v) for k, v in ie_result.items() if v is not None) for f in ('_type', 'url', 'id', 'extractor', 'extractor_key', 'ie_key'): if f in force_properties: del force_properties[f] new...
class MarkerStyle: self._snap_threshold = None self._joinstyle = 'round' self._capstyle = 'butt' self._filled = True self._marker_function() def __bool__(self):
class MarkerStyle: self._snap_threshold = None self._joinstyle = 'round' self._capstyle = 'butt' # Initial guess: Assume the marker is filled unless the fillstyle is # set to 'none'. The marker function will override this for unfilled # markers. self._filled = sel...
from matplotlib.testing.decorators import check_figures_equal import pytest def test_markers_valid(): marker_style = markers.MarkerStyle() mrk_array = np.array([[-0.5, 0],
from matplotlib.testing.decorators import check_figures_equal import pytest def test_marker_fillstyle(): marker_style = markers.MarkerStyle(marker='o', fillstyle='none') assert marker_style.get_fillstyle() == 'none' assert not marker_style.is_filled() def test_markers_valid(): marker_style = markers...
class _MergeOperation: ) ] else: left_keys = [self.left.index.values] if left_drop: self.left = self.left._drop_labels_or_levels(left_drop)
class _MergeOperation: ) ] else: left_keys = [self.left.index._values] if left_drop: self.left = self.left._drop_labels_or_levels(left_drop)
class TestAsOfMerge: result = pd.merge_asof(left, right, on="a", tolerance=10) tm.assert_frame_equal(result, expected)
class TestAsOfMerge: result = pd.merge_asof(left, right, on="a", tolerance=10) tm.assert_frame_equal(result, expected) def test_merge_index_column_tz(self): # GH 29864 index = pd.date_range("2019-10-01", freq="30min", periods=5, tz="UTC") left = pd.DataFrame([0.9, 0.8, 0.7,...
class RNN(Layer): input_shape = input_shape[0] if hasattr(self.cell.state_size, '__len__'): output_dim = self.cell.state_size[0] else: output_dim = self.cell.state_size if self.return_sequences: output_shape = (input_shape[0], input_shape[1], out...
class RNN(Layer): input_shape = input_shape[0] if hasattr(self.cell.state_size, '__len__'): state_size = self.cell.state_size else: state_size = [self.cell.state_size] output_dim = state_size[0] if self.return_sequences: output_shape = (i...