buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class CSVLogger(Callback): self.writer = None self.keys = None self.append_header = True self.file_flags = 'b' if six.PY2 and os.name == 'nt' else '' super(CSVLogger, self).__init__() def on_train_begin(self, logs=None):
class CSVLogger(Callback): self.writer = None self.keys = None self.append_header = True if six.PY2: self.file_flags = 'b' self._open_args = {} else: self.file_flags = '' self._open_args = {'newline': '\n'} super(CSVLogger, ...
class CSVLogger(Callback): if os.path.exists(self.filename): with open(self.filename, 'r' + self.file_flags) as f: self.append_header = not bool(len(f.readline())) self.csv_file = open(self.filename, 'a' + self.file_flags) else: self.csv_fi...
class CSVLogger(Callback): if os.path.exists(self.filename): with open(self.filename, 'r' + self.file_flags) as f: self.append_header = not bool(len(f.readline())) mode = 'a' else: mode = 'w' self.csv_file = io.open(self.filename, ...
class CSVLogger(Callback): if not self.writer: class CustomDialect(csv.excel): delimiter = self.sep self.writer = csv.DictWriter(self.csv_file, fieldnames=['epoch'] + self.keys, dialect=CustomDialect) if self.append_he...
class CSVLogger(Callback): if not self.writer: class CustomDialect(csv.excel): delimiter = self.sep fieldnames = ['epoch'] + self.keys if six.PY2: fieldnames = [unicode(x) for x in fieldnames] self.writer = csv.DictWriter(self.csv_f...
def test_CSVLogger(tmpdir): # case 3, reuse of CSVLogger object model.fit(X_train, y_train, batch_size=batch_size, validation_data=(X_test, y_test), callbacks=cbks, epochs=1) import re with open(filepath) as csvfile: output = " ".join(csvfile.readlines()) assert len(re.fi...
def test_CSVLogger(tmpdir): # case 3, reuse of CSVLogger object model.fit(X_train, y_train, batch_size=batch_size, validation_data=(X_test, y_test), callbacks=cbks, epochs=2) import re with open(filepath) as csvfile: list_lines = csvfile.readlines() for line in list_lines...
class LSTMCell(Layer): inputs_f = inputs inputs_c = inputs inputs_o = inputs x_i = K.dot(inputs_i, self.kernel_i) + self.bias_i x_f = K.dot(inputs_f, self.kernel_f) + self.bias_f x_c = K.dot(inputs_c, self.kernel_c) + self.bias_c ...
class LSTMCell(Layer): inputs_f = inputs inputs_c = inputs inputs_o = inputs x_i = K.dot(inputs_i, self.kernel_i) x_f = K.dot(inputs_f, self.kernel_f) x_c = K.dot(inputs_c, self.kernel_c) x_o = K.dot(inputs_o, self.kernel_o)...
def test_implementation_mode(layer_class): 'dropout': 0.1, 'recurrent_dropout': 0.1}, input_shape=(num_samples, timesteps, embedding_dim)) @rnn_test
def test_implementation_mode(layer_class): 'dropout': 0.1, 'recurrent_dropout': 0.1}, input_shape=(num_samples, timesteps, embedding_dim)) # Without bias layer_test(layer_class, kwargs={'units': units, ...
def gunzip(data): # contains the whole page content if output or getattr(f, 'extrabuf', None): try: output += f.extrabuf finally: break else:
def gunzip(data): # contains the whole page content if output or getattr(f, 'extrabuf', None): try: output += f.extrabuf[-f.extrasize:] finally: break else:
import unittest from os.path import join from scrapy.utils.gz import gunzip, is_gzipped from scrapy.http import Response, Headers from tests import tests_datadir
import unittest from os.path import join from w3lib.encoding import html_to_unicode from scrapy.utils.gz import gunzip, is_gzipped from scrapy.http import Response, Headers from tests import tests_datadir
class GunzipTest(unittest.TestCase): hdrs = Headers({"Content-Type": "application/x-gzip;charset=utf-8"}) r1 = Response("http://www.example.com", headers=hdrs) self.assertTrue(is_gzipped(r1))
class GunzipTest(unittest.TestCase): hdrs = Headers({"Content-Type": "application/x-gzip;charset=utf-8"}) r1 = Response("http://www.example.com", headers=hdrs) self.assertTrue(is_gzipped(r1)) def test_gunzip_illegal_eof(self): with open(join(SAMPLEDIR, 'unexpected-eof.gz'), 'rb') as...
from itertools import cycle as itertools_cycle, groupby from django.conf import settings from django.utils import timezone from django.utils.deprecation import RemovedInDjango40Warning from django.utils.html import conditional_escape, format_html from django.utils.lorem_ipsum import paragraphs, words from django.utils....
from itertools import cycle as itertools_cycle, groupby from django.conf import settings from django.utils import timezone from django.utils.deprecation import RemovedInDjango40Warning from django.utils.html import conditional_escape, escape, format_html from django.utils.lorem_ipsum import paragraphs, words from djang...
class CycleNode(Node): class DebugNode(Node): def render(self, context): from pprint import pformat output = [pformat(val) for val in context] output.append('\n\n') output.append(pformat(sys.modules)) return ''.join(output)
class CycleNode(Node): class DebugNode(Node): def render(self, context): if not settings.DEBUG: return '' from pprint import pformat output = [escape(pformat(val)) for val in context] output.append('\n\n') output.append(escape(pformat(sys.modules))) retu...
import sys from django.contrib.auth.models import Group from django.template import Context, Engine, TemplateSyntaxError from django.template.base import UNKNOWN_SOURCE from django.test import SimpleTestCase, override_settings
import sys from django.template import Context, Engine, TemplateSyntaxError from django.template.base import UNKNOWN_SOURCE from django.test import SimpleTestCase, override_settings
class TemplateTests(SimpleTestCase): with self.assertRaises(NoReverseMatch): t.render(Context()) def test_debug_tag_non_ascii(self): """ #23060 -- Test non-ASCII model representation in debug output. """ group = Group(name="清風") c1 = Context({"objs": [gro...
class TemplateTests(SimpleTestCase): with self.assertRaises(NoReverseMatch): t.render(Context()) def test_extends_generic_template(self): """ #24338 -- Allow extending django.template.backends.django.Template
class Session(BaseConfigDict): """ for name, value in request_headers.items(): value = value.decode('utf8') if name == 'User-Agent' and value.startswith('HTTPie/'): continue
class Session(BaseConfigDict): """ for name, value in request_headers.items(): if value is None: continue # Ignore explicitely unset headers value = value.decode('utf8') if name == 'User-Agent' and value.startswith('HTTPie/'): conti...
import os import shutil import sys import pytest
import os import shutil import sys from tempfile import gettempdir import pytest
class TestSession(SessionTestBase): r2 = http('--session=test', httpbin.url + '/headers', env=self.env()) assert HTTP_OK in r2 assert r2.json['headers']['User-Agent'] == 'custom'
class TestSession(SessionTestBase): r2 = http('--session=test', httpbin.url + '/headers', env=self.env()) assert HTTP_OK in r2 assert r2.json['headers']['User-Agent'] == 'custom' def test_download_in_session(self, httpbin): # https://github.com/jkbrzt/httpie/issues/412 self....
def _partition_tasks(worker): set_tasks["completed"] = {task for (task, status, ext) in task_history if status == 'DONE' and task in pending_tasks} set_tasks["already_done"] = {task for (task, status, ext) in task_history if status == 'DONE' and task not in pending_tasks and tas...
def _partition_tasks(worker): set_tasks["completed"] = {task for (task, status, ext) in task_history if status == 'DONE' and task in pending_tasks} set_tasks["already_done"] = {task for (task, status, ext) in task_history if status == 'DONE' and task not in pending_tasks and tas...
def _depth_first_search(set_tasks, current_task, visited): for task in current_task._requires(): if task not in visited: _depth_first_search(set_tasks, task, visited) if task in set_tasks["failed"] or task in set_tasks["upstream_failure"]: set_tasks["upstr...
def _depth_first_search(set_tasks, current_task, visited): for task in current_task._requires(): if task not in visited: _depth_first_search(set_tasks, task, visited) if task in set_tasks["ever_failed"] or task in set_tasks["upstream_failure"]: set_tasks["...
def _get_comments(group_tasks): _ORDERED_STATUSES = ( "already_done", "completed", "failed", "scheduling_error", "still_pending",
def _get_comments(group_tasks): _ORDERED_STATUSES = ( "already_done", "completed", "ever_failed", "failed", "scheduling_error", "still_pending",
def _summary_format(set_tasks, worker): str_output += 'Did not run any tasks' smiley = "" reason = "" if set_tasks["failed"]: smiley = ":(" reason = "there were failed tasks" if set_tasks["scheduling_error"]: reason += " and tasks whose scheduling failed" elif...
def _summary_format(set_tasks, worker): str_output += 'Did not run any tasks' smiley = "" reason = "" if set_tasks["ever_failed"]: if not set_tasks["failed"]: smiley = ":)" reason = "there were failed tasks but they all suceeded in a retry" else: s...
class ExecutionSummaryTest(LuigiTestCase): self.assertIn('Luigi Execution Summary', s) self.assertNotIn('00:00:00', s) self.assertNotIn('\n\n\n', s)
class ExecutionSummaryTest(LuigiTestCase): self.assertIn('Luigi Execution Summary', s) self.assertNotIn('00:00:00', s) self.assertNotIn('\n\n\n', s) """ Test that a task once crashing and then succeeding should be counted as no failure. """ def test_status_with_task_retry(self):...
class RetcodesTest(LuigiTestCase): with mock.patch('luigi.scheduler.Scheduler.add_task', new_func): self.run_and_expect('RequiringTask', 0) self.run_and_expect('RequiringTask --retcode-not-run 5', 5)
class RetcodesTest(LuigiTestCase): with mock.patch('luigi.scheduler.Scheduler.add_task', new_func): self.run_and_expect('RequiringTask', 0) self.run_and_expect('RequiringTask --retcode-not-run 5', 5) """ Test that a task once crashing and then succeeding should be counted as no ...
class PythonItemExporter(BaseItemExporter): return dict(self._serialize_dict(value)) if is_listlike(value): return [self._serialize_value(v) for v in value] if self.binary: return to_bytes(value, encoding=self.encoding) else: return to_unicode(valu...
class PythonItemExporter(BaseItemExporter): return dict(self._serialize_dict(value)) if is_listlike(value): return [self._serialize_value(v) for v in value] encode_func = to_bytes if self.binary else to_unicode if isinstance(value, (six.text_type, bytes)): ret...
class PythonItemExporterTest(BaseItemExporterTest): expected = {b'name': b'John\xc2\xa3', b'age': b'22'} self.assertEqual(expected, exporter.export_item(value)) class PprintItemExporterTest(BaseItemExporterTest):
class PythonItemExporterTest(BaseItemExporterTest): expected = {b'name': b'John\xc2\xa3', b'age': b'22'} self.assertEqual(expected, exporter.export_item(value)) def test_other_python_types_item(self): from datetime import datetime now = datetime.now() item = { 'b...
from asyncio.base_events import BaseEventLoop from concurrent.futures import Executor, ProcessPoolExecutor from enum import Enum, Flag from functools import partial, wraps import keyword import logging from multiprocessing import Manager
from asyncio.base_events import BaseEventLoop from concurrent.futures import Executor, ProcessPoolExecutor from enum import Enum, Flag from functools import partial, wraps import io import keyword import logging from multiprocessing import Manager
def format_file_in_place( """ if src.suffix == ".pyi": mode |= FileMode.PYI with tokenize.open(src) as src_buffer: src_contents = src_buffer.read() try: dst_contents = format_file_contents( src_contents, line_length=line_length, fast=fast, mode=mode
def format_file_in_place( """ if src.suffix == ".pyi": mode |= FileMode.PYI with open(src, "rb") as buf: newline, encoding, src_contents = prepare_input(buf.read()) try: dst_contents = format_file_contents( src_contents, line_length=line_length, fast=fast, mode=mode
def format_file_in_place( return False if write_back == write_back.YES: with open(src, "w", encoding=src_buffer.encoding) as f: f.write(dst_contents) elif write_back == write_back.DIFF: src_name = f"{src} (original)"
def format_file_in_place( return False if write_back == write_back.YES: with open(src, "w", encoding=encoding, newline=newline) as f: f.write(dst_contents) elif write_back == write_back.DIFF: src_name = f"{src} (original)"
def format_file_in_place( if lock: lock.acquire() try: sys.stdout.write(diff_contents) finally: if lock: lock.release()
def format_file_in_place( if lock: lock.acquire() try: f = io.TextIOWrapper( sys.stdout.buffer, encoding=encoding, newline=newline, write_through=True, ) f.write(diff_contents) f.d...
def format_stdin_to_stdout( `line_length`, `fast`, `is_pyi`, and `force_py36` arguments are passed to :func:`format_file_contents`. """ src = sys.stdin.read() dst = src try: dst = format_file_contents(src, line_length=line_length, fast=fast, mode=mode)
def format_stdin_to_stdout( `line_length`, `fast`, `is_pyi`, and `force_py36` arguments are passed to :func:`format_file_contents`. """ newline, encoding, src = prepare_input(sys.stdin.buffer.read()) dst = src try: dst = format_file_contents(src, line_length=line_length, fast=fast, mode=...
def format_stdin_to_stdout( finally: if write_back == WriteBack.YES: sys.stdout.write(dst) elif write_back == WriteBack.DIFF: src_name = "<stdin> (original)" dst_name = "<stdin> (formatted)" sys.stdout.write(diff(src, dst, src_name, dst_name)) def...
def format_stdin_to_stdout( finally: if write_back == WriteBack.YES: f = io.TextIOWrapper( sys.stdout.buffer, encoding=encoding, newline=newline, write_through=True, ) f.write(dst) f.detach() ...
def format_str( return dst_contents GRAMMARS = [ pygram.python_grammar_no_print_statement_no_exec_statement, pygram.python_grammar_no_print_statement,
def format_str( return dst_contents def prepare_input(src: bytes) -> Tuple[str, str, str]: """Analyze `src` and return a tuple of (newline, encoding, decoded_contents) Where `newline` is either CRLF or LF, and `decoded_contents` is decoded with universal newlines (i.e. only LF). """ srcbuf = ...
def lib2to3_parse(src_txt: str) -> Node: """Given a string with source, return the lib2to3 Node.""" grammar = pygram.python_grammar_no_print_statement if src_txt[-1] != "\n": nl = "\r\n" if "\r\n" in src_txt[:1024] else "\n" src_txt += nl for grammar in GRAMMARS: drv = driver.Dri...
def lib2to3_parse(src_txt: str) -> Node: """Given a string with source, return the lib2to3 Node.""" grammar = pygram.python_grammar_no_print_statement if src_txt[-1] != "\n": src_txt += "\n" for grammar in GRAMMARS: drv = driver.Driver(grammar, pytree.convert) try:
import asyncio from concurrent.futures import ThreadPoolExecutor from contextlib import contextmanager from functools import partial from io import StringIO import os from pathlib import Path import sys
import asyncio from concurrent.futures import ThreadPoolExecutor from contextlib import contextmanager from functools import partial from io import BytesIO, TextIOWrapper import os from pathlib import Path import sys
class BlackTestCase(unittest.TestCase): source, expected = read_data("../black") hold_stdin, hold_stdout = sys.stdin, sys.stdout try: sys.stdin, sys.stdout = StringIO(source), StringIO() sys.stdin.name = "<stdin>" black.format_stdin_to_stdout( ...
class BlackTestCase(unittest.TestCase): source, expected = read_data("../black") hold_stdin, hold_stdout = sys.stdin, sys.stdout try: sys.stdin = TextIOWrapper(BytesIO(source.encode("utf8")), encoding="utf8") sys.stdout = TextIOWrapper(BytesIO(), encoding="utf8") ...
class BlackTestCase(unittest.TestCase): expected, _ = read_data("expression.diff") hold_stdin, hold_stdout = sys.stdin, sys.stdout try: sys.stdin, sys.stdout = StringIO(source), StringIO() sys.stdin.name = "<stdin>" black.format_stdin_to_stdout( ...
class BlackTestCase(unittest.TestCase): expected, _ = read_data("expression.diff") hold_stdin, hold_stdout = sys.stdin, sys.stdout try: sys.stdin = TextIOWrapper(BytesIO(source.encode("utf8")), encoding="utf8") sys.stdout = TextIOWrapper(BytesIO(), encoding="utf8") ...
class BlackTestCase(unittest.TestCase): tmp_file = Path(black.dump_to_file(source)) hold_stdout = sys.stdout try: sys.stdout = StringIO() self.assertTrue(ff(tmp_file, write_back=black.WriteBack.DIFF)) sys.stdout.seek(0) actual = sys.stdout.read()
class BlackTestCase(unittest.TestCase): tmp_file = Path(black.dump_to_file(source)) hold_stdout = sys.stdout try: sys.stdout = TextIOWrapper(BytesIO(), encoding="utf8") self.assertTrue(ff(tmp_file, write_back=black.WriteBack.DIFF)) sys.stdout.seek(0) ...
class BlackTestCase(unittest.TestCase): result = CliRunner().invoke(black.main, ["-", option, "**()(!!*)"]) self.assertEqual(result.exit_code, 2) if __name__ == "__main__": unittest.main()
class BlackTestCase(unittest.TestCase): result = CliRunner().invoke(black.main, ["-", option, "**()(!!*)"]) self.assertEqual(result.exit_code, 2) def test_preserves_line_endings(self) -> None: with TemporaryDirectory() as workspace: test_file = Path(workspace) / "test.py...
class HadoopJarJobRunner(luigi.contrib.hadoop.JobRunner): arglist.append('{}@{}'.format(username, host)) else: arglist = [] if not job.jar() or not os.path.exists(job.jar()): logger.error("Can't find jar: %s, full path %s", job.jar(), os.path.abspath(job.jar()...
class HadoopJarJobRunner(luigi.contrib.hadoop.JobRunner): arglist.append('{}@{}'.format(username, host)) else: arglist = [] if not job.jar(): raise HadoopJarJobError("Jar not defined") if not os.path.exists(job.jar()): logger.error(...
default: :rc:`scatter.edgecolors` - 'none': No patch boundary will be drawn. - A color or sequence of colors. For non-filled markers, the *edgecolors* kwarg is ignored and forced to 'face' internally. plotnonfinite : bool, default: False Set to plot ...
default: :rc:`scatter.edgecolors` - 'none': No patch boundary will be drawn. - A color or sequence of colors. For non-filled markers, *edgecolors* is ignored. Instead, the color is determined like with 'face', i.e. from *c*, *colors*, or *facecolors*. ...
default: :rc:`scatter.edgecolors` path = marker_obj.get_path().transformed( marker_obj.get_transform()) if not marker_obj.is_filled(): edgecolors = 'face' if linewidths is None: linewidths = rcParams['lines.linewidth'] elif np.iterable(line...
default: :rc:`scatter.edgecolors` path = marker_obj.get_path().transformed( marker_obj.get_transform()) if not marker_obj.is_filled(): if linewidths is None: linewidths = rcParams['lines.linewidth'] elif np.iterable(linewidths):
default: :rc:`scatter.edgecolors` collection = mcoll.PathCollection( (path,), scales, facecolors=colors, edgecolors=edgecolors, linewidths=linewidths, offsets=offsets, transOffset=kwargs.pop('transform', self.transD...
default: :rc:`scatter.edgecolors` collection = mcoll.PathCollection( (path,), scales, facecolors=colors if marker_obj.is_filled() else 'none', edgecolors=edgecolors if marker_obj.is_filled() else colors, linewidths=linewidths, offs...
class TestScatter: with pytest.raises(ValueError): plt.scatter([1, 2, 3], [1, 2, 3], color=[1, 2, 3]) def test_scatter_size_arg_size(self): x = np.arange(4) with pytest.raises(ValueError):
class TestScatter: with pytest.raises(ValueError): plt.scatter([1, 2, 3], [1, 2, 3], color=[1, 2, 3]) def test_scatter_unfilled(self): coll = plt.scatter([0, 1, 2], [1, 3, 2], c=['0.1', '0.3', '0.5'], marker=mmarkers.MarkerStyle('o', fillstyle='none'), ...
from ..packages import six, rfc3986 from ..packages.rfc3986.exceptions import RFC3986Exception, ValidationError from ..packages.rfc3986.validators import Validator url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment']
from ..packages import six, rfc3986 from ..packages.rfc3986.exceptions import RFC3986Exception, ValidationError from ..packages.rfc3986.validators import Validator from ..packages.rfc3986 import abnf_regexp, normalizers, compat, misc url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment']
# Regex for detecting URLs with schemes. RFC 3986 Section 3.1 SCHEME_REGEX = re.compile(r"^(?:[a-zA-Z][a-zA-Z0-9+\-]*:|/)") class Url(namedtuple('Url', url_attrs)): """
# Regex for detecting URLs with schemes. RFC 3986 Section 3.1 SCHEME_REGEX = re.compile(r"^(?:[a-zA-Z][a-zA-Z0-9+\-]*:|/)") PATH_CHARS = abnf_regexp.UNRESERVED_CHARS_SET | abnf_regexp.SUB_DELIMITERS_SET | {':', '@', '/'} QUERY_CHARS = FRAGMENT_CHARS = PATH_CHARS | {'?'} class Url(namedtuple('Url', url_attrs)): "...
def split_first(s, delims): return s[:min_idx], s[min_idx + 1:], min_delim def parse_url(url): """ Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is
def split_first(s, delims): return s[:min_idx], s[min_idx + 1:], min_delim def _encode_invalid_chars(component, allowed_chars, encoding='utf-8'): """Percent-encodes a URI component without reapplying onto an already percent-encoded component. Based on rfc3986.normalizers.encode_component() """ ...
def parse_url(url): return Url() is_string = not isinstance(url, six.binary_type) if not is_string: url = url.decode("utf-8") # RFC 3986 doesn't like URLs that have a host but don't start # with a scheme and we support URLs like that so we need to
def parse_url(url): return Url() is_string = not isinstance(url, six.binary_type) # RFC 3986 doesn't like URLs that have a host but don't start # with a scheme and we support URLs like that so we need to
def parse_url(url): if not SCHEME_REGEX.search(url): url = "//" + url try: iri_ref = rfc3986.IRIReference.from_string(url, encoding="utf-8") except (ValueError, RFC3986Exception): six.raise_from(LocationParseError(url), None) def idna_encode(name): if name and any([ord(...
def parse_url(url): if not SCHEME_REGEX.search(url): url = "//" + url def idna_encode(name): if name and any([ord(x) > 128 for x in name]): try:
def idna_encode(name): raise LocationParseError(u"Name '%s' is not a valid IDNA label" % name) return name has_authority = iri_ref.authority is not None uri_ref = iri_ref.encode(idna_encoder=idna_encode) # rfc3986 strips the authority if it's invalid if has_authority and uri_re...
def idna_encode(name): raise LocationParseError(u"Name '%s' is not a valid IDNA label" % name) return name try: split_iri = misc.IRI_MATCHER.match(compat.to_str(url)).groupdict() iri_ref = rfc3986.IRIReference( split_iri['scheme'], split_iri['authority'], ...
def idna_encode(name): *validator.COMPONENT_NAMES ).validate(uri_ref) except ValidationError: six.raise_from(LocationParseError(url), None) # For the sake of backwards compatibility we put empty # string values for path if there are any defined values
def idna_encode(name): *validator.COMPONENT_NAMES ).validate(uri_ref) except ValidationError: return six.raise_from(LocationParseError(url), None) # For the sake of backwards compatibility we put empty # string values for path if there are any defined values
def test_invalid_host(self, location): 'http://user\\@google.com', 'http://google\\.com', 'user\\@google.com', 'http://google.com#fragment#', 'http://user@user@google.com/', ]) def test_invalid_url(self, url): with pytest.raises(LocationParseError):
def test_invalid_host(self, location): 'http://user\\@google.com', 'http://google\\.com', 'user\\@google.com', 'http://user@user@google.com/', # Invalid IDNA labels u'http://\uD7FF.com', u'http://❤️', # Unicode surrogates u'http://\uD800.com', ...
def test_invalid_url(self, url): ('HTTPS://Example.Com/?Key=Value', 'https://example.com/?Key=Value'), ('Https://Example.Com/#Fragment', 'https://example.com/#Fragment'), ('[::Ff%etH0%Ff]/%ab%Af', '[::ff%25etH0%Ff]/%AB%AF'), ]) def test_parse_url_normalization(self, url, expected_normali...
def test_invalid_url(self, url): ('HTTPS://Example.Com/?Key=Value', 'https://example.com/?Key=Value'), ('Https://Example.Com/#Fragment', 'https://example.com/#Fragment'), ('[::Ff%etH0%Ff]/%ab%Af', '[::ff%25etH0%Ff]/%AB%AF'), # Invalid characters for the query/fragment getting encoded ...
def test_parse_url_normalization(self, url, expected_normalized_url): # Uppercase IRI (u'http://Königsgäßchen.de/straße', Url('http', host='xn--knigsgchen-b4a3dun.de', path='/stra%C3%9Fe')) ] @pytest.mark.parametrize(
def test_parse_url_normalization(self, url, expected_normalized_url): # Uppercase IRI (u'http://Königsgäßchen.de/straße', Url('http', host='xn--knigsgchen-b4a3dun.de', path='/stra%C3%9Fe')), # Unicode Surrogates (u'http://google.com/\uD800', Url('http', host='google.com', path...
def str_repeat(arr, repeats): else: def rep(x, r): try: return bytes.__mul__(x, r) except TypeError:
def str_repeat(arr, repeats): else: def rep(x, r): if x is libmissing.NA: return x try: return bytes.__mul__(x, r) except TypeError:
class TestStringMethods: assert isinstance(rs, Series) tm.assert_series_equal(rs, xp) def test_match(self): # New match behavior introduced in 0.13 values = Series(["fooBAD__barBAD", np.nan, "foo"])
class TestStringMethods: assert isinstance(rs, Series) tm.assert_series_equal(rs, xp) def test_repeat_with_null(self): # GH: 31632 values = Series(["a", None], dtype="string") result = values.str.repeat([3, 4]) exp = Series(["aaa", None], dtype="string") tm.a...
Tests for L{twisted.web.twcgi}. """ import sys, os from twisted.trial import unittest from twisted.internet import reactor, interfaces, error from twisted.python import util, failure, log from twisted.web.http import NOT_FOUND, INTERNAL_SERVER_ERROR from twisted.web import client, twcgi, server, resource from twisted...
Tests for L{twisted.web.twcgi}. """ import sys import os import json from twisted.trial import unittest from twisted.internet import reactor, interfaces, error from twisted.python import util, failure, log from twisted.web.http import NOT_FOUND, INTERNAL_SERVER_ERROR from twisted.web import client, twcgi, server, res...
print print "cgi output" ''' class PythonScript(twcgi.FilteredScript): filter = sys.executable
print print "cgi output" ''' HEADER_OUTPUT_CGI = '''\ import json import os print("") print("") vals = {x:y for x,y in os.environ.items() if x.startswith("HTTP_")} print(json.dumps(vals)) ''' class PythonScript(twcgi.FilteredScript): filter = sys.executable
class CGITests(unittest.TestCase): return factory.deferred def test_duplicateHeaderCGI(self): """ If a CGI script emits two instances of the same header, both are sent in
class CGITests(unittest.TestCase): return factory.deferred def test_noProxyPassthrough(self): """ The CGI script is never called with the Proxy header passed through. """ cgiFilename = self.writeCGI(HEADER_OUTPUT_CGI) portnum = self.startServer(cgiFilename) ...
class CGIScript(resource.Resource): # Propagate HTTP headers for title, header in request.getAllHeaders().items(): envname = title.replace('-', '_').upper() if title not in ('content-type', 'content-length'): envname = "HTTP_" + envname env[envname] = ...
class CGIScript(resource.Resource): # Propagate HTTP headers for title, header in request.getAllHeaders().items(): envname = title.replace('-', '_').upper() if title not in ('content-type', 'content-length', 'proxy'): envname = "HTTP_" + envname env[en...
def _get_grouper( elif is_in_axis(gpr): # df.groupby('name') if gpr in obj: if validate: obj._check_label_or_level_ambiguity(gpr) in_axis, name, gpr = True, gpr, obj[gpr] exclusions.append(name) elif obj._is_level_refer...
def _get_grouper( elif is_in_axis(gpr): # df.groupby('name') if gpr in obj: if validate: obj._check_label_or_level_ambiguity(gpr, axis=axis) in_axis, name, gpr = True, gpr, obj[gpr] exclusions.append(name) elif obj._is_...
def test_groupby_groups_in_BaseGrouper(): result = df.groupby(["beta", pd.Grouper(level="alpha")]) expected = df.groupby(["beta", "alpha"]) assert result.groups == expected.groups
def test_groupby_groups_in_BaseGrouper(): result = df.groupby(["beta", pd.Grouper(level="alpha")]) expected = df.groupby(["beta", "alpha"]) assert result.groups == expected.groups @pytest.mark.parametrize("group_name", ["x", ["x"]]) def test_groupby_axis_1(group_name): # GH 27614 df = pd.DataFrame...
from thefuck.types import Command @pytest.fixture def pip_unknown_cmd(): return '''ERROR: unknown command "instatl" - maybe you meant "install"''' @pytest.fixture def pip_unknown_cmd_without_recommend(): return '''ERROR: unknown command "i"''' def test_match(pip_unknown_cmd, pip_unknown_cmd_without_recomm...
from thefuck.types import Command @pytest.fixture def pip_unknown_cmd_without_recommend(): return '''ERROR: unknown command "i"''' @pytest.fixture def broken(): return 'instatl' @pytest.fixture def suggested(): return 'install' @pytest.fixture def pip_unknown_cmd(broken, suggested): return 'ERRO...
def test_match(pip_unknown_cmd, pip_unknown_cmd_without_recommend): pip_unknown_cmd_without_recommend)) def test_get_new_command(pip_unknown_cmd): assert get_new_command(Command('pip instatl', pip_unknown_cmd)) == 'pip install'
def test_match(pip_unknown_cmd, pip_unknown_cmd_without_recommend): pip_unknown_cmd_without_recommend)) @pytest.mark.parametrize('script, broken, suggested, new_cmd', [ ('pip un+install thefuck', 'un+install', 'uninstall', 'pip uninstall thefuck'), ('pip instatl', 'instatl', 'inst...
def match(command): def get_new_command(command): broken_cmd = re.findall(r'ERROR: unknown command \"([a-z]+)\"', command.output)[0] new_cmd = re.findall(r'maybe you meant \"([a-z]+)\"', command.output)[0] return replace_argument(command.script, broken_cmd, new_cmd)
def match(command): def get_new_command(command): broken_cmd = re.findall(r'ERROR: unknown command "([^"]+)"', command.output)[0] new_cmd = re.findall(r'maybe you meant "([^"]+)"', command.output)[0] return replace_argument(command.script, broken_cmd, new_cmd)
def localpkgs(directory): cache[name] = {'path': fn, 'size': st.st_size, 'device': st.st_dev} return cache def parseArgs(): usage = _(""" Reposync is used to synchronize a remote yum repository to a local
def localpkgs(directory): cache[name] = {'path': fn, 'size': st.st_size, 'device': st.st_dev} return cache def is_subpath(path, root): root = os.path.realpath(root) path = os.path.realpath(os.path.join(root, path)) # join() is used below to ensure root ends with a slash return path.star...
def parseArgs(): parser.add_option("", "--download-metadata", dest="downloadmd", default=False, action="store_true", help=_("download all the non-default metadata")) (opts, args) = parser.parse_args() return (opts, args)
def parseArgs(): parser.add_option("", "--download-metadata", dest="downloadmd", default=False, action="store_true", help=_("download all the non-default metadata")) parser.add_option("", "--allow-path-traversal", default=False, action="store_true", help=_("Allow packages stored ...
def main(): else: local_repo_path = opts.destdir + '/' + repo.id if opts.delete and os.path.exists(local_repo_path): current_pkgs = localpkgs(local_repo_path)
def main(): else: local_repo_path = opts.destdir + '/' + repo.id # Ensure we don't traverse out of local_repo_path by dropping any # packages whose remote_path is absolute or contains up-level # references (unless explicitly allowed). # See RHBZ#1600221 for details. ...
class GroupBy(_GroupBy): base_func = getattr(libgroupby, how) for name, obj in self._iterate_slices(): if aggregate: result_sz = ngroups else: result_sz = len(obj.values) if not cython_dtype: cython_dtype = obj.values....
class GroupBy(_GroupBy): base_func = getattr(libgroupby, how) for name, obj in self._iterate_slices(): values = obj._data._values if aggregate: result_sz = ngroups else: result_sz = len(values) if not cython_dtype: ...
class GroupBy(_GroupBy): func(**kwargs) # Call func to modify indexer values in place if result_is_index: result = algorithms.take_nd(obj.values, result) if post_processing: result = post_processing(result, inferences)
class GroupBy(_GroupBy): func(**kwargs) # Call func to modify indexer values in place if result_is_index: result = algorithms.take_nd(values, result) if post_processing: result = post_processing(result, inferences)
def test_groupby_axis_1(group_name): results = df.groupby(group_name, axis=1).sum() expected = df.T.groupby(group_name).sum().T assert_frame_equal(results, expected)
def test_groupby_axis_1(group_name): results = df.groupby(group_name, axis=1).sum() expected = df.T.groupby(group_name).sum().T assert_frame_equal(results, expected) @pytest.mark.parametrize( "op, expected", [ ( "shift", { "time": [ ...
import logging from six.moves.urllib.parse import urljoin from w3lib.url import safe_url_string
import logging from six.moves.urllib.parse import urljoin, urlparse from w3lib.url import safe_url_string
class RedirectMiddleware(BaseRedirectMiddleware): if 'Location' not in response.headers or response.status not in allowed_status: return response location = safe_url_string(response.headers['location']) redirected_url = urljoin(request.url, location)
class RedirectMiddleware(BaseRedirectMiddleware): if 'Location' not in response.headers or response.status not in allowed_status: return response location = safe_url_string(response.headers['Location']) if response.headers['Location'].startswith(b'//'): request_scheme = ...
class RedirectMiddlewareTest(unittest.TestCase): del rsp.headers['Location'] assert self.mw.process_response(req, rsp, self.spider) is rsp def test_max_redirect_times(self): self.mw.max_redirect_times = 1
class RedirectMiddlewareTest(unittest.TestCase): del rsp.headers['Location'] assert self.mw.process_response(req, rsp, self.spider) is rsp def test_redirect_302_relative(self): url = 'http://www.example.com/302' url2 = '///i8n.example2.com/302' url3 = 'http://i8n.example2.co...
def _convert_by(by): @Substitution("\ndata : DataFrame") @Appender(_shared_docs["pivot"], indents=1) def pivot(data: "DataFrame", index=None, columns=None, values=None) -> "DataFrame": if values is None: cols = [columns] if index is None else [index, columns] append = index is None
def _convert_by(by): @Substitution("\ndata : DataFrame") @Appender(_shared_docs["pivot"], indents=1) def pivot(data: "DataFrame", index=None, columns=None, values=None) -> "DataFrame": if columns is None: raise TypeError("pivot() missing 1 required argument: 'columns'") if values is None: cols ...
class TestPivotTable: expected = DataFrame(data=data, index=index, columns=columns, dtype="object") tm.assert_frame_equal(result, expected) @pytest.mark.xfail( reason="MultiIndexed unstack with tuple names fails with KeyError GH#19966" )
class TestPivotTable: expected = DataFrame(data=data, index=index, columns=columns, dtype="object") tm.assert_frame_equal(result, expected) def test_pivot_columns_none_raise_error(self): # GH 30924 df = pd.DataFrame( {"col1": ["a", "b", "c"], "col2": [1, 2, 3], "col3": [...
def parse_uri(self, uri): "like so: " "swift+http://user:pass@authurl.com/v1/container/obj" ) LOG.error(_("Invalid store uri %(uri)s: %(reason)s") % locals()) raise exception.BadStoreUri(message=reason) pieces = urlparse.urlpar...
def parse_uri(self, uri): "like so: " "swift+http://user:pass@authurl.com/v1/container/obj" ) LOG.error(_("Invalid store URI: %(reason)s") % locals()) raise exception.BadStoreUri(message=reason) pieces = urlparse.urlparse(uri)
def parse_uri(self, uri): if creds: cred_parts = creds.split(':') if len(cred_parts) != 2: reason = (_("Badly formed credentials '%(creds)s' in Swift " "URI") % locals()) LOG.error(reason) raise exception.BadStor...
def parse_uri(self, uri): if creds: cred_parts = creds.split(':') if len(cred_parts) != 2: reason = (_("Badly formed credentials in Swift URI.")) LOG.error(reason) raise exception.BadStoreUri() user, key = cred_parts
def parse_uri(self, uri): path_parts.insert(0, netloc) self.auth_or_store_url = '/'.join(path_parts) except IndexError: reason = _("Badly formed Swift URI: %s") % uri LOG.error(reason) raise exception.BadStoreUri()
def parse_uri(self, uri): path_parts.insert(0, netloc) self.auth_or_store_url = '/'.join(path_parts) except IndexError: reason = _("Badly formed Swift URI.") LOG.error(reason) raise exception.BadStoreUri()
def get(self, location): except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() raise exception.NotFound(_("Swift could not find image at " "uri %(uri)s") % locals()) ...
def get(self, location): except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() msg = _("Swift could not find image at URI.") raise exception.NotFound(msg) else: raise
def add(self, image_id, image_file, image_size): except swiftclient.ClientException, e: if e.http_status == httplib.CONFLICT: raise exception.Duplicate(_("Swift already has an image at " "location %s") % location.get_uri()) msg = ...
def add(self, image_id, image_file, image_size): except swiftclient.ClientException, e: if e.http_status == httplib.CONFLICT: raise exception.Duplicate(_("Swift already has an image at " "this location.")) msg = (_("Failed to add ...
def delete(self, location): except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() raise exception.NotFound(_("Swift could not find image at " "uri %(uri)s") % locals()) ...
def delete(self, location): except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() msg = _("Swift could not find image at URI.") raise exception.NotFound(msg) else: raise...
def set_acls(self, location, public=False, read_tenants=[], except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() raise exception.NotFound(_("Swift could not find image at " ...
def set_acls(self, location, public=False, read_tenants=[], except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() msg = _("Swift could not find image at URI.") raise exception.N...
def read_fixed_bytes(self, num_bytes: int) -> bytes: """ read_bytes = self.read(num_bytes) if len(read_bytes) < num_bytes: raise EOFError(read_bytes) return read_bytes def read_pascal_bytes(self, string_length_size: int) -> bytes:
def read_fixed_bytes(self, num_bytes: int) -> bytes: """ read_bytes = self.read(num_bytes) if len(read_bytes) < num_bytes: raise EOFError("Fewer than 'num_bytes' bytes remaining in the " "underlying bytestream") return read_bytes def read_pascal_bytes...
def from_bytes( Raises: ValueError: The provided byte string is not an ``openssh-key-v1`` key list or the declared key count is negative. UserWarning: The check numbers in the decrypted private byte string do not match (likely due to an incorrect passphra...
def from_bytes( Raises: ValueError: The provided byte string is not an ``openssh-key-v1`` key list, when the declared key count is negative, or when an EOF is found while parsing the key. UserWarning: The check numbers in the decrypted private byte strin...
def from_bytes( at the end of the decrypted private byte string are not as expected. """ byte_stream = PascalStyleByteStream(byte_string) header = byte_stream.read_from_format_instructions_dict( cls.HEADER_FORMAT_INSTRUCTIONS_DICT ) i...
def from_bytes( at the end of the decrypted private byte string are not as expected. """ try: byte_stream = PascalStyleByteStream(byte_string) header = byte_stream.read_from_format_instructions_dict( cls.HEADER_FORMAT_INSTRUCTIONS_...
class FileSystemStorage(Storage): if not os.path.exists(directory): try: if self.directory_permissions_mode is not None: # os.makedirs applies the global umask, so we reset it, # for consistency with file_permissions_mode behavior. ...
class FileSystemStorage(Storage): if not os.path.exists(directory): try: if self.directory_permissions_mode is not None: # Set the umask because os.makedirs() doesn't apply the "mode" # argument to intermediate-level directories. ...
import time import unittest from datetime import datetime, timedelta from io import StringIO from urllib.request import urlopen from django.core.cache import cache
import time import unittest from datetime import datetime, timedelta from io import StringIO from pathlib import Path from urllib.request import urlopen from django.core.cache import cache
class FileStoragePermissions(unittest.TestCase): @override_settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765) def test_file_upload_directory_permissions(self): self.storage = FileSystemStorage(self.storage_dir) name = self.storage.save("the_directory/the_file", ContentFile("data")) dir_mo...
class FileStoragePermissions(unittest.TestCase): @override_settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765) def test_file_upload_directory_permissions(self): self.storage = FileSystemStorage(self.storage_dir) name = self.storage.save('the_directory/subdir/the_file', ContentFile('data')) ...
import sys import tempfile import unittest from io import StringIO from django.conf import settings from django.contrib.staticfiles import finders, storage
import sys import tempfile import unittest from io import StringIO from pathlib import Path from django.conf import settings from django.contrib.staticfiles import finders, storage
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_permissions(self): call_command('collectstatic', **self.command_params) test_file = os.path.join(settings.STATIC_ROOT, "test.txt") test_dir = os.path.join(settings.STATIC_ROOT, "subdir") file_mod...
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_permissions(self): call_command('collectstatic', **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / 'test.txt' file_mode = test_file.stat().st_mode & 0o777 ...
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_default_permissions(self): call_command('collectstatic', **self.command_params) test_file = os.path.join(settings.STATIC_ROOT, "test.txt") test_dir = os.path.join(settings.STATIC_ROOT, "subdir") ...
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_default_permissions(self): call_command('collectstatic', **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / 'test.txt' file_mode = test_file.stat().st_mode ...
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_subclass_of_static_storage(self): call_command('collectstatic', **self.command_params) test_file = os.path.join(settings.STATIC_ROOT, "test.txt") test_dir = os.path.join(settings.STATIC_ROOT, "subdir") ...
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_subclass_of_static_storage(self): call_command('collectstatic', **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / 'test.txt' file_mode = test_file.stat().s...
import grp import os import re import platform import pwd import shutil import socket import time import re from ansible.module_utils._text import to_native from ansible.module_utils.basic import load_platform_subclass, AnsibleModule try:
import grp import os import re import platform import pty import pwd import select import shutil import socket import subprocess import time from ansible.module_utils._text import to_native, to_bytes, to_text from ansible.module_utils.basic import load_platform_subclass, AnsibleModule try:
class User(object): cmd.append(self.ssh_comment) cmd.append('-f') cmd.append(ssh_key_file) cmd.append('-N') if self.ssh_passphrase is not None: cmd.append(self.ssh_passphrase) else: cmd.append('') (rc, out, err) = self.execute_command(cmd)...
class User(object): cmd.append(self.ssh_comment) cmd.append('-f') cmd.append(ssh_key_file) if self.ssh_passphrase is not None: if self.module.check_mode: self.module.debug('In check mode, would have run: "%s"' % cmd) return (0, '', '') ...
import pytest import os from thefuck.rules.fix_file import match, get_new_command from tests.utils import Command # (script, file, line, col (or None), stdout, stderr)
import pytest import os from thefuck.rules.fix_file import match, get_new_command from tests.utils import Command from thefuck.types import Settings # (script, file, line, col (or None), stdout, stderr)
awk: ./a:2: BEGIN { print "Hello, world!" + } awk: ./a:2: ^ syntax error """), ('llc a.ll', 'a.ll', 1, None, '', """ llc: a.ll:1:1: error: expected top-level entity + ^ """), ('go build a.go', 'a.go', 1, None, '', """ can't load package: a.go:1:1: expected 'package', found '+' """), (...
awk: ./a:2: BEGIN { print "Hello, world!" + } awk: ./a:2: ^ syntax error """), ('llc a.ll', 'a.ll', 1, 2, '', """ llc: a.ll:1:2: error: expected top-level entity + ^ """), ('go build a.go', 'a.go', 1, 2, '', """ can't load package: a.go:1:2: expected 'package', found '+' """), ('make'...
def test_not_file(mocker, monkeypatch, test): def test_get_new_command(mocker, monkeypatch, test): mocker.patch('os.path.isfile', return_value=True) monkeypatch.setenv('EDITOR', 'dummy_editor') cmd = Command(script=test[0], stdout=test[4], stderr=test[5]) assert (get_new_command(cmd, None) == 'd...
def test_not_file(mocker, monkeypatch, test): def test_get_new_command(mocker, monkeypatch, test): mocker.patch('os.path.isfile', return_value=True) monkeypatch.setenv('EDITOR', 'dummy_editor') cmd = Command(script=test[0], stdout=test[4], stderr=test[5]) #assert (get_new_command(cmd, Settings({})) == ...
import re import os from thefuck.utils import memoize from thefuck import shells patterns = ( # js, node: '^ at {file}:{line}:{col}',
import re import os from thefuck.utils import memoize, wrap_settings from thefuck import shells # order is important: only the first match is considered patterns = ( # js, node: '^ at {file}:{line}:{col}',
patterns = ( # lua: '^lua: {file}:{line}:', # fish: '^{file} \(line {line}\):', # bash, sh, ssh: '^{file}: line {line}: ', # ghc, make, ruby, zsh: '^{file}:{line}:', # cargo, clang, gcc, go, pep8, rustc: '^{file}:{line}:{col}', # pe...
patterns = ( # lua: '^lua: {file}:{line}:', # fish: '^{file} \\(line {line}\\):', # bash, sh, ssh: '^{file}: line {line}: ', # cargo, clang, gcc, go, pep8, rustc: '^{file}:{line}:{col}', # ghc, make, ruby, zsh: '^{file}:{line}:', # ...
def match(command, settings): return _search(command.stderr) or _search(command.stdout) def get_new_command(command, settings): m = _search(command.stderr) or _search(command.stdout) # Note: there does not seem to be a standard for columns, so they are just # ignored for now editor_call = '{} {} ...
def match(command, settings): return _search(command.stderr) or _search(command.stdout) @wrap_settings({'fixlinecmd': '{editor} {file} +{line}', 'fixcolcmd': None}) def get_new_command(command, settings): m = _search(command.stderr) or _search(command.stdout) # Note: there does not seem t...
from ansible.release import __version__ from ansible.utils.collection_loader import set_collection_playbook_paths from ansible.utils.display import Display from ansible.utils.path import unfrackpath from ansible.vars.manager import VariableManager
from ansible.release import __version__ from ansible.utils.collection_loader import set_collection_playbook_paths from ansible.utils.display import Display from ansible.utils.path import unfrackpath from ansible.utils.unsafe_proxy import AnsibleUnsafeBytes from ansible.vars.manager import VariableManager