buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class NetapiClient(object): def __init__(self, opts): self.opts = opts def _is_master_running(self): '''
class NetapiClient(object): def __init__(self, opts): self.opts = opts self.loadauth = salt.auth.LoadAuth(opts) self.key = salt.daemons.masterapi.access_keys(self.opts) minopts = copy.deepcopy(self.opts) minopts["enable_ssh_minions"] = True self.ckminions = salt.util...
class NetapiClient(object): self.opts['sock_dir'], ipc_file)) def run(self, low): ''' Execute the specified function in the specified client by passing the
class NetapiClient(object): self.opts['sock_dir'], ipc_file)) def _prep_auth_info(self, clear_load): sensitive_load_keys = [] key = None if "token" in clear_load: auth_type = "token" err_name = "TokenAuthenticationError" sensitive_...
class NetapiClient(object): raise salt.exceptions.EauthAuthenticationError( 'Raw shell option not allowed.') l_fun = getattr(self, low['client']) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {}))
class NetapiClient(object): raise salt.exceptions.EauthAuthenticationError( 'Raw shell option not allowed.') if low['client'] == 'ssh': self._authorize_ssh(low) l_fun = getattr(self, low['client']) f_call = salt.utils.args.format_call(l_fun, low) ...
# encoding: utf-8 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import time # Import Salt Testing libs from tests.support.paths import TMP_CONF_DIR, TMP from tests.support.unit import TestCase, skipIf from tests.support.mock import patch from te...
# encoding: utf-8 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import copy import logging import os import time import salt.config import salt.netapi import salt.utils.files import salt.utils.platform import salt.utils.pycrypto # Import Salt Testing libs from tests.sup...
class NetapiSSHClientTest(SSHCase): ''' opts = salt.config.client_config(os.path.join(TMP_CONF_DIR, 'master')) self.netapi = salt.netapi.NetapiClient(opts) # Initialize salt-ssh self.run_function('test.ping')
class NetapiSSHClientTest(SSHCase): ''' opts = salt.config.client_config(os.path.join(TMP_CONF_DIR, 'master')) self.netapi = salt.netapi.NetapiClient(opts) opts = salt.config.client_config(os.path.join(TMP_CONF_DIR, "master")) naopts = copy.deepcopy(opts) naopts["ignore_h...
class NetapiSSHClientTest(SSHCase): "roster": "cache", "client": "ssh", "tgt": "www.zerodayinitiative.com", "fun": "xx", "eauth": "xx", "ssh_priv": "aaa|id>{} #".format(path), } ret = self.netapi.run(low) self.assertFalse(os...
class NetapiSSHClientTest(SSHCase): "roster": "cache", "client": "ssh", "tgt": "www.zerodayinitiative.com", "ssh_priv": "aaa|id>{} #".format(path), "fun": "test.ping", "eauth": "auto", "username": "saltdev_auto", "password":...
class NetapiSSHClientTest(SSHCase): "roster": "cache", "client": "ssh", "tgt": "root|id>{} #@127.0.0.1".format(path), "fun": "xx", "eauth": "xx", "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", } ...
class NetapiSSHClientTest(SSHCase): "roster": "cache", "client": "ssh", "tgt": "root|id>{} #@127.0.0.1".format(path), "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", "fun": "test.ping", "eauth": "auto", ...
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "xx", "eauth": "xx", "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", "ssh_options": ["|id>{} #".f...
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "test.ping", "eauth": "auto", "username": "saltdev_auto", "password": "saltdev", "roster_file": "/tmp/salt-tests-tmpdir/c...
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "xx", "eauth": "xx", "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", "ssh_port": "hhhhh|id>{} #"....
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "test.ping", "eauth": "auto", "username": "saltdev_auto", "password": "saltdev", "roster_file": "/tmp/salt-tests-tmpdir/c...
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "xx", "eauth": "xx", "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", "ssh_remote_port_forwards": ...
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "test.ping", "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", "ssh_remote_port_forwards": "hhhhh|id>{} #, lol"...
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...
def test_sampleformat_not_corrupted(self): out.seek(0) with Image.open(out) as im: im.load()
def test_sampleformat_not_corrupted(self): out.seek(0) with Image.open(out) as im: im.load() def test_realloc_overflow(self): TiffImagePlugin.READ_LIBTIFF = True with Image.open("Tests/images/tiff_overflow_rows_per_strip.tif") as im: with self.assertRaises(IO...
def main(): level=dict(type='str', choices=['authNoPriv', 'authPriv']), integrity=dict(type='str', choices=['md5', 'sha']), privacy=dict(type='str', choices=['aes', 'des']), authkey=dict(type='str'), privkey=dict(type='str'), ), required_togeth...
def main(): level=dict(type='str', choices=['authNoPriv', 'authPriv']), integrity=dict(type='str', choices=['md5', 'sha']), privacy=dict(type='str', choices=['aes', 'des']), authkey=dict(type='str', no_log=True), privkey=dict(type='str', no_log=True), ...
class TimeseriesGenerator(Sequence): self.reverse = reverse self.batch_size = batch_size def __len__(self): return int(np.ceil( (self.end_index - self.start_index) / (self.batch_size * self.stride))) def _empty_batch(self, num_rows):
class TimeseriesGenerator(Sequence): self.reverse = reverse self.batch_size = batch_size if self.start_index > self.end_index: raise ValueError('`start_index+length=%i > end_index=%i` ' 'is disallowed, as no part of the sequence ' ...
class TimeseriesGenerator(Sequence): def __getitem__(self, index): if self.shuffle: rows = np.random.randint( self.start_index, self.end_index, size=self.batch_size) else: i = self.start_index + self.batch_size * self.stride * index rows = np.arang...
class TimeseriesGenerator(Sequence): def __getitem__(self, index): if self.shuffle: rows = np.random.randint( self.start_index, self.end_index + 1, size=self.batch_size) else: i = self.start_index + self.batch_size * self.stride * index rows = np.a...
import numpy as np from numpy.testing import assert_allclose import pytest
from math import ceil import numpy as np from numpy.testing import assert_allclose, assert_raises import pytest
def test_TimeseriesGenerator(): length=10, sampling_rate=2, start_index=10, end_index=30, batch_size=2) assert len(data_gen) == 5 assert (np.allclose(data_gen[0][0], np.array([[[10], ...
def test_TimeseriesGenerator(): length=10, sampling_rate=2, start_index=10, end_index=30, batch_size=2) assert len(data_gen) == 6 assert (np.allclose(data_gen[0][0], np.array([[[10], ...
def test_TimeseriesGenerator(): length=10, sampling_rate=2, start_index=10, end_index=30, batch_size=2) assert len(data_gen) == 5 assert np.allclose(data_gen[0][0], np.array( [np.array(data[10:19:2]...
def test_TimeseriesGenerator(): length=10, sampling_rate=2, start_index=10, end_index=30, batch_size=2) assert len(data_gen) == 6 assert np.allclose(data_gen[0][0], np.array( [np.array(data[10:19:2])...
def read_conllx(input_data, use_morphology=False, n=0): continue try: id_ = int(id_) - 1 head = (int(head) - 1) if head != "0" else id_ dep = "ROOT" if dep == "root" else dep tag = pos if tag == "_" else ...
def read_conllx(input_data, use_morphology=False, n=0): continue try: id_ = int(id_) - 1 head = (int(head) - 1) if head not in ["0", "_"] else id_ dep = "ROOT" if dep == "root" else dep tag = pos if tag =...
class Model(Container): @interfaces.legacy_generator_methods_support def fit_generator(self, generator, steps_per_epoch, epochs=1, verbose=1, callbacks=None,
class Model(Container): @interfaces.legacy_generator_methods_support def fit_generator(self, generator, steps_per_epoch=None, epochs=1, verbose=1, callbacks=None,
class Model(Container): to yield from `generator` before declaring one epoch finished and starting the next epoch. It should typically be equal to the number of samples of your dataset divided by the batch size. Not used if using `Sequence`. ep...
class Model(Container): to yield from `generator` before declaring one epoch finished and starting the next epoch. It should typically be equal to the number of samples of your dataset divided by the batch size. Optional for `Sequence`: if ...
class Model(Container): validation_steps: Only relevant if `validation_data` is a generator. Total number of steps (batches of samples) to yield from `generator` before stopping. class_weight: Dictionary mapping class indices to a weight for the cl...
class Model(Container): validation_steps: Only relevant if `validation_data` is a generator. Total number of steps (batches of samples) to yield from `generator` before stopping. Optional for `Sequence`: if unspecified, will use the `len(valida...
class Model(Container): if do_validation: self._make_test_function() # python 2 has 'next', 3 has '__next__' # avoid any explicit version checks val_gen = (hasattr(validation_data, 'next') or hasattr(validation_data, '__next__') or isins...
class Model(Container): if do_validation: self._make_test_function() is_sequence = isinstance(generator, Sequence) if not is_sequence and use_multiprocessing and workers > 1: warnings.warn( UserWarning('Using a generator with `use_multiprocessing=True`' ...
class Model(Container): val_data += [0.] for cbk in callbacks: cbk.validation_data = val_data is_sequence = isinstance(generator, Sequence) if not is_sequence and use_multiprocessing and workers > 1: warnings.warn( UserWarning('Usin...
class Model(Container): val_data += [0.] for cbk in callbacks: cbk.validation_data = val_data enqueuer = None try:
class Model(Container): return self.history @interfaces.legacy_generator_methods_support def evaluate_generator(self, generator, steps, max_queue_size=10, workers=1, use_multiprocessing=False):
class Model(Container): return self.history @interfaces.legacy_generator_methods_support def evaluate_generator(self, generator, steps=None, max_queue_size=10, workers=1, use_multiprocessing=False):
class Model(Container): when using multiprocessing. steps: Total number of steps (batches of samples) to yield from `generator` before stopping. Not used if using Sequence. max_queue_size: maximum size for the generator queue worker...
class Model(Container): when using multiprocessing. steps: Total number of steps (batches of samples) to yield from `generator` before stopping. Optional for `Sequence`: if unspecified, will use the `len(generator)` as a number of steps. ...
class Model(Container): ' and multiple workers may duplicate your data.' ' Please consider using the`keras.utils.Sequence' ' class.')) if is_sequence: steps = len(generator) enqueuer = None try:
class Model(Container): ' and multiple workers may duplicate your data.' ' Please consider using the`keras.utils.Sequence' ' class.')) if steps is None: if is_sequence: steps = len(generator) ...
class Model(Container): return averages @interfaces.legacy_generator_methods_support def predict_generator(self, generator, steps, max_queue_size=10, workers=1, use_multiprocessing=False,
class Model(Container): return averages @interfaces.legacy_generator_methods_support def predict_generator(self, generator, steps=None, max_queue_size=10, workers=1, use_multiprocessing=False,
class Model(Container): when using multiprocessing. steps: Total number of steps (batches of samples) to yield from `generator` before stopping. Not used if using Sequence. max_queue_size: Maximum size for the generator queue. worke...
class Model(Container): when using multiprocessing. steps: Total number of steps (batches of samples) to yield from `generator` before stopping. Optional for `Sequence`: if unspecified, will use the `len(generator)` as a number of steps. ...
class Model(Container): ' and multiple workers may duplicate your data.' ' Please consider using the`keras.utils.Sequence' ' class.')) if is_sequence: steps = len(generator) enqueuer = None try:
class Model(Container): ' and multiple workers may duplicate your data.' ' Please consider using the`keras.utils.Sequence' ' class.')) if steps is None: if is_sequence: steps = len(generator) ...
class Sequential(Model): @interfaces.legacy_generator_methods_support def fit_generator(self, generator, steps_per_epoch, epochs=1, verbose=1, callbacks=None,
class Sequential(Model): @interfaces.legacy_generator_methods_support def fit_generator(self, generator, steps_per_epoch=None, epochs=1, verbose=1, callbacks=None,
class Sequential(Model): finished and starting the next epoch. It should typically be equal to the number of samples of your dataset divided by the batch size. epochs: Integer, total number of iterations on the data. Note that in conjunction wi...
class Sequential(Model): finished and starting the next epoch. It should typically be equal to the number of samples of your dataset divided by the batch size. Optional for `Sequence`: if unspecified, will use the `len(generator)` as a numb...
class Sequential(Model): at the end of every epoch. It should typically be equal to the number of samples of your validation dataset divided by the batch size. class_weight: Dictionary mapping class indices to a weight for the class. ...
class Sequential(Model): at the end of every epoch. It should typically be equal to the number of samples of your validation dataset divided by the batch size. Optional for `Sequence`: if unspecified, will use the `len(validation_data)` as ...
class Sequential(Model): initial_epoch=initial_epoch) @interfaces.legacy_generator_methods_support def evaluate_generator(self, generator, steps, max_queue_size=10, workers=1, use_multiprocessing=False): """Ev...
class Sequential(Model): initial_epoch=initial_epoch) @interfaces.legacy_generator_methods_support def evaluate_generator(self, generator, steps=None, max_queue_size=10, workers=1, use_multiprocessing=False): ...
class Sequential(Model): or (inputs, targets, sample_weights) steps: Total number of steps (batches of samples) to yield from `generator` before stopping. max_queue_size: maximum size for the generator queue workers: maximum number of processes to spin...
class Sequential(Model): or (inputs, targets, sample_weights) steps: Total number of steps (batches of samples) to yield from `generator` before stopping. Optional for `Sequence`: if unspecified, will use the `len(generator)` as a number of ste...
class Sequential(Model): use_multiprocessing=use_multiprocessing) @interfaces.legacy_generator_methods_support def predict_generator(self, generator, steps, max_queue_size=10, workers=1, use_multiprocessing=False, ...
class Sequential(Model): use_multiprocessing=use_multiprocessing) @interfaces.legacy_generator_methods_support def predict_generator(self, generator, steps=None, max_queue_size=10, workers=1, use_multiprocessing=Fa...
class Sequential(Model): generator: generator yielding batches of input samples. steps: Total number of steps (batches of samples) to yield from `generator` before stopping. max_queue_size: maximum size for the generator queue workers: maximum number of pr...
class Sequential(Model): generator: generator yielding batches of input samples. steps: Total number of steps (batches of samples) to yield from `generator` before stopping. Optional for `Sequence`: if unspecified, will use the `len(generator)` as ...
def test_model_methods(): # test starting from non-zero initial epoch trained_epochs = [] # define tracer callback def on_epoch_begin(epoch, logs): trained_epochs.append(epoch) tracker_cb = LambdaCallback(on_epoch_begin=on_epoch_begin) out = model.fit([input_a_np, input_b_np], ...
def test_model_methods(): # test starting from non-zero initial epoch trained_epochs = [] trained_batches = [] # define tracer callback def on_epoch_begin(epoch, logs): trained_epochs.append(epoch) def on_batch_begin(batch, logs): trained_batches.append(batch) tracker_cb ...
def test_model_methods(): model.compile(optimizer, loss, metrics=[], loss_weights=loss_weights, sample_weight_mode=None) trained_epochs = [] out = model.fit_generator(generator=RandomSequence(3), steps_per_epoch=12, epochs=5, initial_epoch=0, validation_data=R...
def test_model_methods(): model.compile(optimizer, loss, metrics=[], loss_weights=loss_weights, sample_weight_mode=None) trained_epochs = [] trained_batches = [] out = model.fit_generator(generator=RandomSequence(3), steps_per_epoch=3, epochs=5, initial_ep...
install_requires = [ 'botocore==1.20.3', 'docutils>=0.10,<0.16', 's3transfer>=0.3.0,<0.4.0', 'PyYAML>=3.10,<5.4', 'colorama>=0.2.5,<0.4.4', 'rsa>=3.1.2,<=4.5.0', ]
install_requires = [ 'botocore==1.20.3', 'docutils>=0.10,<0.16', 's3transfer>=0.3.0,<0.4.0', 'PyYAML>=3.10,<5.5', 'colorama>=0.2.5,<0.4.4', 'rsa>=3.1.2,<=4.5.0', ]
class APIRouter(routing.Router): include_in_schema=route.include_in_schema, name=route.name, ) def get( self,
class APIRouter(routing.Router): include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route...
def test_getproxies_environment_keep_no_proxies(self): self.assertTrue(urllib.request.proxy_bypass_environment('anotherdomain.com:8888')) self.assertTrue(urllib.request.proxy_bypass_environment('newdomain.com:1234')) def test_proxy_bypass_environment_host_match(self): bypass = urllib.reques...
def test_getproxies_environment_keep_no_proxies(self): self.assertTrue(urllib.request.proxy_bypass_environment('anotherdomain.com:8888')) self.assertTrue(urllib.request.proxy_bypass_environment('newdomain.com:1234')) def test_proxy_cgi_ignore(self): try: self.env.set('HTTP_PROXY...
def getproxies_environment(): name = name.lower() if value and name[-6:] == '_proxy': proxies[name[:-6]] = value for name, value in os.environ.items(): if name[-6:] == '_proxy': name = name.lower()
def getproxies_environment(): name = name.lower() if value and name[-6:] == '_proxy': proxies[name[:-6]] = value # CVE-2016-1000110 - If we are running as CGI script, forget HTTP_PROXY # (non-all-lowercase) as it may be set from the web server by a "Proxy:" # header from the clie...
def repercent_broken_unicode(path): repercent-encode any octet produced that is not part of a strictly legal UTF-8 octet sequence. """ try: path.decode() except UnicodeDecodeError as e: repercent = quote(path[e.start:e.end], safe=b"/#%[]=:;$&()+,!?*@'~") path = repercent_brok...
def repercent_broken_unicode(path): repercent-encode any octet produced that is not part of a strictly legal UTF-8 octet sequence. """ while True: try: path.decode() except UnicodeDecodeError as e: # CVE-2019-14235: A recursion shouldn't be used since the exceptio...
import datetime import unittest from unittest import mock from urllib.parse import quote_plus
import datetime import sys import unittest from unittest import mock from urllib.parse import quote_plus
from urllib.parse import quote_plus from django.test import SimpleTestCase from django.utils.encoding import ( DjangoUnicodeDecodeError, escape_uri_path, filepath_to_uri, force_bytes, force_text, get_system_encoding, iri_to_uri, smart_bytes, smart_text, uri_to_iri, ) from django.utils.functional import Simp...
from urllib.parse import quote_plus from django.test import SimpleTestCase from django.utils.encoding import ( DjangoUnicodeDecodeError, escape_uri_path, filepath_to_uri, force_bytes, force_text, get_system_encoding, iri_to_uri, repercent_broken_unicode, smart_bytes, smart_text, uri_to_iri, ) from django.ut...
class TestEncodingUtils(SimpleTestCase): with mock.patch('locale.getdefaultlocale', side_effect=Exception): self.assertEqual(get_system_encoding(), 'ascii') class TestRFC3987IEncodingUtils(unittest.TestCase):
class TestEncodingUtils(SimpleTestCase): with mock.patch('locale.getdefaultlocale', side_effect=Exception): self.assertEqual(get_system_encoding(), 'ascii') def test_repercent_broken_unicode_recursion_error(self): # Prepare a string long enough to force a recursion error if the tested ...
from django.utils.encoding import force_bytes, force_str, force_text from django.utils.functional import allow_lazy from django.utils.six.moves.urllib.parse import ( quote, quote_plus, unquote, unquote_plus, urlencode as original_urlencode, urlparse, ) ETAG_MATCH = re.compile(r'(?:W/)?"((?:\\.|[^"])*)"') MONT...
from django.utils.encoding import force_bytes, force_str, force_text from django.utils.functional import allow_lazy from django.utils.six.moves.urllib.parse import ( quote, quote_plus, unquote, unquote_plus, urlencode as original_urlencode, ) if six.PY2: from urlparse import ( ParseResult, SplitResult,...
def is_safe_url(url, host=None): return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host) def _is_safe_url(url, host): # Chrome considers any URL with more than two slashes to be absolute, but # urlparse is not so flexible. Treat any url with three slashes as unsafe. if url.starts...
def is_safe_url(url, host=None): return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host) # Copied from urllib.parse.urlparse() but uses fixed urlsplit() function. def _urlparse(url, scheme='', allow_fragments=True): """Parse a URL into 6 components: <scheme>://<netloc>/<path>;<params...
class TestUtilsHttp(unittest.TestCase): r'http://testserver\me:pass@example.com', r'http://testserver\@example.com', r'http:\\testserver\confirm\me@example.com', '\n'): self.assertFalse(http.is_safe_url(bad_url, ...
class TestUtilsHttp(unittest.TestCase): r'http://testserver\me:pass@example.com', r'http://testserver\@example.com', r'http:\\testserver\confirm\me@example.com', 'http:999999999', 'ftp:9999999999', ...
class TestUtilsHttp(unittest.TestCase): 'HTTPS://testserver/', '//testserver/', 'http://testserver/confirm?email=me@example.com', '/url%20with%20spaces/'): self.assertTrue(http.is_safe_url(good_url, host='testserver'), "%s s...
class TestUtilsHttp(unittest.TestCase): 'HTTPS://testserver/', '//testserver/', 'http://testserver/confirm?email=me@example.com', '/url%20with%20spaces/', 'path/http:2222222222'): self.assertTrue(http.is...
def _isna_new(obj): elif isinstance(obj, type): return False elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)): return _isna_ndarraylike(obj) elif isinstance(obj, ABCDataFrame): return obj.isna() elif isinstance(obj, list): return _isna_ndarr...
def _isna_new(obj): elif isinstance(obj, type): return False elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)): return _isna_ndarraylike(obj, old=False) elif isinstance(obj, ABCDataFrame): return obj.isna() elif isinstance(obj, list): return ...
def _isna_old(obj): elif isinstance(obj, type): return False elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)): return _isna_ndarraylike_old(obj) elif isinstance(obj, ABCDataFrame): return obj.isna() elif isinstance(obj, list): return _isna_n...
def _isna_old(obj): elif isinstance(obj, type): return False elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)): return _isna_ndarraylike(obj, old=True) elif isinstance(obj, ABCDataFrame): return obj.isna() elif isinstance(obj, list): return _...
def _use_inf_as_na(key): globals()["_isna"] = _isna_new def _isna_ndarraylike(obj): values = getattr(obj, "_values", obj) dtype = values.dtype if is_extension_array_dtype(dtype): result = values.isna() elif is_string_dtype(dtype): result = _isna_string_dtype(values, dtype, old...
def _use_inf_as_na(key): globals()["_isna"] = _isna_new def _isna_ndarraylike(obj, old: bool = False): """ Return an array indicating which values of the input array are NaN / NA. Parameters ---------- obj: array-like The input array whose elements are to be checked. old: bool...
import pytest from pandas.core.dtypes.dtypes import CategoricalDtype from pandas import Categorical, Index, Series, isna import pandas._testing as tm
import pytest from pandas.core.dtypes.dtypes import CategoricalDtype import pandas as pd from pandas import Categorical, DataFrame, Index, Series, isna import pandas._testing as tm
class TestCategoricalMissing: expected = Categorical(["A", "B", "C", "B", "A"], dtype=cat.dtype) tm.assert_categorical_equal(result, expected) assert isna(cat[-1]) # didnt modify original inplace
class TestCategoricalMissing: expected = Categorical(["A", "B", "C", "B", "A"], dtype=cat.dtype) tm.assert_categorical_equal(result, expected) assert isna(cat[-1]) # didnt modify original inplace @pytest.mark.parametrize( "values, expected", [ ([1, 2, 3], np.arr...
from xmlrpc.server import DocXMLRPCServer import http.client import sys import threading import unittest
from xmlrpc.server import DocXMLRPCServer import http.client import re import sys import threading import unittest
def test_annotations(self): b'method_annotation</strong></a>(x: bytes)</dt></dl>'), response.read()) if __name__ == '__main__': unittest.main()
def test_annotations(self): b'method_annotation</strong></a>(x: bytes)</dt></dl>'), response.read()) def test_server_title_escape(self): # bpo-38243: Ensure that the server title and documentation # are escaped for HTML. self.serv.set_server_title('test_title<script...
def export_add(self, x, y): from http.server import BaseHTTPRequestHandler from functools import partial from inspect import signature import http.server import socketserver import sys
def export_add(self, x, y): from http.server import BaseHTTPRequestHandler from functools import partial from inspect import signature import html import http.server import socketserver import sys
def generate_html_documentation(self): methods ) return documenter.page(self.server_title, documentation) class DocXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): """XML-RPC and documentation request handler class.
def generate_html_documentation(self): methods ) return documenter.page(html.escape(self.server_title), documentation) class DocXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): """XML-RPC and documentation request handler class.
class tqdm(Comparable): if not _is_ascii(full_bar.charset) and _is_ascii(bar_format): bar_format = _unicode(bar_format) res = bar_format.format(bar=full_bar, **format_dict) if ncols: return disp_trim(res, ncols) elif bar_format: # ...
class tqdm(Comparable): if not _is_ascii(full_bar.charset) and _is_ascii(bar_format): bar_format = _unicode(bar_format) res = bar_format.format(bar=full_bar, **format_dict) return disp_trim(res, ncols) if ncols else res elif bar_format: # user-spe...
class tqdm(Comparable): if ncols else 10, charset=Bar.BLANK) res = bar_format.format(bar=full_bar, **format_dict) if ncols: return disp_trim(res, ncols) else: # no total: no progressbar, ETA, just progress stats retu...
class tqdm(Comparable): if ncols else 10, charset=Bar.BLANK) res = bar_format.format(bar=full_bar, **format_dict) return disp_trim(res, ncols) if ncols else res else: # no total: no progressbar, ETA, just progress stats return ((pre...
def test_format_meter(): # l_bar gets chopped # no bar # no r_bar format_meter(0, 1000, 13, ncols=10, bar_width=10, bar_format="************{bar}$$$$$$$$$$"), "**********" # 10/12 stars since ncols is 10 ) eq_(
def test_format_meter(): # l_bar gets chopped # no bar # no r_bar format_meter(0, 1000, 13, ncols=10, bar_format="************{bar:10}$$$$$$$$$$"), "**********" # 10/12 stars since ncols is 10 ) eq_(
def test_format_meter(): # l_bar displays # bar gets chopped # no r_bar format_meter(0, 1000, 13, ncols=20, bar_width=10, bar_format="************{bar}$$$$$$$$$$"), "************ " # all 12 stars and 8/10 bar parts ) eq_(
def test_format_meter(): # l_bar displays # bar gets chopped # no r_bar format_meter(0, 1000, 13, ncols=20, bar_format="************{bar:10}$$$$$$$$$$"), "************ " # all 12 stars and 8/10 bar parts ) eq_(
def test_format_meter(): # l_bar displays # bar displays # r_bar gets chopped format_meter(0, 1000, 13, ncols=30, bar_width=10, bar_format="************{bar}$$$$$$$$$$"), "************ $$$$$$$$" # all 12 stars and 10 bar parts, but only 8/10 dollar signs ) eq_( ...
def test_format_meter(): # l_bar displays # bar displays # r_bar gets chopped format_meter(0, 1000, 13, ncols=30, bar_format="************{bar:10}$$$$$$$$$$"), "************ $$$$$$$$" # all 12 stars and 10 bar parts, but only 8/10 dollar signs ) eq_( # l...
def disp_trim(data, length): if len(data) == disp_len(data): return data[:length] while disp_len(data) > length: # carefully delete one char at a time data = data[:-1] if RE_ANSI.search(data): # assume ANSI reset is required return data + "\033[0m" return data
def disp_trim(data, length): if len(data) == disp_len(data): return data[:length] ansi_present = bool(RE_ANSI.search(data)) while disp_len(data) > length: # carefully delete one char at a time data = data[:-1] if ansi_present and bool(RE_ANSI.search(data)): # assume ANSI reset ...
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 URLValidator(RegexValidator): r'\Z', re.IGNORECASE) message = _('Enter a valid URL.') schemes = ['http', 'https', 'ftp', 'ftps'] def __init__(self, schemes=None, **kwargs): super().__init__(**kwargs)
class URLValidator(RegexValidator): r'\Z', re.IGNORECASE) message = _('Enter a valid URL.') schemes = ['http', 'https', 'ftp', 'ftps'] unsafe_chars = frozenset('\t\r\n') def __init__(self, schemes=None, **kwargs): super().__init__(**kwargs)
class URLValidator(RegexValidator): def __call__(self, value): if not isinstance(value, str): raise ValidationError(self.message, code=self.code, params={'value': value}) # Check if the scheme is valid. scheme = value.split('://')[0].lower() if scheme not in self.schemes:
class URLValidator(RegexValidator): def __call__(self, value): if not isinstance(value, str): raise ValidationError(self.message, code=self.code, params={'value': value}) if self.unsafe_chars.intersection(value): raise ValidationError(self.message, code=self.code, params={'va...
TEST_DATA = [ (URLValidator(), None, ValidationError), (URLValidator(), 56, ValidationError), (URLValidator(), 'no_scheme', ValidationError), # Trailing newlines not accepted (URLValidator(), 'http://www.djangoproject.com/\n', ValidationError), (URLValidator(), 'http://[::ffff:192.9.5.5]\n', Val...
TEST_DATA = [ (URLValidator(), None, ValidationError), (URLValidator(), 56, ValidationError), (URLValidator(), 'no_scheme', ValidationError), # Newlines and tabs are not accepted. (URLValidator(), 'http://www.djangoproject.com/\n', ValidationError), (URLValidator(), 'http://[::ffff:192.9.5.5]\n'...
def test_urlsplit_normalization(self): urlparse.urlsplit(u'http://\u30d5\u309a\ufe1380') for scheme in [u"http", u"https", u"ftp"]: for c in denorm_chars: url = u"{}://netloc{}false.netloc/path".format(scheme, c) if test_support.verbose: ...
def test_urlsplit_normalization(self): urlparse.urlsplit(u'http://\u30d5\u309a\ufe1380') for scheme in [u"http", u"https", u"ftp"]: for netloc in [u"netloc{}false.netloc", u"n{}user@netloc"]: for c in denorm_chars: url = u"{}://{}/path".format(scheme,...
def _checknetloc(netloc): # looking for characters like \u2100 that expand to 'a/c' # IDNA uses NFKC equivalence, so normalize for this check import unicodedata n = netloc.rpartition('@')[2] # ignore anything to the left of '@' n = n.replace(':', '') # ignore characters already included n...
def _checknetloc(netloc): # looking for characters like \u2100 that expand to 'a/c' # IDNA uses NFKC equivalence, so normalize for this check import unicodedata n = netloc.replace(u'@', u'') # ignore characters already included n = n.replace(u':', u'') # but not the surrounding text n = n.r...
def test_match(stderr): def test_get_new_command(stderr): assert get_new_command(Command('git push', stderr=stderr))\ == "git push --set-upstream origin master" assert get_new_command(Command('git push -u origin', stderr=stderr))\ == "git push --set-upstream origin master" assert get_new_com...
def test_match(stderr): def test_get_new_command(stderr): assert get_new_command(Command('git push', stderr=stderr))\ == "git push --set-upstream origin master" assert get_new_command(Command('git push -u', stderr=stderr))\ == "git push --set-upstream origin master" assert get_new_command(Co...
def get_new_command(command): pass if upstream_option_index is not -1: command.script_parts.pop(upstream_option_index) command.script_parts.pop(upstream_option_index) push_upstream = command.stderr.split('\n')[-3].strip().partition('git ')[2] return replace_argument(" ".join(command...
def get_new_command(command): pass if upstream_option_index is not -1: command.script_parts.pop(upstream_option_index) try: command.script_parts.pop(upstream_option_index) except IndexError: # This happens for `git push -u` pass push_upstream ...
class TestDecompressionBomb: with Image.open(TEST_FILE): pass def test_exception_ico(self): with pytest.raises(Image.DecompressionBombError): with Image.open("Tests/images/decompression_bomb.ico"):
class TestDecompressionBomb: with Image.open(TEST_FILE): pass @pytest.mark.xfail(reason="different exception") def test_exception_ico(self): with pytest.raises(Image.DecompressionBombError): with Image.open("Tests/images/decompression_bomb.ico"):
def test_apng_syntax_errors(): exception = e assert exception is None with pytest.raises(SyntaxError): with Image.open("Tests/images/apng/syntax_num_frames_high.png") as im: im.seek(im.n_frames - 1) im.load()
def test_apng_syntax_errors(): exception = e assert exception is None with pytest.raises(OSError): with Image.open("Tests/images/apng/syntax_num_frames_high.png") as im: im.seek(im.n_frames - 1) im.load()
from PIL import Image from .helper import assert_image_equal_tofile
from PIL import Image import pytest from .helper import assert_image_equal_tofile
def test_combined_larger_than_size(): with pytest.raises(OSError): with Image.open("Tests/images/combined_larger_than_size.psd"): pass
def test_combined_larger_than_size(): with pytest.raises(OSError): with Image.open("Tests/images/combined_larger_than_size.psd"): pass @pytest.mark.parametrize( "test_file,raises", [ ("Tests/images/timeout-1ee28a249896e05b83840ae8140622de8e648ba9.psd", Image.UnidentifiedImageErr...
class TestFileTiff: ) def test_string_dimension(self): # Assert that an error is raised if one of the dimensions is a string with pytest.raises(ValueError): with Image.open("Tests/images/string_dimension.tiff"): pass @pytest.mark.skipif(not is_win32(), reason="Windo...
class TestFileTiff: ) def test_string_dimension(self): # Assert that an error is raised if one of the dimensions is a string with pytest.raises(OSError): with Image.open("Tests/images/string_dimension.tiff") as im: im.load() @pytest.mark.skipif(not is_win32(), reas...
def _safe_read(fp, size): :param fp: File handle. Must implement a <b>read</b> method. :param size: Number of bytes to read. :returns: A string containing up to <i>size</i> bytes of data. """ if size <= 0: return b"" if size <= SAFEBLOCK: return fp.read(size) data = [] ...
def _safe_read(fp, size): :param fp: File handle. Must implement a <b>read</b> method. :param size: Number of bytes to read. :returns: A string containing <i>size</i> bytes of data. Raises an OSError if the file is truncated and the read can not be completed """ if size <= 0: return ...
def _safe_read(fp, size): break data.append(block) size -= len(block) return b"".join(data) class PyCodecState: def __init__(self): self.xsize = 0
def _safe_read(fp, size): break data.append(block) size -= len(block) if sum(len(d) for d in data) < size: raise OSError("Truncated File Read") return b"".join(data) class PyCodecState: def __init__(self): self.xsize = 0
class PsdImageFile(ImageFile.ImageFile): end = self.fp.tell() + size size = i32(read(4)) if size: self.layers = _layerinfo(self.fp) self.fp.seek(end) self.n_frames = len(self.layers) self.is_animated = self.n_frames > 1
class PsdImageFile(ImageFile.ImageFile): end = self.fp.tell() + size size = i32(read(4)) if size: _layer_data = io.BytesIO(ImageFile._safe_read(self.fp, size)) self.layers = _layerinfo(_layer_data, size) self.fp.seek(end) self.n_fra...
class PsdImageFile(ImageFile.ImageFile): finally: self.__fp = None def _layerinfo(file): # read layerinfo block layers = [] read = file.read for i in range(abs(i16(read(2)))): # bounding box y0 = i32(read(4))
class PsdImageFile(ImageFile.ImageFile): finally: self.__fp = None def _layerinfo(fp, ct_bytes): # read layerinfo block layers = [] def read(size): return ImageFile._safe_read(fp, size) ct = i16(read(2)) # sanity check if ct_bytes < (abs(ct) * 20): raise S...
def _layerinfo(file): # image info info = [] mode = [] types = list(range(i16(read(2)))) if len(types) > 4: continue
def _layerinfo(file): # image info info = [] mode = [] ct_types = i16(read(2)) types = list(range(ct_types)) if len(types) > 4: continue
def _layerinfo(file): size = i32(read(4)) # length of the extra data field combined = 0 if size: data_end = file.tell() + size length = i32(read(4)) if length: file.seek(length - 16, io.SEEK_CUR) combined += length + 4 ...
def _layerinfo(file): size = i32(read(4)) # length of the extra data field combined = 0 if size: data_end = fp.tell() + size length = i32(read(4)) if length: fp.seek(length - 16, io.SEEK_CUR) combined += length + 4 le...
def _layerinfo(file): name = read(length).decode("latin-1", "replace") combined += length + 1 file.seek(data_end) layers.append((name, mode, (x0, y0, x1, y1))) # get tiles
def _layerinfo(file): name = read(length).decode("latin-1", "replace") combined += length + 1 fp.seek(data_end) layers.append((name, mode, (x0, y0, x1, y1))) # get tiles
def _layerinfo(file): for name, mode, bbox in layers: tile = [] for m in mode: t = _maketile(file, m, bbox, 1) if t: tile.extend(t) layers[i] = name, mode, bbox, tile
def _layerinfo(file): for name, mode, bbox in layers: tile = [] for m in mode: t = _maketile(fp, m, bbox, 1) if t: tile.extend(t) layers[i] = name, mode, bbox, tile
def sendEmail(sydent, templateName, mailTo, substitutions): allSubstitutions[k+"_forhtml"] = cgi.escape(v.decode('utf8')) allSubstitutions[k+"_forurl"] = urllib.quote(v) mailString = open(mailTemplateFile).read() % allSubstitutions rawFrom = email.utils.parseaddr(mailFrom)[1] ...
def sendEmail(sydent, templateName, mailTo, substitutions): allSubstitutions[k+"_forhtml"] = cgi.escape(v.decode('utf8')) allSubstitutions[k+"_forurl"] = urllib.quote(v) mailString = open(mailTemplateFile).read().decode('utf8') % allSubstitutions parsedFrom = email.utils.parsead...