buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
from datetime import timedelta from pandas import Series, Timedelta, date_range, period_range, to_datetime import pandas._testing as tm
from datetime import timedelta import pytest from pandas import PeriodIndex, Series, Timedelta, date_range, period_range, to_datetime import pandas._testing as tm
class TestToTimestamp: exp_index = exp_index + Timedelta(1, "s") - Timedelta(1, "ns") tm.assert_index_equal(result.index, exp_index) assert result.name == "foo"
class TestToTimestamp: exp_index = exp_index + Timedelta(1, "s") - Timedelta(1, "ns") tm.assert_index_equal(result.index, exp_index) assert result.name == "foo" def test_to_timestamp_raises(self, indices): # https://github.com/pandas-dev/pandas/issues/33327 index = indices ...
import sys # Import 3rd-party libs import jinja2 import jinja2.ext from salt.ext import six if sys.version_info[:2] >= (3, 5):
import sys # Import 3rd-party libs import jinja2 import jinja2.ext import jinja2.sandbox from salt.ext import six if sys.version_info[:2] >= (3, 5):
def render_jinja_tmpl(tmplstr, context, tmplpath=None): opt_jinja_env_helper(opt_jinja_env, 'jinja_env') if opts.get('allow_undefined', False): jinja_env = jinja2.Environment(**env_args) else: jinja_env = jinja2.Environment(undefined=jinja2.StrictUndefined, ...
def render_jinja_tmpl(tmplstr, context, tmplpath=None): opt_jinja_env_helper(opt_jinja_env, 'jinja_env') if opts.get('allow_undefined', False): jinja_env = jinja2.sandbox.SandboxedEnvironment(**env_args) else: jinja_env = jinja2.sandbox.SandboxedEnvironment(undefined=jinja2.StrictUndefi...
def render_jinja_tmpl(tmplstr, context, tmplpath=None): exc, out), buf=tmplstr) except (jinja2.exceptions.TemplateRuntimeError, jinja2.exceptions.TemplateSyntaxError) as exc: trace = traceback.extract_tb(sys.exc_info()[2]) line, out = _get_jinja_error(trace, c...
def render_jinja_tmpl(tmplstr, context, tmplpath=None): exc, out), buf=tmplstr) except (jinja2.exceptions.TemplateRuntimeError, jinja2.exceptions.TemplateSyntaxError, jinja2.exceptions.SecurityError) as exc: trace = traceback.extract_tb(sys.exc_info()[2]) ...
from __future__ import absolute_import, print_function, unicode_literals import os import sys import logging # Import Salt libs import salt.utils.templates
from __future__ import absolute_import, print_function, unicode_literals import os import sys import logging import pytest # Import Salt libs import salt.utils.templates
class RenderTestCase(TestCase): res = salt.utils.templates.render_cheetah_tmpl(tmpl, ctx) self.assertEqual(res.strip(), 'OK') class MockRender(object): def __call__(self, tplstr, context, tmplpath=None):
class RenderTestCase(TestCase): res = salt.utils.templates.render_cheetah_tmpl(tmpl, ctx) self.assertEqual(res.strip(), 'OK') def test_render_jinja_cve_2021_25283(self): tmpl = '''{{ [].__class__ }}''' ctx = dict(self.context) ctx['var'] = 'OK' with pytest.raises(sal...
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): ...
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 --quiet', stderr=stderr))\ == "git push --set-upstream origin master --quiet"
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 match(command): @git_support def get_new_command(command): push_upstream = command.stderr.split('\n')[-3].strip().partition('git ')[2] return replace_argument(command.script, 'push', push_upstream)
def match(command): @git_support def get_new_command(command): # If --set-upstream or -u are passed, remove it and its argument. This is # because the remaining arguments are concatenated onto the command suggested # by git, which includes --set-upstream and its argument upstream_option_index = -1 ...
class _Rolling_and_Expanding(_Rolling): raise ValueError("engine must be either 'numba' or 'cython'") # TODO: Why do we always pass center=False? # name=func for WindowGroupByMixin._apply return self._apply( apply_func, center=False, floor=0, ...
class _Rolling_and_Expanding(_Rolling): raise ValueError("engine must be either 'numba' or 'cython'") # TODO: Why do we always pass center=False? # name=func & raw=raw for WindowGroupByMixin._apply return self._apply( apply_func, center=False, flo...
class TestGrouperGrouping: result = r.apply(lambda x: x.sum(), raw=raw) expected = g.apply(lambda x: x.expanding().apply(lambda y: y.sum(), raw=raw)) tm.assert_frame_equal(result, expected)
class TestGrouperGrouping: result = r.apply(lambda x: x.sum(), raw=raw) expected = g.apply(lambda x: x.expanding().apply(lambda y: y.sum(), raw=raw)) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("expected_value,raw_value", [[1.0, True], [0.0, False]]) def test_groupb...
class RadialLocator(mticker.Locator): :class:`~matplotlib.ticker.Locator` (which may be different depending on the scale of the *r*-axis. """ def __init__(self, base, axes=None): self.base = base self._axes = axes
class RadialLocator(mticker.Locator): :class:`~matplotlib.ticker.Locator` (which may be different depending on the scale of the *r*-axis. """ def __init__(self, base, axes=None): self.base = base self._axes = axes
class RadialLocator(mticker.Locator): # docstring inherited return self.base.refresh() def view_limits(self, vmin, vmax): vmin, vmax = self.base.view_limits(vmin, vmax) if vmax > vmin:
class RadialLocator(mticker.Locator): # docstring inherited return self.base.refresh() def nonsingular(self, vmin, vmax): # docstring inherited return ((0, 1) if (vmin, vmax) == (-np.inf, np.inf) # Init. limits. else self.base.nonsingular(vmin, vmax)) def view_...
def test_log_scales_invalid(): ax.set_ylim(-1, 10) @image_comparison(['stackplot_test_image', 'stackplot_test_image']) def test_stackplot(): fig = plt.figure()
def test_log_scales_invalid(): ax.set_ylim(-1, 10) def test_polar_no_data(): plt.subplot(projection="polar") ax = plt.gca() assert ax.get_rmin() == 0 and ax.get_rmax() == 1 plt.close("all") # Used to behave differently (by triggering an autoscale with no data). plt.polar() ax = plt...
LOGGING_CONFIG_DEFAULTS = dict( version=1, disable_existing_loggers=False, loggers={ "root": {"level": "INFO", "handlers": ["console"]}, "sanic.error": { "level": "INFO", "handlers": ["error_console"],
LOGGING_CONFIG_DEFAULTS = dict( version=1, disable_existing_loggers=False, loggers={ "sanic.root": {"level": "INFO", "handlers": ["console"]}, "sanic.error": { "level": "INFO", "handlers": ["error_console"],
def test_logging_defaults(): reset_logging() app = Sanic("test_logging") for fmt in [h.formatter for h in logging.getLogger('root').handlers]: assert fmt._fmt == LOGGING_CONFIG_DEFAULTS['formatters']['generic']['format'] for fmt in [h.formatter for h in logging.getLogger('sanic.error').handler...
def test_logging_defaults(): reset_logging() app = Sanic("test_logging") for fmt in [h.formatter for h in logging.getLogger('sanic.root').handlers]: assert fmt._fmt == LOGGING_CONFIG_DEFAULTS['formatters']['generic']['format'] for fmt in [h.formatter for h in logging.getLogger('sanic.error').h...
def test_logging_pass_customer_logconfig(): app = Sanic("test_logging", log_config=modified_config) for fmt in [h.formatter for h in logging.getLogger('root').handlers]: assert fmt._fmt == modified_config['formatters']['generic']['format'] for fmt in [h.formatter for h in logging.getLogger('sanic...
def test_logging_pass_customer_logconfig(): app = Sanic("test_logging", log_config=modified_config) for fmt in [h.formatter for h in logging.getLogger('sanic.root').handlers]: assert fmt._fmt == modified_config['formatters']['generic']['format'] for fmt in [h.formatter for h in logging.getLogger(...
def test_logging_pass_customer_logconfig(): def test_log_connection_lost(app, debug, monkeypatch): """ Should not log Connection lost exception on non debug """ stream = StringIO() root = logging.getLogger('root') root.addHandler(logging.StreamHandler(stream)) monkeypatch.setattr(sanic.server, 'logg...
def test_logging_pass_customer_logconfig(): def test_log_connection_lost(app, debug, monkeypatch): """ Should not log Connection lost exception on non debug """ stream = StringIO() root = logging.getLogger('sanic.root') root.addHandler(logging.StreamHandler(stream)) monkeypatch.setattr(sanic.server,...
def test_log_connection_lost(app, debug, monkeypatch): assert 'Connection lost before response written @' in log else: assert 'Connection lost before response written @' not in log
def test_log_connection_lost(app, debug, monkeypatch): assert 'Connection lost before response written @' in log else: assert 'Connection lost before response written @' not in log def test_logging_modified_root_logger_config(): reset_logging() modified_config = LOGGING_CONFIG_DEFAULTS ...
class HiveCommandClient(HiveClient): if partition is None: stdout = run_hive_cmd('use {0}; show tables like "{1}";'.format(database, table)) return stdout and table in stdout else: stdout = run_hive_cmd("""use %s; show partitions %s partition ...
class HiveCommandClient(HiveClient): if partition is None: stdout = run_hive_cmd('use {0}; show tables like "{1}";'.format(database, table)) return stdout and table.lower() in stdout else: stdout = run_hive_cmd("""use %s; show partitions %s partition ...
class HiveCommandClientTest(unittest.TestCase): returned = self.client.table_exists("mytable") self.assertTrue(returned) run_command.return_value = "day=2013-06-28/hour=3\n" \ "day=2013-06-28/hour=4\n" \ "day=2013-07-07/hour=...
class HiveCommandClientTest(unittest.TestCase): returned = self.client.table_exists("mytable") self.assertTrue(returned) # Issue #896 test case insensitivity returned = self.client.table_exists("MyTable") self.assertTrue(returned) run_command.return_value = "day=2013-06...
class HiveCommandClientTest(unittest.TestCase): returned = self.apacheclient.table_exists("mytable") self.assertTrue(returned) run_command.return_value = "day=2013-06-28/hour=3\n" \ "day=2013-06-28/hour=4\n" \ "day=2013-07-07...
class HiveCommandClientTest(unittest.TestCase): returned = self.apacheclient.table_exists("mytable") self.assertTrue(returned) # Issue #896 test case insensitivity returned = self.apacheclient.table_exists("MyTable") self.assertTrue(returned) run_command.return_value = ...
def wrapped(self, *args, **kwargs): try: try: return_tuple = func(self, *args, **kwargs) display.vvv(return_tuple, host=self.host) # 0 = success # 1-254 = remote command return code # 255 coul...
def wrapped(self, *args, **kwargs): try: try: return_tuple = func(self, *args, **kwargs) if self._play_context.no_log: display.vvv('rc=%s, stdout & stderr censored due to no log' % return_tuple[0], host=self.host) ...
def wrapped(self, *args, **kwargs): break if SSH_ERROR: raise AnsibleConnectionFailure("Failed to connect to the host via ssh: %s" % to_native(return_tuple[2])) break
def wrapped(self, *args, **kwargs): break if SSH_ERROR: msg = "Failed to connect to the host via ssh: " if self._play_context.no_log: msg += '<error censored due to no log>' ...
def _create_powershell_wrapper(b_module_data, module_args, environment, exec_manifest['csharp_utils'][name] = b64_data exec_manifest['csharp_utils_module'] = list(finder.cs_utils_module.keys()) # FUTURE: smuggle this back as a dict instead of serializing here; # the connection plugin may need to mo...
def _create_powershell_wrapper(b_module_data, module_args, environment, exec_manifest['csharp_utils'][name] = b64_data exec_manifest['csharp_utils_module'] = list(finder.cs_utils_module.keys()) b_json = to_bytes(json.dumps(exec_manifest)) # delimit the payload JSON from the wrapper to keep sensitiv...
class ActionModule(ActionBase): # PowerShell runs the script in a special wrapper to enable things # like become and environment args if self._connection._shell.SHELL_FAMILY == "powershell": # FIXME: use a more public method to get the exec payload pc ...
class ActionModule(ActionBase): # PowerShell runs the script in a special wrapper to enable things # like become and environment args if self._connection._shell.SHELL_FAMILY == "powershell": # FUTURE: use a more public method to get the exec payload pc...
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
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 pandas.core.dtypes.cast import ( validate_numeric_casting, ) from pandas.core.dtypes.common import ( ensure_float64, ensure_int64, ensure_platform_int, infer_dtype_from_object,
from pandas.core.dtypes.cast import ( validate_numeric_casting, ) from pandas.core.dtypes.common import ( ensure_int64, ensure_platform_int, infer_dtype_from_object,
Wild 185.0 numeric_df = self._get_numeric_data() cols = numeric_df.columns idx = cols.copy() mat = numeric_df.values if method == "pearson": correl = libalgos.nancorr(ensure_float64(mat), minp=min_periods) elif method == "spearman": correl...
Wild 185.0 numeric_df = self._get_numeric_data() cols = numeric_df.columns idx = cols.copy() mat = numeric_df.astype(float, copy=False).to_numpy() if method == "pearson": correl = libalgos.nancorr(mat, minp=min_periods) elif method == "spearman": ...
Wild 185.0 numeric_df = self._get_numeric_data() cols = numeric_df.columns idx = cols.copy() mat = numeric_df.values if notna(mat).all(): if min_periods is not None and min_periods > len(mat): baseCov = np.empty((mat.shape[1], mat.shape[1])) ...
Wild 185.0 numeric_df = self._get_numeric_data() cols = numeric_df.columns idx = cols.copy() mat = numeric_df.astype(float, copy=False).to_numpy() if notna(mat).all(): if min_periods is not None and min_periods > len(mat): base_cov = np.empty(...
class TestDataFrameCov: ) tm.assert_frame_equal(result, expected) class TestDataFrameCorr: # DataFrame.corr(), as opposed to DataFrame.corrwith
class TestDataFrameCov: ) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "other_column", [pd.array([1, 2, 3]), np.array([1.0, 2.0, 3.0])] ) def test_cov_nullable_integer(self, other_column): # https://github.com/pandas-dev/pandas/issues/33803 data ...
class TestDataFrameCorr: df3.cov() df3.corr() class TestDataFrameCorrWith: def test_corrwith(self, datetime_frame):
class TestDataFrameCorr: df3.cov() df3.corr() @td.skip_if_no_scipy @pytest.mark.parametrize( "nullable_column", [pd.array([1, 2, 3]), pd.array([1, 2, None])] ) @pytest.mark.parametrize( "other_column", [pd.array([1, 2, 3]), np.array([1.0, 2.0, 3.0]), np.array([1....
class CrawlerProcess(CrawlerRunner): def __init__(self, settings): super(CrawlerProcess, self).__init__(settings) install_shutdown_handlers(self._signal_shutdown) configure_logging(settings) log_scrapy_info(settings) def _signal_shutdown(self, signum, _): install_shutdow...
class CrawlerProcess(CrawlerRunner): def __init__(self, settings): super(CrawlerProcess, self).__init__(settings) install_shutdown_handlers(self._signal_shutdown) configure_logging(self.settings) log_scrapy_info(self.settings) def _signal_shutdown(self, signum, _): insta...
import warnings import unittest from scrapy.crawler import Crawler, CrawlerRunner from scrapy.settings import Settings, default_settings from scrapy.spiderloader import SpiderLoader from scrapy.utils.spider import DefaultSpider
import warnings import unittest from scrapy.crawler import Crawler, CrawlerRunner, CrawlerProcess from scrapy.settings import Settings, default_settings from scrapy.spiderloader import SpiderLoader from scrapy.utils.spider import DefaultSpider
class CrawlerRunnerTestCase(unittest.TestCase): self.assertEqual(len(w), 1) self.assertIn('Please use SPIDER_LOADER_CLASS', str(w[0].message))
class CrawlerRunnerTestCase(unittest.TestCase): self.assertEqual(len(w), 1) self.assertIn('Please use SPIDER_LOADER_CLASS', str(w[0].message)) class CrawlerProcessTest(unittest.TestCase): def test_crawler_process_accepts_dict(self): runner = CrawlerProcess({'foo': 'bar'}) s...
HOST = test_support.HOST CERTFILE = None SVN_PYTHON_ORG_ROOT_CERT = None def handle_error(prefix): exc_format = ' '.join(traceback.format_exception(*sys.exc_info()))
HOST = test_support.HOST CERTFILE = None SVN_PYTHON_ORG_ROOT_CERT = None NULLBYTECERT = None def handle_error(prefix): exc_format = ' '.join(traceback.format_exception(*sys.exc_info()))
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_4238(self): p = ssl._ssl._test_decode_cert(NULLBYTECERT) if test_support.verbose: sys.stdout.write("\n" + pprint.pformat(p) + "\n") su...
def test_default_ciphers(self): def test_main(verbose=False): global CERTFILE, SVN_PYTHON_ORG_ROOT_CERT, NOKIACERT CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir, "keycert.pem") SVN_PYTHON_ORG_ROOT_CERT = os.path.join(
def test_default_ciphers(self): def test_main(verbose=False): global CERTFILE, SVN_PYTHON_ORG_ROOT_CERT, NOKIACERT, NULLBYTECERT CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir, "keycert.pem") SVN_PYTHON_ORG_ROOT_CERT = os.path.join(
def test_main(verbose=False): "https_svn_python_org_root.pem") NOKIACERT = os.path.join(os.path.dirname(__file__) or os.curdir, "nokia.pem") if (not os.path.exists(CERTFILE) or not os.path.exists(SVN_PYTHON_ORG_ROOT_CERT) or not os.path.exists(NOKIACERT)): ...
def test_main(verbose=False): "https_svn_python_org_root.pem") NOKIACERT = os.path.join(os.path.dirname(__file__) or os.curdir, "nokia.pem") NULLBYTECERT = os.path.join(os.path.dirname(__file__) or os.curdir, "nullbytecert.pem") if (not o...
def generate_tokens(readline): stashed = tok continue if token == 'def': if (stashed and stashed[0] == NAME and stashed[1] == 'async'): ...
def generate_tokens(readline): stashed = tok continue if token in ('def', 'for'): if (stashed and stashed[0] == NAME and stashed[1] == 'async'): ...
class BlackTestCase(unittest.TestCase): self.assertFormatEqual(expected, actual) black.assert_stable(source, actual, line_length=ll, mode=mode) @patch("black.dump_to_file", dump_to_stderr) def test_fmtonoff(self) -> None: source, expected = read_data("fmtonoff")
class BlackTestCase(unittest.TestCase): self.assertFormatEqual(expected, actual) black.assert_stable(source, actual, line_length=ll, mode=mode) @patch("black.dump_to_file", dump_to_stderr) def test_python37(self) -> None: source, expected = read_data("python37") actual = fs(sour...
def load_model_from_path(model_path, meta=False, **overrides): for name in pipeline: if name not in disable: config = meta.get("pipeline_args", {}).get(name, {}) factory = factories.get(name, name) component = nlp.create_pipe(factory, config=config) nlp.add_pi...
def load_model_from_path(model_path, meta=False, **overrides): for name in pipeline: if name not in disable: config = meta.get("pipeline_args", {}).get(name, {}) config.update(overrides) factory = factories.get(name, name) component = nlp.create_pipe(factory, ...
class MultiIndex(Index): if len(uniques) < len(level_index): # Remove unobserved levels from level_index level_index = level_index.take(uniques) if len(level_index): grouper = level_index.take(codes)
class MultiIndex(Index): if len(uniques) < len(level_index): # Remove unobserved levels from level_index level_index = level_index.take(uniques) else: # break references back to us so that setting the name # on the output of a groupby doesn't reflect back ...
def test_apply_series_return_dataframe_groups(): ["17661101"], index=pd.DatetimeIndex(["2015-02-24"], name="day"), name="userId" ) tm.assert_series_equal(result, expected)
def test_apply_series_return_dataframe_groups(): ["17661101"], index=pd.DatetimeIndex(["2015-02-24"], name="day"), name="userId" ) tm.assert_series_equal(result, expected) @pytest.mark.parametrize("category", [False, True]) def test_apply_multi_level_name(category): # https://github.com/pandas-dev...
class HTTP1Connection(httputil.HTTPConnection): return connection_header != "close" elif ("Content-Length" in headers or headers.get("Transfer-Encoding", "").lower() == "chunked" or start_line.method in ("HEAD", "GET")): return connection_header == "keep-alive...
class HTTP1Connection(httputil.HTTPConnection): return connection_header != "close" elif ("Content-Length" in headers or headers.get("Transfer-Encoding", "").lower() == "chunked" or getattr(start_line, 'method', None) in ("HEAD", "GET")): # start_line may be a...
TEST_MODULES = [ 'tornado.test.curl_httpclient_test', 'tornado.test.escape_test', 'tornado.test.gen_test', 'tornado.test.httpclient_test', 'tornado.test.httpserver_test', 'tornado.test.httputil_test',
TEST_MODULES = [ 'tornado.test.curl_httpclient_test', 'tornado.test.escape_test', 'tornado.test.gen_test', 'tornado.test.http1connection_test', 'tornado.test.httpclient_test', 'tornado.test.httpserver_test', 'tornado.test.httputil_test',
import time from django.conf import settings from django.db.backends.base.creation import BaseDatabaseCreation from django.db.utils import DatabaseError from django.utils.functional import cached_property from django.utils.six.moves import input TEST_DATABASE_PREFIX = 'test_' PASSWORD = 'Im_a_lumberjack' class Datab...
import time from django.conf import settings from django.db.backends.base.creation import BaseDatabaseCreation from django.db.utils import DatabaseError from django.utils.crypto import get_random_string from django.utils.functional import cached_property from django.utils.six.moves import input TEST_DATABASE_PREFIX = ...
class DatabaseCreation(BaseDatabaseCreation): ] # Ignore "user already exists" error when keepdb is on acceptable_ora_err = 'ORA-01920' if keepdb else None self._execute_allow_fail_statements(cursor, statements, parameters, verbosity, acceptable_ora_err) # Most test-suites can be...
class DatabaseCreation(BaseDatabaseCreation): ] # Ignore "user already exists" error when keepdb is on acceptable_ora_err = 'ORA-01920' if keepdb else None success = self._execute_allow_fail_statements(cursor, statements, parameters, verbosity, acceptable_ora_err) # If the passwo...
class DatabaseCreation(BaseDatabaseCreation): """ settings_dict = self.connection.settings_dict val = settings_dict['TEST'].get(key, default) if val is None: val = TEST_DATABASE_PREFIX + settings_dict[prefixed] return val
class DatabaseCreation(BaseDatabaseCreation): """ settings_dict = self.connection.settings_dict val = settings_dict['TEST'].get(key, default) if val is None and prefixed: val = TEST_DATABASE_PREFIX + settings_dict[prefixed] return val
class DatabaseCreation(BaseDatabaseCreation): return self._test_settings_get('USER', prefixed='USER') def _test_database_passwd(self): return self._test_settings_get('PASSWORD', default=PASSWORD) def _test_database_tblspace(self): return self._test_settings_get('TBLSPACE', prefixed='US...
class DatabaseCreation(BaseDatabaseCreation): return self._test_settings_get('USER', prefixed='USER') def _test_database_passwd(self): password = self._test_settings_get('PASSWORD') if password is None and self._test_user_create(): # Oracle passwords are limited to 30 chars and ...
to the w3lib.url module. Always import those from there instead. """ import posixpath import re from six.moves.urllib.parse import (ParseResult, urlunparse, urldefrag, urlparse, parse_qsl, urlencode, unquote) # scrapy.utils.url was moved to w3lib....
to the w3lib.url module. Always import those from there instead. """ import posixpath import re import six from six.moves.urllib.parse import (ParseResult, urlunparse, urldefrag, urlparse, parse_qsl, urlencode, quote, unquote) if six.PY3: from ...
def url_has_any_extension(url, extensions): return posixpath.splitext(parse_url(url).path)[1].lower() in extensions def canonicalize_url(url, keep_blank_values=True, keep_fragments=False, encoding=None): """Canonicalize the given url by applying the following procedures: - sort query...
def url_has_any_extension(url, extensions): return posixpath.splitext(parse_url(url).path)[1].lower() in extensions def _safe_ParseResult(parts, encoding='utf8', path_encoding='utf8'): return ( to_native_str(parts.scheme), to_native_str(parts.netloc.encode('idna')), # default encoding...
def parse_url(url, encoding=None): """ if isinstance(url, ParseResult): return url return urlparse(to_native_str(url, encoding)) def escape_ajax(url):
def parse_url(url, encoding=None): """ if isinstance(url, ParseResult): return url return urlparse(to_unicode(url, encoding)) if six.PY3: from urllib.parse import _coerce_args, unquote_to_bytes def parse_qsl_to_bytes(qs, keep_blank_values=False, strict_parsing=False): """Parse a q...
import unittest import six from scrapy.spiders import Spider from scrapy.utils.url import (url_is_from_any_domain, url_is_from_spider, canonicalize_url, add_http_if_no_scheme, guess_scheme) __doctests__ = ['scrapy.utils.url']
import unittest import six from six.moves.urllib.parse import urlparse from scrapy.spiders import Spider from scrapy.utils.url import (url_is_from_any_domain, url_is_from_spider, canonicalize_url, add_http_if_no_scheme, guess_scheme, parse_url) __doctests__...
class CanonicalizeUrlTest(unittest.TestCase): self.assertEqual(canonicalize_url("http://www.example.com/do?q=a%20space&a=1"), "http://www.example.com/do?a=1&q=a+space") @unittest.skipUnless(six.PY2, "TODO") def test_normalize_percent_encoding_in_paths(self): ...
class CanonicalizeUrlTest(unittest.TestCase): self.assertEqual(canonicalize_url("http://www.example.com/do?q=a%20space&a=1"), "http://www.example.com/do?a=1&q=a+space") def test_canonicalize_url_unicode_path(self): self.assertEqual(canonicalize_url(u"http:/...
class CanonicalizeUrlTest(unittest.TestCase): "http://www.example.com/a%20do%C2%A3.html?a=1") def test_non_ascii_percent_encoding_in_query_arguments(self): self.assertEqual(canonicalize_url(u"http://www.example.com/do?price=\xa3500&a=5&z=3"), ...
class CanonicalizeUrlTest(unittest.TestCase): "http://www.example.com/a%20do%C2%A3.html?a=1") def test_non_ascii_percent_encoding_in_query_arguments(self): self.assertEqual(canonicalize_url(u"http://www.example.com/do?price=£500&a=5&z=3"), ...
class CanonicalizeUrlTest(unittest.TestCase): "http://www.simplybedrooms.com/White-Bedroom-Furniture/Bedroom-Mirror:-Josephine-Cheval-Mirror.html"), "http://www.simplybedrooms.com/White-Bedroom-Furniture/Bedroom-Mirror:-Josephine-Cheval-Mirror.html") @unittest.skipUnless(six.PY2, "TODO") ...
class CanonicalizeUrlTest(unittest.TestCase): "http://www.simplybedrooms.com/White-Bedroom-Furniture/Bedroom-Mirror:-Josephine-Cheval-Mirror.html"), "http://www.simplybedrooms.com/White-Bedroom-Furniture/Bedroom-Mirror:-Josephine-Cheval-Mirror.html") def test_safe_characters_unicode(self): ...
class CanonicalizeUrlTest(unittest.TestCase): self.assertEqual(canonicalize_url("http://www.EXAMPLE.com/"), "http://www.example.com/") def test_quoted_slash_and_question_sign(self): self.assertEqual(canonicalize_url("http://foo.com/AC%2FDC+rocks%3f/?yeah=1"...
class CanonicalizeUrlTest(unittest.TestCase): self.assertEqual(canonicalize_url("http://www.EXAMPLE.com/"), "http://www.example.com/") def test_canonicalize_idns(self): self.assertEqual(canonicalize_url(u'http://www.bücher.de?q=bücher'), ...
class DatabaseFeatures(BaseDatabaseFeatures): only_supports_unbounded_with_preceding_and_following = True supports_aggregate_filter_clause = True supported_explain_formats = {"JSON", "TEXT", "XML", "YAML"} validates_explain_options = False # A query will error on invalid options. supports_deferrabl...
class DatabaseFeatures(BaseDatabaseFeatures): only_supports_unbounded_with_preceding_and_following = True supports_aggregate_filter_clause = True supported_explain_formats = {"JSON", "TEXT", "XML", "YAML"} supports_deferrable_unique_constraints = True has_json_operators = True json_key_contains_...
from django.db.backends.utils import split_tzname_delta class DatabaseOperations(BaseDatabaseOperations): cast_char_field_without_max_length = "varchar" explain_prefix = "EXPLAIN" cast_data_types = { "AutoField": "integer", "BigAutoField": "bigint",
from django.db.backends.utils import split_tzname_delta class DatabaseOperations(BaseDatabaseOperations): cast_char_field_without_max_length = "varchar" explain_prefix = "EXPLAIN" explain_options = frozenset( [ "ANALYZE", "BUFFERS", "COSTS", "SETTINGS"...
class DatabaseOperations(BaseDatabaseOperations): return super().subtract_temporals(internal_type, lhs, rhs) def explain_query_prefix(self, format=None, **options): prefix = super().explain_query_prefix(format) extra = {} if format: extra["FORMAT"] = format if op...
class DatabaseOperations(BaseDatabaseOperations): return super().subtract_temporals(internal_type, lhs, rhs) def explain_query_prefix(self, format=None, **options): extra = {} # Normalize options. if options: options = { name.upper(): "true" if value else...
__all__ = ["Query", "RawQuery"] # SQL comments are forbidden in column aliases. FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(r"['`\"\]\[;\s]|--|/\*|\*/") def get_field_names_from_opts(opts): return set(
__all__ = ["Query", "RawQuery"] # SQL comments are forbidden in column aliases. FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(r"['`\"\]\[;\s]|--|/\*|\*/") # Inspired from # https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS EXPLAIN_OPTIONS_PATTERN = _lazy_re_compile(r"[\w\-]+") def g...
class Query(BaseExpression): def explain(self, using, format=None, **options): q = self.clone() q.explain_info = ExplainInfo(format, options) compiler = q.get_compiler(using=using) return "\n".join(compiler.explain_query())
class Query(BaseExpression): def explain(self, using, format=None, **options): q = self.clone() for option_name in options: if ( not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name) or "--" in option_name ): raise ValueError(f"In...
class ExplainTests(TestCase): @skipUnlessDBFeature("validates_explain_options") def test_unknown_options(self): with self.assertRaisesMessage(ValueError, "Unknown options: test, test2"): Tag.objects.all().explain(test=1, test2=1) def test_unknown_format(self): msg = "DOES NOT E...
class ExplainTests(TestCase): @skipUnlessDBFeature("validates_explain_options") def test_unknown_options(self): with self.assertRaisesMessage(ValueError, "Unknown options: TEST, TEST2"): Tag.objects.all().explain(**{"TEST": 1, "TEST2": 1}) def test_unknown_format(self): msg = "...
class ExplainTests(TestCase): option = "{} {}".format(name.upper(), "true" if value else "false") self.assertIn(option, captured_queries[0]["sql"]) @unittest.skipUnless(connection.vendor == "mysql", "MySQL specific") def test_mysql_text_to_traditional(self): # En...
class ExplainTests(TestCase): option = "{} {}".format(name.upper(), "true" if value else "false") self.assertIn(option, captured_queries[0]["sql"]) def test_option_sql_injection(self): qs = Tag.objects.filter(name="test") options = {"SUMMARY true) SELECT 1; -...
class ActionBase(with_metaclass(ABCMeta, object)): Create and return a temporary path on a remote box. ''' become_unprivileged = self._is_become_unprivileged() remote_tmp = self.get_shell_option('remote_tmp', default='~/.ansible/tmp') # deal with tmpdir creation basefil...
class ActionBase(with_metaclass(ABCMeta, object)): Create and return a temporary path on a remote box. ''' # Network connection plugins (network_cli, netconf, etc.) execute on the controller, rather than the remote host. # As such, we want to avoid using remote_user for paths as remote...
class ActionBase(with_metaclass(ABCMeta, object)): elif u'No space left on device' in result['stderr']: output = result['stderr'] else: output = ('Authentication or permission failure. ' 'In some cases, you may have been able to authentic...
class ActionBase(with_metaclass(ABCMeta, object)): elif u'No space left on device' in result['stderr']: output = result['stderr'] else: output = ('Failed to create temporary directory.' 'In some cases, you may have been able to authentica...
import random import re import time import ansible.constants as C from ansible.errors import AnsibleError from ansible.module_utils.six import text_type from ansible.module_utils.six.moves import shlex_quote
import random import re import time from ansible.errors import AnsibleError from ansible.module_utils.six import text_type from ansible.module_utils.six.moves import shlex_quote
class ShellBase(AnsiblePlugin): except KeyError: pass def env_prefix(self, **kwargs): return ' '.join(['%s=%s' % (k, shlex_quote(text_type(v))) for k, v in kwargs.items()])
class ShellBase(AnsiblePlugin): except KeyError: pass @staticmethod def _generate_temp_dir_name(): return 'ansible-tmp-%s-%s-%s' % (time.time(), os.getpid(), random.randint(0, 2**48)) def env_prefix(self, **kwargs): return ' '.join(['%s=%s' % (k, shlex_quote(text_type(v...
class ShellBase(AnsiblePlugin): def mkdtemp(self, basefile=None, system=False, mode=0o700, tmpdir=None): if not basefile: basefile = 'ansible-tmp-%s-%s' % (time.time(), random.randint(0, 2**48)) # When system is specified we have to create this in a directory where # other user...
class ShellBase(AnsiblePlugin): def mkdtemp(self, basefile=None, system=False, mode=0o700, tmpdir=None): if not basefile: basefile = self.__class__._generate_temp_dir_name() # When system is specified we have to create this in a directory where # other users can read and access...
class ShellBase(AnsiblePlugin): # passed in tmpdir if it is valid or the first one from the setting if not. if system: tmpdir = tmpdir.rstrip('/') if tmpdir in self.get_option('system_tmpdirs'): basetmpdir = tmpdir
class ShellBase(AnsiblePlugin): # passed in tmpdir if it is valid or the first one from the setting if not. if system: if tmpdir: tmpdir = tmpdir.rstrip('/') if tmpdir in self.get_option('system_tmpdirs'): basetmpdir = tmpdir
class ShellBase(AnsiblePlugin): basetmp = self.join_path(basetmpdir, basefile) cmd = 'mkdir -p %s echo %s %s' % (self._SHELL_SUB_LEFT, basetmp, self._SHELL_SUB_RIGHT) cmd += ' %s echo %s=%s echo %s %s' % (self._SHELL_AND, basefile, self._SHELL_SUB_LEFT, basetmp, self._SHELL_SUB_RIGHT) ...
class ShellBase(AnsiblePlugin): basetmp = self.join_path(basetmpdir, basefile) # use mkdir -p to ensure parents exist, but mkdir fullpath to ensure last one is created by us cmd = 'mkdir -p %s echo %s %s' % (self._SHELL_SUB_LEFT, basetmpdir, self._SHELL_SUB_RIGHT) cmd += '%s mkdir %s' ...
class ShellModule(ShellBase): def mkdtemp(self, basefile=None, system=False, mode=None, tmpdir=None): # Windows does not have an equivalent for the system temp files, so # the param is ignored basefile = self._escape(self._unquote(basefile)) basetmpdir = tmpdir if tmpdir else self.ge...
class ShellModule(ShellBase): def mkdtemp(self, basefile=None, system=False, mode=None, tmpdir=None): # Windows does not have an equivalent for the system temp files, so # the param is ignored if not basefile: basefile = self.__class__._generate_temp_dir_name() basefile =...
def is_string_dtype(arr_or_dtype) -> bool: """ These have kind = "O" but aren't string dtypes so need to be explicitly excluded """ is_excluded_checks = (is_period_dtype, is_interval_dtype) return any(is_excluded(dtype) for is_excluded in is_excluded_checks) return _is_dtype...
def is_string_dtype(arr_or_dtype) -> bool: """ These have kind = "O" but aren't string dtypes so need to be explicitly excluded """ is_excluded_checks = (is_period_dtype, is_interval_dtype, is_categorical_dtype) return any(is_excluded(dtype) for is_excluded in is_excluded_checks)...
class TestCategoricalDtype(Base): result = str(Categorical(DatetimeIndex([])).categories.dtype) assert result == expected class TestDatetimeTZDtype(Base): @pytest.fixture
class TestCategoricalDtype(Base): result = str(Categorical(DatetimeIndex([])).categories.dtype) assert result == expected def test_not_string(self): # though CategoricalDtype has object kind, it cannot be string assert not is_string_dtype(CategoricalDtype()) class TestDatetimeTZDt...
def _connect(self): def _create_database(self, last_upgrade_to_run): """ Make sure that the database is created and sets the file permissions. This should be done before storing any sensitive data in it. """ # Create the tables in the database conn = self._connect() ...
def _connect(self): def _create_database(self, last_upgrade_to_run): """ Make sure that the database is created and has appropriate file permissions. This should be done before storing any sensitive data in it. """ # Prepare a file fd = os.open( self.file...
def _create_database(self, last_upgrade_to_run): finally: conn.close() # Set the file permissions os.chmod(self.filename, stat.S_IRUSR | stat.S_IWUSR) def _create_tables(self, conn, last_upgrade_to_run): conn.execute( """
def _create_database(self, last_upgrade_to_run): finally: conn.close() def _create_tables(self, conn, last_upgrade_to_run): conn.execute( """
import os import platform import shutil import tempfile import pytest
import os import platform import shutil import stat import tempfile import pytest
def setUp(self, request): os.unlink(self.db_path) except OSError: pass self.home = tempfile.mkdtemp() yield for cleanup_method in [lambda: os.unlink(self.db_path), lambda: shutil.rmtree(self.home)]: try: cleanup_method exce...
def setUp(self, request): os.unlink(self.db_path) except OSError: pass self.test_home = tempfile.mkdtemp() yield for cleanup_method in [ lambda: os.unlink(self.db_path), lambda: shutil.rmtree(self.test_home) ]: try: ...
def _make_sqlite_account_info(self, env=None, last_upgrade_to_run=None): :param dict env: Override Environment variables. """ # Override HOME to ensure hermetic tests with mock.patch('os.environ', env or {'HOME': self.home}): return SqliteAccountInfo( file_nam...
def _make_sqlite_account_info(self, env=None, last_upgrade_to_run=None): :param dict env: Override Environment variables. """ # Override HOME to ensure hermetic tests with mock.patch('os.environ', env or {'HOME': self.test_home}): return SqliteAccountInfo( fil...
def _make_sqlite_account_info(self, env=None, last_upgrade_to_run=None): def test_uses_default(self): account_info = self._make_sqlite_account_info( env={ 'HOME': self.home, 'USERPROFILE': self.home, } ) actual_path = os.path.abspath(ac...
def _make_sqlite_account_info(self, env=None, last_upgrade_to_run=None): def test_uses_default(self): account_info = self._make_sqlite_account_info( env={ 'HOME': self.test_home, 'USERPROFILE': self.test_home, } ) actual_path = os.path....
def test_uses_xdg_config_home(self, apiver): def test_uses_existing_file_and_ignores_xdg(self): with WindowsSafeTempDir() as d: default_db_file_location = os.path.join(self.home, '.b2_account_info') open(default_db_file_location, 'a').close() account_info = self._make_sq...
def test_uses_xdg_config_home(self, apiver): def test_uses_existing_file_and_ignores_xdg(self): with WindowsSafeTempDir() as d: default_db_file_location = os.path.join(self.test_home, '.b2_account_info') open(default_db_file_location, 'a').close() account_info = self._ma...
def test_account_info_env_var_overrides_xdg_config_home(self): with WindowsSafeTempDir() as d: account_info = self._make_sqlite_account_info( env={ 'HOME': self.home, 'USERPROFILE': self.home, XDG_CONFIG_HOME_ENV_VAR: d, ...
def test_account_info_env_var_overrides_xdg_config_home(self): with WindowsSafeTempDir() as d: account_info = self._make_sqlite_account_info( env={ 'HOME': self.test_home, 'USERPROFILE': self.test_home, XDG_CONFIG_HOME_ENV_V...
class TestUtil(unittest.TestCase): d = json.loads(stripped) self.assertEqual(d, [{"id": "532cb", "x": 3}]) def test_uppercase_escape(self): self.assertEqual(uppercase_escape('aä'), 'aä') self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
class TestUtil(unittest.TestCase): d = json.loads(stripped) self.assertEqual(d, [{"id": "532cb", "x": 3}]) stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc') d = json.loads(stripped) self.assertEqual(d, {'STATUS': 'OK'}) def test_uppercase_escape(self): ...
from ..utils import ( unified_strdate, parse_duration, qualities, url_basename, )
from ..utils import ( unified_strdate, parse_duration, qualities, strip_jsonp, url_basename, )
class NPOIE(InfoExtractor): 'http://e.omroep.nl/metadata/aflevering/%s' % video_id, video_id, # We have to remove the javascript callback transform_source=lambda j: re.sub(r'parseMetadata\((.*?)\);\n//.*$', r'\1', j) ) token_page = self._download_webpage( ...
class NPOIE(InfoExtractor): 'http://e.omroep.nl/metadata/aflevering/%s' % video_id, video_id, # We have to remove the javascript callback transform_source=strip_jsonp, ) token_page = self._download_webpage( 'http://ida.omroep.nl/npoplayer/i.js'...