buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class Orthogonal(Initializer): rng = np.random if self.seed is not None: rng = np.random.RandomState(self.seed) a = rng.normal(0.0, 1.0, flat_shape) u, _, v = np.linalg.svd(a, full_matrices=False) # Pick the one with the correct shape.
class Orthogonal(Initializer): rng = np.random if self.seed is not None: rng = np.random.RandomState(self.seed) self.seed += 1 a = rng.normal(0.0, 1.0, flat_shape) u, _, v = np.linalg.svd(a, full_matrices=False) # Pick the one with the correct shape.
class TestBackend(object): else: assert_list_pairwise(v_list, shape=False, allclose=False, itself=True) def test_print_tensor(self): check_single_tensor_operation('print_tensor', (), WITH_NP) check_single_tensor_operation('print_tensor', (2,), WITH_NP) check_single_tenso...
class TestBackend(object): else: assert_list_pairwise(v_list, shape=False, allclose=False, itself=True) def test_print_tensor(self, capsys): for k in [KTH, KTF]: x = k.placeholder((1, 1)) y = k.print_tensor(x, 'msg') fn = k.function([x], [y]) ...
class TestBackend(object): def test_log(self): check_single_tensor_operation('log', (4, 2), WITH_NP) @pytest.mark.skipif(K.backend() == 'theano', reason='theano returns tuples for update ops') def test_update_add(self): x = np.random.randn(3, 4) x_var = K.var...
class TestBackend(object): def test_log(self): check_single_tensor_operation('log', (4, 2), WITH_NP) @pytest.mark.skipif(K.backend() == 'theano', reason='theano returns tuples for update ops') def test_update(self): x = np.ones((3, 4)) x_var = K.variable(x) ...
class TestBackend(object): assert output == [21.] assert K.get_session().run(fetches=[x, y]) == [30., 40.] @pytest.mark.skipif(K.backend() != 'tensorflow', reason='Uses the `options` and `run_metadata` arguments.') def test_function_tf_run_options_with_run_metadata(self)...
class TestBackend(object): assert output == [21.] assert K.get_session().run(fetches=[x, y]) == [30., 40.] @pytest.mark.skipif(K.backend() != 'tensorflow' or not KTF._is_tf_1(), reason='Uses the `options` and `run_metadata` arguments.') def test_function_tf_run_options_w...
class TestBackend(object): assert_allclose(y1, y2, atol=1e-05) def test_random_normal(self): # test standard normal as well as a normal with a different set of parameters for mean, std in [(0., 1.), (-10., 5.)]: rand = K.eval(K.random_normal((300, 200), ...
class TestBackend(object): assert_allclose(y1, y2, atol=1e-05) def test_random_normal(self): # TODO: make this a parameterized test for mean, std in [(0., 1.), (-10., 5.)]: rand = K.eval(K.random_normal((200, 200), mean=mean, ...
class TestBackend(object): np.asarray([-5., -4., 0., 4., 9.], dtype=np.float32)) @pytest.mark.skipif(K.backend() != 'tensorflow' or KTF._is_tf_1(), reason='This test is for tensorflow parallelism.') def test_tensorflow_ses...
class TestBackend(object): np.asarray([-5., -4., 0., 4., 9.], dtype=np.float32)) if __name__ == '__main__': pytest.main([__file__])
def test_one(tensor_shape): target_mean=1., target_max=1.) if __name__ == '__main__': pytest.main([__file__])
def test_one(tensor_shape): target_mean=1., target_max=1.) @pytest.mark.parametrize('initializer', [initializers.orthogonal, initializers.uniform, initializers.normal, initializers.truncated_normal, ...
from pandas.core.dtypes.common import ( is_datetime64_dtype, is_datetime64tz_dtype, is_datetime_or_timedelta_dtype, is_integer, is_list_like, is_scalar, is_timedelta64_dtype,
from pandas.core.dtypes.common import ( is_datetime64_dtype, is_datetime64tz_dtype, is_datetime_or_timedelta_dtype, is_extension_array_dtype, is_integer, is_integer_dtype, is_list_like, is_scalar, is_timedelta64_dtype,
def cut( x = _preprocess_for_cut(x) x, dtype = _coerce_to_type(x) if not np.iterable(bins): if is_scalar(bins) and bins < 1: raise ValueError("`bins` should be a positive integer.")
def cut( x = _preprocess_for_cut(x) x, dtype = _coerce_to_type(x) # To support cut(IntegerArray), we convert to object dtype with NaN # Will properly support in the future. # https://github.com/pandas-dev/pandas/pull/31290 if is_extension_array_dtype(x.dtype) and is_integer_dtype(x.dtype): ...
def test_value_counts_na(): tm.assert_series_equal(result, expected) # TODO(jreback) - these need testing / are broken # shift
def test_value_counts_na(): tm.assert_series_equal(result, expected) @pytest.mark.parametrize("bins", [3, [0, 5, 15]]) @pytest.mark.parametrize("right", [True, False]) @pytest.mark.parametrize("include_lowest", [True, False]) def test_cut(bins, right, include_lowest): a = np.random.randint(0, 10, size=50).ast...
class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray) if is_datetime64_any_dtype(other) and is_timedelta64_dtype(self.dtype): # ndarray[datetime64] cannot be subtracted from self, so # we need to wrap in DatetimeArray/Index and flip the operation if...
class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray) if is_datetime64_any_dtype(other) and is_timedelta64_dtype(self.dtype): # ndarray[datetime64] cannot be subtracted from self, so # we need to wrap in DatetimeArray/Index and flip the operation if...
class TestTimedeltaArraylikeAddSubOps: result = other + idx tm.assert_equal(result, expected) def test_td64arr_add_sub_timestamp(self, box_with_array): # GH#11925 ts = Timestamp("2012-01-01") # TODO: parametrize over types of datetime scalar? tdi = timedelta_range("...
class TestTimedeltaArraylikeAddSubOps: result = other + idx tm.assert_equal(result, expected) @pytest.mark.parametrize( "ts", [ Timestamp("2012-01-01"), Timestamp("2012-01-01").to_pydatetime(), Timestamp("2012-01-01").to_datetime64(), ], ...
def load_inputs_from_input_arg_string(inputs_str, input_exprs_str, input_examples = preprocess_input_examples_arg_string(input_examples_str) for input_tensor_key, (filename, variable_name) in inputs.items(): data = np.load(file_io.FileIO(filename, mode='rb')) # When a variable_name key is specified for th...
def load_inputs_from_input_arg_string(inputs_str, input_exprs_str, input_examples = preprocess_input_examples_arg_string(input_examples_str) for input_tensor_key, (filename, variable_name) in inputs.items(): data = np.load(file_io.FileIO(filename, mode='rb'), allow_pickle=True) # When a variable_name key ...
from youtube_dl.utils import ( xpath_with_ns, parse_iso8601, strip_jsonp, ) if sys.version_info < (3, 0):
from youtube_dl.utils import ( xpath_with_ns, parse_iso8601, strip_jsonp, uppercase_escape, ) if sys.version_info < (3, 0):
class TestUtil(unittest.TestCase): d = json.loads(stripped) self.assertEqual(d, [{"id": "532cb", "x": 3}]) if __name__ == '__main__': unittest.main()
class TestUtil(unittest.TestCase): d = json.loads(stripped) self.assertEqual(d, [{"id": "532cb", "x": 3}]) def test_uppercase_escpae(self): self.assertEqual(uppercase_escape(u'aä'), u'aä') self.assertEqual(uppercase_escape(u'\\U0001d550'), u'𝕐') if __name__ == '__main__': unit...
# -*- coding: utf-8 -*- import calendar import contextlib import ctypes import datetime
# -*- coding: utf-8 -*- import calendar import codecs import contextlib import ctypes import datetime
class PagedList(object): def uppercase_escape(s): return re.sub( r'\\U[0-9a-fA-F]{8}', lambda m: m.group(0).decode('unicode-escape'), s) try: struct.pack(u'!I', 0)
class PagedList(object): def uppercase_escape(s): unicode_escape = codecs.getdecoder('unicode_escape') return re.sub( r'\\U[0-9a-fA-F]{8}', lambda m: unicode_escape(m.group(0))[0], s) try: struct.pack(u'!I', 0)
from asgiref.local import Local from django.conf import settings from django.core import signals from django.core.cache.backends.base import ( BaseCache, CacheKeyWarning, InvalidCacheBackendError, ) from django.utils.module_loading import import_string __all__ = [ 'cache', 'caches', 'DEFAULT_CACHE_ALIAS', 'Inv...
from asgiref.local import Local from django.conf import settings from django.core import signals from django.core.cache.backends.base import ( BaseCache, CacheKeyWarning, InvalidCacheBackendError, InvalidCacheKey, ) from django.utils.module_loading import import_string __all__ = [ 'cache', 'caches', 'DEFAULT_C...
class CacheKeyWarning(RuntimeWarning): pass # Stub class to ensure not passing in a `timeout` argument results in # the default timeout DEFAULT_TIMEOUT = object()
class CacheKeyWarning(RuntimeWarning): pass class InvalidCacheKey(ValueError): pass # Stub class to ensure not passing in a `timeout` argument results in # the default timeout DEFAULT_TIMEOUT = object()
class BaseCache: backend. This encourages (but does not force) writing backend-portable cache code. """ if len(key) > MEMCACHE_MAX_KEY_LENGTH: warnings.warn( 'Cache key will cause errors if used with memcached: %r ' '(longer than %s)' % (key, M...
class BaseCache: backend. This encourages (but does not force) writing backend-portable cache code. """ for warning in memcache_key_warnings(key): warnings.warn(warning, CacheKeyWarning) def incr_version(self, key, delta=1, version=None): """
class BaseCache: def close(self, **kwargs): """Close the cache connection""" pass
class BaseCache: def close(self, **kwargs): """Close the cache connection""" pass def memcache_key_warnings(key): if len(key) > MEMCACHE_MAX_KEY_LENGTH: yield ( 'Cache key will cause errors if used with memcached: %r ' '(longer than %s)' % (key, MEMCACHE_MAX_KEY...
import pickle import re import time from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache from django.utils.functional import cached_property
import pickle import re import time from django.core.cache.backends.base import ( DEFAULT_TIMEOUT, BaseCache, InvalidCacheKey, memcache_key_warnings, ) from django.utils.functional import cached_property
class BaseMemcachedCache(BaseCache): def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_key(key, version=version) return self._cache.add(key, value, self.get_backend_timeout(timeout)) def get(self, key, default=None, version=None): key = self.make_key(key...
class BaseMemcachedCache(BaseCache): def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_key(key, version=version) self.validate_key(key) return self._cache.add(key, value, self.get_backend_timeout(timeout)) def get(self, key, default=None, version=None): ...
class BaseMemcachedCache(BaseCache): def incr(self, key, delta=1, version=None): key = self.make_key(key, version=version) # memcached doesn't support a negative delta if delta < 0: return self._cache.decr(key, -delta)
class BaseMemcachedCache(BaseCache): def incr(self, key, delta=1, version=None): key = self.make_key(key, version=version) self.validate_key(key) # memcached doesn't support a negative delta if delta < 0: return self._cache.decr(key, -delta)
class BaseMemcachedCache(BaseCache): def decr(self, key, delta=1, version=None): key = self.make_key(key, version=version) # memcached doesn't support a negative delta if delta < 0: return self._cache.incr(key, -delta)
class BaseMemcachedCache(BaseCache): def decr(self, key, delta=1, version=None): key = self.make_key(key, version=version) self.validate_key(key) # memcached doesn't support a negative delta if delta < 0: return self._cache.incr(key, -delta)
class BaseMemcachedCache(BaseCache): original_keys = {} for key, value in data.items(): safe_key = self.make_key(key, version=version) safe_data[safe_key] = value original_keys[safe_key] = key failed_keys = self._cache.set_multi(safe_data, self.get_backend_tim...
class BaseMemcachedCache(BaseCache): original_keys = {} for key, value in data.items(): safe_key = self.make_key(key, version=version) self.validate_key(safe_key) safe_data[safe_key] = value original_keys[safe_key] = key failed_keys = self._cache.s...
class BaseMemcachedCache(BaseCache): def clear(self): self._cache.flush_all() class MemcachedCache(BaseMemcachedCache): "An implementation of a cache binding using python-memcached"
class BaseMemcachedCache(BaseCache): def clear(self): self._cache.flush_all() def validate_key(self, key): for warning in memcache_key_warnings(key): raise InvalidCacheKey(warning) class MemcachedCache(BaseMemcachedCache): "An implementation of a cache binding using python-mem...
from unittest import mock from django.conf import settings from django.core import management, signals from django.core.cache import ( DEFAULT_CACHE_ALIAS, CacheKeyWarning, cache, caches, ) from django.core.cache.backends.base import InvalidCacheBackendError from django.core.cache.utils import make_template_fragmen...
from unittest import mock from django.conf import settings from django.core import management, signals from django.core.cache import ( DEFAULT_CACHE_ALIAS, CacheKeyWarning, InvalidCacheKey, cache, caches, ) from django.core.cache.backends.base import InvalidCacheBackendError from django.core.cache.utils import make...
class BaseCacheTests: def _perform_invalid_key_test(self, key, expected_warning): """ All the builtin backends (except memcached, see below) should warn on keys that would be refused by memcached. This encourages portable caching code without making it too difficult to use productio...
class BaseCacheTests: def _perform_invalid_key_test(self, key, expected_warning): """ All the builtin backends should warn (except memcached that should error) on keys that would be refused by memcached. This encourages portable caching code without making it too difficult to use pr...
class BaseMemcachedTests(BaseCacheTests): with self.settings(CACHES={'default': params}): self.assertEqual(cache._servers, ['server1.tld', 'server2:11211']) def test_invalid_key_characters(self): """ On memcached, we don't introduce a duplicate key validation ...
class BaseMemcachedTests(BaseCacheTests): with self.settings(CACHES={'default': params}): self.assertEqual(cache._servers, ['server1.tld', 'server2:11211']) def _perform_invalid_key_test(self, key, expected_warning): """ Whilst other backends merely warn, memcach...
class PyLibMCCacheTests(BaseMemcachedTests, TestCase): # libmemcached manages its own connections. should_disconnect_on_close = False # By default, pylibmc/libmemcached don't verify keys client-side and so # this test triggers a server-side bug that causes later tests to fail # (#19914). The `verif...
class PyLibMCCacheTests(BaseMemcachedTests, TestCase): # libmemcached manages its own connections. should_disconnect_on_close = False @override_settings(CACHES=caches_setting_for_tests( base=PyLibMCCache_params, exclude=memcached_excluded_caches,
import warnings from datetime import datetime from hashlib import sha256 from typing import List, Optional from unpaddedbase64 import encode_base64
import warnings from datetime import datetime from hashlib import sha256 from typing import List, Optional, Pattern from unpaddedbase64 import encode_base64
def read_config(self, config: dict, config_dir_path: str, **kwargs): fed_whitelist_entries = [] # Support globs (*) in whitelist values self.federation_certificate_verification_whitelist = [] # type: List[str] for entry in fed_whitelist_entries: try: ent...
def read_config(self, config: dict, config_dir_path: str, **kwargs): fed_whitelist_entries = [] # Support globs (*) in whitelist values self.federation_certificate_verification_whitelist = [] # type: List[Pattern] for entry in fed_whitelist_entries: try: ...
from synapse.events import EventBase from synapse.types import UserID from synapse.util.caches.lrucache import LruCache logger = logging.getLogger(__name__)
from synapse.events import EventBase from synapse.types import UserID from synapse.util import glob_to_regex, re_word_boundary from synapse.util.caches.lrucache import LruCache logger = logging.getLogger(__name__)
def _contains_display_name(self, display_name: str) -> bool: r = regex_cache.get((display_name, False, True), None) if not r: r1 = re.escape(display_name) r1 = _re_word_boundary(r1) r = re.compile(r1, flags=re.IGNORECASE) regex_cache[(display_name, False, ...
def _contains_display_name(self, display_name: str) -> bool: r = regex_cache.get((display_name, False, True), None) if not r: r1 = re.escape(display_name) r1 = re_word_boundary(r1) r = re.compile(r1, flags=re.IGNORECASE) regex_cache[(display_name, False, T...
def _glob_matches(glob: str, value: str, word_boundary: bool = False) -> bool: try: r = regex_cache.get((glob, True, word_boundary), None) if not r: r = _glob_to_re(glob, word_boundary) regex_cache[(glob, True, word_boundary)] = r return bool(r.search(value)) exce...
def _glob_matches(glob: str, value: str, word_boundary: bool = False) -> bool: try: r = regex_cache.get((glob, True, word_boundary), None) if not r: r = glob_to_regex(glob, word_boundary) regex_cache[(glob, True, word_boundary)] = r return bool(r.search(value)) ex...
def _glob_matches(glob: str, value: str, word_boundary: bool = False) -> bool: return False def _glob_to_re(glob: str, word_boundary: bool) -> Pattern: """Generates regex for a given glob. Args: glob word_boundary: Whether to match against word boundaries or entire string. """ ...
def _glob_matches(glob: str, value: str, word_boundary: bool = False) -> bool: return False def _flatten_dict( d: Union[EventBase, dict], prefix: Optional[List[str]] = None,
import json import logging import re import attr from frozendict import frozendict
import json import logging import re from typing import Pattern import attr from frozendict import frozendict
logger = logging.getLogger(__name__) def _reject_invalid_json(val): """Do not allow Infinity, -Infinity, or NaN values in JSON.""" raise ValueError("Invalid JSON value: '%s'" % val)
logger = logging.getLogger(__name__) _WILDCARD_RUN = re.compile(r"([\?\*]+)") def _reject_invalid_json(val): """Do not allow Infinity, -Infinity, or NaN values in JSON.""" raise ValueError("Invalid JSON value: '%s'" % val)
def log_failure(failure, msg, consumeErrors=True): return failure def glob_to_regex(glob): """Converts a glob to a compiled regex object. The regex is anchored at the beginning and end of the string. Args: glob (str) Returns: re.RegexObject """ res = "" for c in ...
def log_failure(failure, msg, consumeErrors=True): return failure def glob_to_regex(glob: str, word_boundary: bool = False) -> Pattern: """Converts a glob to a compiled regex object. Args: glob: pattern to match word_boundary: If True, the pattern will be allowed to match at word boun...
def test_block_ip_literals(self): self.assertFalse(server_matches_acl_event("[1:2::]", e)) self.assertTrue(server_matches_acl_event("1:2:3:4", e)) class StateQueryTests(unittest.FederatingHomeserverTestCase):
def test_block_ip_literals(self): self.assertFalse(server_matches_acl_event("[1:2::]", e)) self.assertTrue(server_matches_acl_event("1:2:3:4", e)) def test_wildcard_matching(self): e = _create_acl_event({"allow": ["good*.com"]}) self.assertTrue( server_matches_acl_event(...
# See the License for the specific language governing permissions and # limitations under the License. from synapse.api.room_versions import RoomVersions from synapse.events import FrozenEvent from synapse.push import push_rule_evaluator
# See the License for the specific language governing permissions and # limitations under the License. from typing import Any, Dict from synapse.api.room_versions import RoomVersions from synapse.events import FrozenEvent from synapse.push import push_rule_evaluator
def test_display_name(self): # A display name with spaces should work fine. self.assertTrue(evaluator.matches(condition, "@user:test", "foo bar")) def test_no_body(self): """Not having a body shouldn't break the evaluator.""" evaluator = self._get_evaluator({})
def test_display_name(self): # A display name with spaces should work fine. self.assertTrue(evaluator.matches(condition, "@user:test", "foo bar")) def _assert_matches( self, condition: Dict[str, Any], content: Dict[str, Any], msg=None ) -> None: evaluator = self._get_evaluator(c...
class APIRouter(routing.Router): def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable:
class APIRouter(routing.Router): def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute( path, endpoint=endpoint, name=name, dependency_overrides_provider=self.dependency_overrides_pr...
from fastapi import APIRouter, FastAPI, WebSocket from fastapi.testclient import TestClient router = APIRouter()
from fastapi import APIRouter, Depends, FastAPI, WebSocket from fastapi.testclient import TestClient router = APIRouter()
async def routerindex(websocket: WebSocket): await websocket.close() app.include_router(router) app.include_router(prefix_router, prefix="/prefix")
async def routerindex(websocket: WebSocket): await websocket.close() async def ws_dependency(): return "Socket Dependency" @router.websocket("/router-ws-depends/") async def router_ws_decorator_depends( websocket: WebSocket, data=Depends(ws_dependency) ): await websocket.accept() await websocket...
def test_router2(): with client.websocket_connect("/router2") as websocket: data = websocket.receive_text() assert data == "Hello, router!"
def test_router2(): with client.websocket_connect("/router2") as websocket: data = websocket.receive_text() assert data == "Hello, router!" def test_router_ws_depends(): client = TestClient(app) with client.websocket_connect("/router-ws-depends/") as websocket: assert websocket.rec...
options: name: description: - Zone name. required: true path: description:
options: name: description: - Zone name. - A zone name must be unique name. - A zone name must begin with an alpha-numeric character. - The name can contain alpha-numeric characters, underbars I(_), hyphens I(-), and periods I(.). - The name cannot be longer than 64 characters. t...
EXAMPLES = ''' import os import platform import tempfile import time
EXAMPLES = ''' import os import platform import re import tempfile import time
class Zone(object): if int(self.os_minor) < 10: self.module.fail_json(msg='This module requires Solaris 10 or later') def configure(self): if not self.path: self.module.fail_json(msg='Missing required argument: path')
class Zone(object): if int(self.os_minor) < 10: self.module.fail_json(msg='This module requires Solaris 10 or later') match = re.match('^[a-zA-Z0-9][-_.a-zA-Z0-9]{0,62}$', self.name) if not match: self.module.fail_json(msg="Provided zone name is not a valid zone name. " ...
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 ...
def test_groupby_mean_no_overflow(): } ) assert df.groupby("user")["connections"].mean()["A"] == 3689348814740003840
def test_groupby_mean_no_overflow(): } ) assert df.groupby("user")["connections"].mean()["A"] == 3689348814740003840 @pytest.mark.parametrize( "values", [ { "a": [1, 1, 1, 2, 2, 2, 3, 3, 3], "b": [1, pd.NA, 2, 1, pd.NA, 2, 1, pd.NA, 2], }, {"a": ...
from typing import ( Callable, Collection, Dict, Generic, Iterable, Iterator,
from typing import ( Callable, Collection, Dict, Generator, Generic, Iterable, Iterator,
def generate_trailers_to_omit(line: Line, line_length: int) -> Iterator[Set[Leaf def get_future_imports(node: Node) -> Set[str]: """Return a set of __future__ imports in the file.""" imports = set() for child in node.children: if child.type != syms.simple_stmt: break
def generate_trailers_to_omit(line: Line, line_length: int) -> Iterator[Set[Leaf def get_future_imports(node: Node) -> Set[str]: """Return a set of __future__ imports in the file.""" imports: Set[str] = set() def get_imports_from_children(children: List[LN]) -> Generator[str, None, None]: for chil...
def get_future_imports(node: Node) -> Set[str]: module_name = first_child.children[1] if not isinstance(module_name, Leaf) or module_name.value != "__future__": break for import_from_child in first_child.children[3:]: if isinstance(import_from_child, L...
def get_future_imports(node: Node) -> Set[str]: module_name = first_child.children[1] if not isinstance(module_name, Leaf) or module_name.value != "__future__": break imports |= set(get_imports_from_children(first_child.children[3:])) else: break ...
#!/usr/bin/env python2 from __future__ import unicode_literals u'hello' U"hello"
#!/usr/bin/env python2 from __future__ import unicode_literals as _unicode_literals from __future__ import absolute_import from __future__ import print_function as lol, with_function u'hello' U"hello"
Ur"hello" #!/usr/bin/env python2 from __future__ import unicode_literals "hello" "hello"
Ur"hello" #!/usr/bin/env python2 from __future__ import unicode_literals as _unicode_literals from __future__ import absolute_import from __future__ import print_function as lol, with_function "hello" "hello"
class BlackTestCase(unittest.TestCase): self.assertEqual(set(), black.get_future_imports(node)) node = black.lib2to3_parse("from some.module import black\n") self.assertEqual(set(), black.get_future_imports(node)) def test_debug_visitor(self) -> None: source, _ = read_data("debug_vi...
class BlackTestCase(unittest.TestCase): self.assertEqual(set(), black.get_future_imports(node)) node = black.lib2to3_parse("from some.module import black\n") self.assertEqual(set(), black.get_future_imports(node)) node = black.lib2to3_parse( "from __future__ import unicode_li...
def gen_python_files_in_dir( """Generate all files under `path` whose paths are not excluded by the `exclude` regex, but are included by the `include` regex. `report` is where output about exclusions goes. """ assert root.is_absolute(), f"INTERNAL ERROR: `root` must be absolute but is {root}" f...
def gen_python_files_in_dir( """Generate all files under `path` whose paths are not excluded by the `exclude` regex, but are included by the `include` regex. Symbolic links pointing outside of the root directory are ignored. `report` is where output about exclusions goes. """ assert root.is_ab...
import sys from tempfile import TemporaryDirectory from typing import Any, BinaryIO, Generator, List, Tuple, Iterator import unittest from unittest.mock import patch from click import unstyle from click.testing import CliRunner
import sys from tempfile import TemporaryDirectory from typing import Any, BinaryIO, Generator, List, Tuple, Iterator import unittest from unittest.mock import patch, MagicMock from click import unstyle from click.testing import CliRunner
class BlackTestCase(unittest.TestCase): with self.assertRaises(AssertionError): black.assert_equivalent("{}", "None") if __name__ == "__main__": unittest.main(module="test_black")
class BlackTestCase(unittest.TestCase): with self.assertRaises(AssertionError): black.assert_equivalent("{}", "None") def test_symlink_out_of_root_directory(self) -> None: # prepare argumens path = MagicMock() root = THIS_DIR child = MagicMock() include =...
class Response(object_ref): """ if isinstance(url, Link): url = url.url url = self.urljoin(url) return Request(url, callback, method=method,
class Response(object_ref): """ if isinstance(url, Link): url = url.url elif url is None: raise ValueError("url can't be None") url = self.urljoin(url) return Request(url, callback, method=method,
class BaseResponseTest(unittest.TestCase): self._assert_followed_url(Link('http://example.com/foo'), 'http://example.com/foo') def test_follow_whitespace_url(self): self._assert_followed_url('foo ', 'http://example.com/foo%20')
class BaseResponseTest(unittest.TestCase): self._assert_followed_url(Link('http://example.com/foo'), 'http://example.com/foo') def test_follow_None_url(self): r = self.response_class("http://example.com") self.assertRaises(ValueError, r.follow, None) d...
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 APIRouter(routing.Router): include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> None: route = self.route_class( path, endpoint=endpoint, response_model=response_model,
class APIRouter(routing.Router): include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, route_class_override: Optional[Type[APIRoute]] = None, ) -> None: route_class = route_class_override or self.route_class route = route_class( ...
class APIRouter(routing.Router): include_in_schema=route.include_in_schema, response_class=route.response_class or default_response_class, name=route.name, ) elif isinstance(route, routing.Route): self.add_route(
class APIRouter(routing.Router): include_in_schema=route.include_in_schema, response_class=route.response_class or default_response_class, name=route.name, route_class_override=type(route), ) elif isinstance(rout...
class Index(IndexOpsMixin, PandasObject): pass # Return an actual float index. return Float64Index(data, copy=copy, dtype=dtype, name=name) elif inferred == "string": pass
class Index(IndexOpsMixin, PandasObject): pass # Return an actual float index. return Float64Index(data, copy=copy, name=name) elif inferred == "string": pass
from pandas.core.dtypes.common import ( is_float_dtype, is_integer_dtype, is_scalar, needs_i8_conversion, pandas_dtype, )
from pandas.core.dtypes.common import ( is_float_dtype, is_integer_dtype, is_scalar, is_signed_integer_dtype, is_unsigned_integer_dtype, needs_i8_conversion, pandas_dtype, )
from pandas.core.dtypes.generic import ( ) from pandas.core.dtypes.missing import isna from pandas.core import algorithms import pandas.core.common as com from pandas.core.indexes.base import Index, InvalidIndexError, _index_shared_docs
from pandas.core.dtypes.generic import ( ) from pandas.core.dtypes.missing import isna from pandas._typing import Dtype from pandas.core import algorithms import pandas.core.common as com from pandas.core.indexes.base import Index, InvalidIndexError, _index_shared_docs
class NumericIndex(Index): _is_numeric_dtype = True def __new__(cls, data=None, dtype=None, copy=False, name=None, fastpath=None): if fastpath is not None: warnings.warn( "The 'fastpath' keyword is deprecated, and will be "
class NumericIndex(Index): _is_numeric_dtype = True def __new__(cls, data=None, dtype=None, copy=False, name=None, fastpath=None): cls._validate_dtype(dtype) if fastpath is not None: warnings.warn( "The 'fastpath' keyword is deprecated, and will be "
class NumericIndex(Index): name = data.name return cls._simple_new(subarr, name=name) @Appender(_index_shared_docs["_maybe_cast_slice_bound"]) def _maybe_cast_slice_bound(self, label, side, kind): assert kind in ["ix", "loc", "getitem", None]
class NumericIndex(Index): name = data.name return cls._simple_new(subarr, name=name) @classmethod def _validate_dtype(cls, dtype: Dtype) -> None: if dtype is None: return validation_metadata = { "int64index": (is_signed_integer_dtype, "signed integer...
from pandas.util._decorators import Appender, cache_readonly from pandas.core.dtypes.common import ( ensure_platform_int, ensure_python_int, is_int64_dtype, is_integer, is_integer_dtype, is_list_like,
from pandas.util._decorators import Appender, cache_readonly from pandas.core.dtypes.common import ( ensure_platform_int, ensure_python_int, is_integer, is_integer_dtype, is_list_like,
class RangeIndex(Int64Index): # -------------------------------------------------------------------- @staticmethod def _validate_dtype(dtype): """ require dtype to be None or int64 """ if not (dtype is None or is_int64_dtype(dtype)): raise TypeError("Invalid to pass a non-int64...
class RangeIndex(Int64Index): # -------------------------------------------------------------------- @cache_readonly def _constructor(self): """ return the class to use for construction """
class TestFloat64Index(Numeric): result = Index(np.array([np.nan])) assert pd.isna(result.values).all() def test_constructor_invalid(self): # invalid
class TestFloat64Index(Numeric): result = Index(np.array([np.nan])) assert pd.isna(result.values).all() @pytest.mark.parametrize( "index, dtype", [ (pd.Int64Index, "float64"), (pd.UInt64Index, "categorical"), (pd.Float64Index, "datetime64"), ...
class TestRangeIndex(Numeric): result = RangeIndex(index) tm.assert_index_equal(result, index, exact=True) with pytest.raises(TypeError): RangeIndex(index, dtype="float64") def test_constructor_range(self):
class TestRangeIndex(Numeric): result = RangeIndex(index) tm.assert_index_equal(result, index, exact=True) with pytest.raises( ValueError, match="Incorrect `dtype` passed: expected signed integer, received float64", ): RangeIndex(index, dtype="float64...
class TestRangeIndex(Numeric): expected = RangeIndex(1, 5, 2) tm.assert_index_equal(result, expected, exact=True) with pytest.raises(TypeError): Index(range(1, 5, 2), dtype="float64") msg = r"^from_range\(\) got an unexpected keyword argument" with pytest.raises(Type...
class TestRangeIndex(Numeric): expected = RangeIndex(1, 5, 2) tm.assert_index_equal(result, expected, exact=True) with pytest.raises( ValueError, match="Incorrect `dtype` passed: expected signed integer, received float64", ): Index(range(1, 5, 2), dty...
class TestRangeIndex(Numeric): RangeIndex(1.1, 10.2, 1.3) # invalid passed type with pytest.raises(TypeError): RangeIndex(1, 5, dtype="float64") @pytest.mark.parametrize(
class TestRangeIndex(Numeric): RangeIndex(1.1, 10.2, 1.3) # invalid passed type with pytest.raises( ValueError, match="Incorrect `dtype` passed: expected signed integer, received float64", ): RangeIndex(1, 5, dtype="float64") @pytest.mark.par...
def test_get(): 1764.0, 1849.0, 1936.0, ], dtype="object", ), )
def test_get(): 1764.0, 1849.0, 1936.0, ] ), )
class TestAllURLsMatching(unittest.TestCase): def test_facebook_matching(self): self.assertTrue(FacebookIE.suitable('https://www.facebook.com/Shiniknoh#!/photo.php?v=10153317450565268')) def test_no_duplicates(self): ies = gen_extractors()
class TestAllURLsMatching(unittest.TestCase): def test_facebook_matching(self): self.assertTrue(FacebookIE.suitable('https://www.facebook.com/Shiniknoh#!/photo.php?v=10153317450565268')) self.assertTrue(FacebookIE.suitable('https://www.facebook.com/cindyweather?fref=ts#!/photo.php?v=101521839989457...
from ..utils import ( class FacebookIE(InfoExtractor): _VALID_URL = r'''(?x) https?://(?:\w+\.)?facebook\.com/ (?:[^#?]*\#!/)? (?:video/video\.php|photo\.php|video/embed)\?(?:.*?) (?:v|video_id)=(?P<id>[0-9]+) (?:.*)'''
from ..utils import ( class FacebookIE(InfoExtractor): _VALID_URL = r'''(?x) https?://(?:\w+\.)?facebook\.com/ (?:[^#]*?\#!/)? (?:video/video\.php|photo\.php|video/embed)\?(?:.*?) (?:v|video_id)=(?P<id>[0-9]+) (?:.*)'''
from django.utils.safestring import SafeData, SafeText, mark_safe from django.utils.text import normalize_newlines # Configuration for urlize() function. TRAILING_PUNCTUATION_RE = re.compile( '^' # Beginning of word '(.*?)' # The URL in word '([.,:;!]+)' # Allowed non-wrapping, trailing pu...
from django.utils.safestring import SafeData, SafeText, mark_safe from django.utils.text import normalize_newlines # Configuration for urlize() function. TRAILING_PUNCTUATION_CHARS = '.,:;!' WRAPPING_PUNCTUATION = [('(', ')'), ('<', '>'), ('[', ']'), ('&lt;', '&gt;'), ('"', '"'), ('\'', '\'')] # List of possible stri...
unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)') word_split_re = re.compile(r'''([\s<>"']+)''') simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE) simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$', re.IGNORECASE) simple_email_re = re.compile(r'^\S+@\S+\.\...
unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)') word_split_re = re.compile(r'''([\s<>"']+)''') simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE) simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$', re.IGNORECASE) _html_escapes = { ord('&'): '&amp;',
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): trimmed_something = False # Trim trailing punctuation. match = TRAILING_PUNCTUATION_RE.match(middle) if match: middle = match.group(1) trail = match.group(2) + trail ...
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): trimmed_something = False # Trim trailing punctuation. stripped = middle.rstrip(TRAILING_PUNCTUATION_CHARS) if middle != stripped: trail = middle[len(stripped):] + trail ...
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): trimmed_something = True return lead, middle, trail words = word_split_re.split(str(text)) for i, word in enumerate(words): if '.' in word or '@' in word or ':' in word:
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): trimmed_something = True return lead, middle, trail def is_email_simple(value): """Return True if value looks like an email address.""" # An @ must be in the middle of the value. if '@' not ...
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): elif simple_url_2_re.match(middle): middle, middle_unescaped, trail = unescape(middle, trail) url = smart_urlquote('http://%s' % middle_unescaped) elif ':' not in middle and simple_email_re.m...
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): elif simple_url_2_re.match(middle): middle, middle_unescaped, trail = unescape(middle, trail) url = smart_urlquote('http://%s' % middle_unescaped) elif ':' not in middle and is_email_simple(m...
class TestUtilsHtml(SimpleTestCase): for value, output in tests: with self.subTest(value=value): self.assertEqual(urlize(value), output)
class TestUtilsHtml(SimpleTestCase): for value, output in tests: with self.subTest(value=value): self.assertEqual(urlize(value), output) def test_urlize_unchanged_inputs(self): tests = ( ('a' + '@a' * 50000) + 'a', # simple_email_re catastrophic test ...
from pipenv.patched import crayons from pipenv.utils import ( cmd_list_to_shell, convert_deps_to_pip, create_spinner, download_file, find_python, get_canonical_names, get_source_list, is_pinned, is_python_command, is_required_version, is_star, is_valid_url, parse_indexes, pep423_name, prepare_pip_source...
from pipenv.patched import crayons from pipenv.utils import ( cmd_list_to_shell, convert_deps_to_pip, create_spinner, download_file, find_python, get_canonical_names, get_host_and_port, get_source_list, is_pinned, is_python_command, is_required_version, is_star, is_valid_url, parse_indexes, pep423_name,...
def import_requirements(project, r=None, dev=False): if extra_index: indexes.append(extra_index) if trusted_host: trusted_hosts.append(trusted_host) indexes = sorted(set(indexes)) trusted_hosts = sorted(set(trusted_hosts)) reqs = [install_req_from_parsed_requirement(f...
def import_requirements(project, r=None, dev=False): if extra_index: indexes.append(extra_index) if trusted_host: trusted_hosts.append(get_host_and_port(trusted_host)) indexes = sorted(set(indexes)) trusted_hosts = sorted(set(trusted_hosts)) reqs = [install_req_from_p...
def import_requirements(project, r=None, dev=False): else: project.add_package_to_pipfile(str(package.req), dev=dev) for index in indexes: trusted = index in trusted_hosts project.add_index_to_pipfile(index, verify_ssl=trusted) project.recase_pipfile()
def import_requirements(project, r=None, dev=False): else: project.add_package_to_pipfile(str(package.req), dev=dev) for index in indexes: # don't require HTTPS for trusted hosts (see: https://pip.pypa.io/en/stable/cli/pip/#cmdoption-trusted-host) host_and_port = get_host...
def get_url_name(url): return urllib3_util.parse_url(url).host def get_canonical_names(packages): """Canonicalize a list of packages and return a set of canonical names""" from .vendor.packaging.utils import canonicalize_name
def get_url_name(url): return urllib3_util.parse_url(url).host def get_host_and_port(url): """Get the host, or the host:port pair if port is explicitly included, for the given URL. Examples: >>> get_host_and_port('example.com') 'example.com' >>> get_host_and_port('example.com:443') 'examp...
def test_convert_deps_to_pip_unicode(): ("--extra-index-url=https://example.com/simple/", (None, "https://example.com/simple/", None, [])), ("--trusted-host=example.com", (None, None, "example.com", [])), ("# -i https://example.com/simple/", (None, None, None, [])), ("requests", (None, None, None, ["req...
def test_convert_deps_to_pip_unicode(): ("--extra-index-url=https://example.com/simple/", (None, "https://example.com/simple/", None, [])), ("--trusted-host=example.com", (None, None, "example.com", [])), ("# -i https://example.com/simple/", (None, None, None, [])), ("requests # -i https://example.com/s...
from youtube_dl.utils import ( unified_strdate, unsmuggle_url, url_basename, xpath_with_ns, )
from youtube_dl.utils import ( unified_strdate, unsmuggle_url, url_basename, urlencode_postdata, xpath_with_ns, )
class TestUtil(unittest.TestCase): bam''') self.assertEqual(read_batch_urls(f), [u'foo', u'bar', u'baz', u'bam']) if __name__ == '__main__': unittest.main()
class TestUtil(unittest.TestCase): bam''') self.assertEqual(read_batch_urls(f), [u'foo', u'bar', u'baz', u'bam']) def test_urlencode_postdata(self): data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'}) self.assertTrue(isinstance(data, bytes)) if __name__ =...
from ..utils import ( compat_urllib_error, compat_urllib_parse, compat_urllib_request, ExtractorError, )
from ..utils import ( compat_urllib_error, compat_urllib_parse, compat_urllib_request, urlencode_postdata, ExtractorError, )
class FacebookIE(InfoExtractor): login_page_req = compat_urllib_request.Request(self._LOGIN_URL) login_page_req.add_header('Cookie', 'locale=en_US') self.report_login() login_page = self._download_webpage(login_page_req, None, note=False, errnote='Unable to download login pa...
class FacebookIE(InfoExtractor): login_page_req = compat_urllib_request.Request(self._LOGIN_URL) login_page_req.add_header('Cookie', 'locale=en_US') login_page = self._download_webpage(login_page_req, None, note='Downloading login page', errnote='Unable to download login...
class FacebookIE(InfoExtractor): 'timezone': '-60', 'trynum': '1', } request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(login_form)) request.add_header('Content-Type', 'application/x-www-form-urlencoded') try: lo...
class FacebookIE(InfoExtractor): 'timezone': '-60', 'trynum': '1', } request = compat_urllib_request.Request(self._LOGIN_URL, urlencode_postdata(login_form)) request.add_header('Content-Type', 'application/x-www-form-urlencoded') try: login_results...
def read_batch_urls(batch_fd): with contextlib.closing(batch_fd) as fd: return [url for url in map(fixup, fd) if url]
def read_batch_urls(batch_fd): with contextlib.closing(batch_fd) as fd: return [url for url in map(fixup, fd) if url] def urlencode_postdata(*args, **kargs): return compat_urllib_parse.urlencode(*args, **kargs).encode('ascii')
def SHA244(self,data:str): hash = str(sha.digest()) return self.__Salt(hash,salt=self.salt) def MD5(self,data:str): sha = hashlib.md5(bytes(data.encode())) hash = str(sha.digest()) return self.__Salt(hash,salt=self.salt) def SHA384(self,data:str): sha = hashlib....
def SHA244(self,data:str): hash = str(sha.digest()) return self.__Salt(hash,salt=self.salt) def SHA384(self,data:str): sha = hashlib.sha384(bytes(data.encode())) hash = str(sha.digest())