buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
def test_clone_functional_model(): new_model.train_on_batch(None, val_out) def test_clone_sequential_model(): val_a = np.random.random((10, 4)) val_out = np.random.random((10, 4))
def test_clone_functional_model(): new_model.train_on_batch(None, val_out) def test_clone_functional_model_with_multi_outputs(): input_layer = keras.Input(shape=(4,)) # Layer with single input and multiple outputs layer1 = keras.layers.Lambda(lambda x: [x + 1, x], lam...
else: from twisted.internet import defer, reactor, ssl logger = logging.getLogger(__name__)
else: from twisted.internet import defer, reactor, ssl from .utils.misc import arg_to_iter logger = logging.getLogger(__name__)
class MailSender(object): msg = MIMEMultipart() else: msg = MIMENonMultipart(*mimetype.split('/', 1)) msg['From'] = self.mailfrom msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(localtime=True)
class MailSender(object): msg = MIMEMultipart() else: msg = MIMENonMultipart(*mimetype.split('/', 1)) to = list(arg_to_iter(to)) cc = list(arg_to_iter(cc)) msg['From'] = self.mailfrom msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(local...
class MailSenderTest(unittest.TestCase): def test_send(self): mailsender = MailSender(debug=True) mailsender.send(to=['test@scrapy.org'], subject='subject', body='body', _callback=self._catch_mail_sent) assert self.catched_msg
class MailSenderTest(unittest.TestCase): def test_send(self): mailsender = MailSender(debug=True) mailsender.send(to=['test@scrapy.org'], subject='subject', body='body', _callback=self._catch_mail_sent) assert self.catched_msg
class MailSenderTest(unittest.TestCase): self.assertEqual(msg.get_payload(), 'body') self.assertEqual(msg.get('Content-Type'), 'text/plain') def test_send_html(self): mailsender = MailSender(debug=True) mailsender.send(to=['test@scrapy.org'], subject='subject', body='<p>body</p>', m...
class MailSenderTest(unittest.TestCase): self.assertEqual(msg.get_payload(), 'body') self.assertEqual(msg.get('Content-Type'), 'text/plain') def test_send_single_values_to_and_cc(self): mailsender = MailSender(debug=True) mailsender.send(to='test@scrapy.org', subject='subject', body...
class MailSenderTest(unittest.TestCase): mailsender = MailSender(debug=True) mailsender.send(to=['test@scrapy.org'], subject=subject, body=body, attachs=attachs, charset='utf-8', _callback=self._catch_mail_sent) assert self.catched_msg self.assertEqual(self.catc...
class MailSenderTest(unittest.TestCase): mailsender = MailSender(debug=True) mailsender.send(to=['test@scrapy.org'], subject=subject, body=body, attachs=attachs, charset='utf-8', _callback=self._catch_mail_sent) assert self.catched_msg se...
class MailSenderTest(unittest.TestCase): msg = self.catched_msg['msg'] self.assertEqual(msg['subject'], subject) self.assertEqual(msg.get_charset(), Charset('utf-8')) self.assertEqual(msg.get('Content-Type'), 'multipart/mixed; charset="utf-8"') payload = msg.get_payload() ...
class MailSenderTest(unittest.TestCase): msg = self.catched_msg['msg'] self.assertEqual(msg['subject'], subject) self.assertEqual(msg.get_charset(), Charset('utf-8')) self.assertEqual(msg.get('Content-Type'), 'multipart/mixed; charset="utf-8"') payload =...
class TestUtil(unittest.TestCase): "playlist":[{"controls":{"all":null}}] }''') inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"' json_code = js_to_json(inp) self.assertEqual(json.loads(json_code...
class TestUtil(unittest.TestCase): "playlist":[{"controls":{"all":null}}] }''') inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"''' self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''') inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabaner...
def js_to_json(code): if v in ('true', 'false', 'null'): return v if v.startswith('"'): return v if v.startswith("'"): v = v[1:-1] v = re.sub(r"\\\\|\\'|\"", lambda m: { '\\\\': '\\\\',
def js_to_json(code): if v in ('true', 'false', 'null'): return v if v.startswith('"'): v = re.sub(r"\\'", "'", v[1:-1]) elif v.startswith("'"): v = v[1:-1] v = re.sub(r"\\\\|\\'|\"", lambda m: { '\\\\': '\\\\',
class RangeIndex(Int64Index): @Appender(_index_shared_docs["get_indexer"]) def get_indexer(self, target, method=None, limit=None, tolerance=None): if not (method is None and tolerance is None and is_list_like(target)): return super().get_indexer(target, method=method, tolerance=tolerance) ...
class RangeIndex(Int64Index): @Appender(_index_shared_docs["get_indexer"]) def get_indexer(self, target, method=None, limit=None, tolerance=None): if com.any_not_none(method, tolerance, limit) or not is_list_like(target): return super().get_indexer( target, method=method, to...
class TestDataFrameIndexing(TestData): assert mask[-5:].all() assert not mask[:-5].any() def test_set_dataframe_column_ns_dtype(self): x = DataFrame([datetime.now(), datetime.now()]) assert x[0].dtype == np.dtype("M8[ns]")
class TestDataFrameIndexing(TestData): assert mask[-5:].all() assert not mask[:-5].any() def test_reindex_limit(self): # GH 28631 data = [["A", "A", "A"], ["B", "B", "B"], ["C", "C", "C"], ["D", "D", "D"]] exp_data = [ ["A", "A", "A"], ["B", "B", "B"]...
class TestRangeIndex(Numeric): expected = np.array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5], dtype=np.intp) tm.assert_numpy_array_equal(indexer, expected) def test_join_outer(self): # join with Int64Index other = Int64Index(np.arange(25, 14, -1))
class TestRangeIndex(Numeric): expected = np.array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5], dtype=np.intp) tm.assert_numpy_array_equal(indexer, expected) def test_get_indexer_limit(self): # GH 28631 idx = RangeIndex(4) target = RangeIndex(6) result = idx.get_indexer(target, m...
def serialize_response( errors.extend(errors_) if errors: raise ValidationError(errors) return jsonable_encoder( value, include=include,
def serialize_response( errors.extend(errors_) if errors: raise ValidationError(errors) if skip_defaults and isinstance(response, BaseModel): value = response.dict(skip_defaults=skip_defaults) return jsonable_encoder( value, include=inc...
from thefuck.types import Command @pytest.fixture def output(branch_name): return "fatal: A branch named '{}' already exists.".format(branch_name) @pytest.fixture
from thefuck.types import Command @pytest.fixture def output(src_branch_name): return "fatal: A branch named '{}' already exists.".format(src_branch_name) @pytest.fixture
def new_command(branch_name): 'git branch -D {0} && git checkout -b {0}', 'git checkout {0}']] @pytest.mark.parametrize('script, branch_name', [ ('git branch foo', 'foo'), ('git checkout bar', 'bar')]) def test_match(output, script, branch_name): assert match(Command(script, output)) @pytest.mark.pa...
def new_command(branch_name): 'git branch -D {0} && git checkout -b {0}', 'git checkout {0}']] @pytest.mark.parametrize('script, src_branch_name, branch_name', [ ('git branch foo', 'foo', 'foo'), ('git checkout bar', 'bar', 'bar'), ('git checkout -b "let\'s-push-this"', '"let\'s-push-this"', '"let...
from thefuck.utils import eager @git_support def match(command): return ("fatal: A branch named '" in command.output and " already exists." in command.output) @git_support @eager def get_new_command(command): branch_name = re.findall( r"fatal: A branch named '([^']*)' already exists.", com...
from thefuck.utils import eager @git_support def match(command): return ("fatal: A branch named '" in command.output and "' already exists." in command.output) @git_support @eager def get_new_command(command): branch_name = re.findall( r"fatal: A branch named '(.+)' already exists.", comma...
class Axes(_AxesBase): @_preprocess_data(replace_names=["y", "xmin", "xmax", "colors"], label_namer="y") def hlines(self, y, xmin, xmax, colors='k', linestyles='solid', label='', **kwargs): """ Plot horizontal lines at each *y* from *xmin* to *xmax*.
class Axes(_AxesBase): @_preprocess_data(replace_names=["y", "xmin", "xmax", "colors"], label_namer="y") def hlines(self, y, xmin, xmax, colors=None, linestyles='solid', label='', **kwargs): """ Plot horizontal lines at each *y* from *xmin* to *xmax*.
class Axes(_AxesBase): Respective beginning and end of each line. If scalars are provided, all lines will have same length. colors : list of colors, default: 'k' linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, optional
class Axes(_AxesBase): Respective beginning and end of each line. If scalars are provided, all lines will have same length. colors : list of colors, default: :rc:`lines.color` linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, optional
class Axes(_AxesBase): @_preprocess_data(replace_names=["x", "ymin", "ymax", "colors"], label_namer="x") def vlines(self, x, ymin, ymax, colors='k', linestyles='solid', label='', **kwargs): """ Plot vertical lines.
class Axes(_AxesBase): @_preprocess_data(replace_names=["x", "ymin", "ymax", "colors"], label_namer="x") def vlines(self, x, ymin, ymax, colors=None, linestyles='solid', label='', **kwargs): """ Plot vertical lines.
class Axes(_AxesBase): Respective beginning and end of each line. If scalars are provided, all lines will have same length. colors : list of colors, default: 'k' linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, optional
class Axes(_AxesBase): Respective beginning and end of each line. If scalars are provided, all lines will have same length. colors : list of colors, default: :rc:`lines.color` linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, optional
def hist2d( # Autogenerated by boilerplate.py. Do not edit as changes will be lost. @_copy_docstring_and_deprecators(Axes.hlines) def hlines( y, xmin, xmax, colors='k', linestyles='solid', label='', *, data=None, **kwargs): return gca().hlines( y, xmin, xmax, colors=colors, linestyles=lines...
def hist2d( # Autogenerated by boilerplate.py. Do not edit as changes will be lost. @_copy_docstring_and_deprecators(Axes.hlines) def hlines( y, xmin, xmax, colors=None, linestyles='solid', label='', *, data=None, **kwargs): return gca().hlines( y, xmin, xmax, colors=colors, linestyles=line...
def violinplot( # Autogenerated by boilerplate.py. Do not edit as changes will be lost. @_copy_docstring_and_deprecators(Axes.vlines) def vlines( x, ymin, ymax, colors='k', linestyles='solid', label='', *, data=None, **kwargs): return gca().vlines( x, ymin, ymax, colors=colors, linestyles=l...
def violinplot( # Autogenerated by boilerplate.py. Do not edit as changes will be lost. @_copy_docstring_and_deprecators(Axes.vlines) def vlines( x, ymin, ymax, colors=None, linestyles='solid', label='', *, data=None, **kwargs): return gca().vlines( x, ymin, ymax, colors=colors, linestyles=...
def test_vlines(): ax5.set_xlim(0, 15) @image_comparison(['hlines_basic', 'hlines_with_nan', 'hlines_masked'], extensions=['png']) def test_hlines():
def test_vlines(): ax5.set_xlim(0, 15) def test_vlines_default(): fig, ax = plt.subplots() with mpl.rc_context({'lines.color': 'red'}): lines = ax.vlines(0.5, 0, 1) assert mpl.colors.same_color(lines.get_color(), 'red') @image_comparison(['hlines_basic', 'hlines_with_nan', 'hlines_masked...
def test_hlines(): ax5.set_ylim(0, 15) @pytest.mark.parametrize('data', [[1, 2, 3, np.nan, 5], np.ma.masked_equal([1, 2, 3, 4, 5], 4)]) @check_figures_equal(extensions=["png"])
def test_hlines(): ax5.set_ylim(0, 15) def test_hlines_default(): fig, ax = plt.subplots() with mpl.rc_context({'lines.color': 'red'}): lines = ax.hlines(0.5, 0, 1) assert mpl.colors.same_color(lines.get_color(), 'red') @pytest.mark.parametrize('data', [[1, 2, 3, np.nan, 5], ...
def _make_ghost_gridspec_slots(fig, gs): # this gridspec slot doesn't have an axis so we # make a "ghost". ax = fig.add_subplot(gs[nn]) ax.set_frame_on(False) ax.set_xticks([]) ax.set_yticks([]) ax.set_facecolor((1, 0, 0, 0)) def _mak...
def _make_ghost_gridspec_slots(fig, gs): # this gridspec slot doesn't have an axis so we # make a "ghost". ax = fig.add_subplot(gs[nn]) ax.set_visible(False) def _make_layout_margins(ax, renderer, h_pad, w_pad):
class FigureCanvasBase: def inaxes(self, xy): """ Check if a point is in an axes. Parameters ----------
class FigureCanvasBase: def inaxes(self, xy): """ Return the topmost visible `~.axes.Axes` containing the point *xy*. Parameters ----------
class FigureCanvasBase: Returns ------- axes: topmost axes containing the point, or None if no axes. """ axes_list = [a for a in self.figure.get_axes() if a.patch.contains_point(xy)] if axes_list: axes = cbook._topmost_artist(axes_list)...
class FigureCanvasBase: Returns ------- axes : `~matplotlib.axes.Axes` or None The topmost visible axes containing the point, or None if no axes. """ axes_list = [a for a in self.figure.get_axes() if a.patch.contains_point(xy) and a.get_visible()...
def test_aspect_nonlinear_adjustable_datalim(): ax.apply_aspect() assert ax.get_xlim() == pytest.approx([1*10**(1/2), 100/10**(1/2)]) assert ax.get_ylim() == (1 / 101, 1 / 11)
def test_aspect_nonlinear_adjustable_datalim(): ax.apply_aspect() assert ax.get_xlim() == pytest.approx([1*10**(1/2), 100/10**(1/2)]) assert ax.get_ylim() == (1 / 101, 1 / 11) def test_invisible_axes(): # invisible axes should not respond to events... fig, ax = plt.subplots() assert fig.canvas...
class DataFrame(NDFrame): ) return result def transpose(self, *args, **kwargs): """ Transpose index and columns.
class DataFrame(NDFrame): ) return result def transpose(self, *args, copy: bool = False): """ Transpose index and columns.
class DataFrame(NDFrame): Parameters ---------- *args, **kwargs Additional arguments and keywords have no effect but might be accepted for compatibility with numpy. Returns -------
class DataFrame(NDFrame): Parameters ---------- *args : tuple, optional Accepted for compatibility with NumPy. copy : bool, default False Whether to copy the data after transposing, even for DataFrames with a single dtype. Note that a cop...
class DataFrame(NDFrame): dtype: object """ nv.validate_transpose(args, dict()) return super().transpose(1, 0, **kwargs) T = property(transpose)
class DataFrame(NDFrame): dtype: object """ nv.validate_transpose(args, dict()) # construct the args dtypes = list(self.dtypes) if self._is_homogeneous_type and dtypes and is_extension_array_dtype(dtypes[0]): # We have EAs with the same dtype. We can preserve...
class NDFrame(PandasObject, SelectionMixin): self._data.set_axis(axis, labels) self._clear_item_cache() def transpose(self, *args, **kwargs): """ Permute the dimensions of the %(klass)s Parameters ---------- args : %(args_transpose)s copy : bool, def...
class NDFrame(PandasObject, SelectionMixin): self._data.set_axis(axis, labels) self._clear_item_cache() def swapaxes(self, axis1, axis2, copy=True): """ Interchange axes and swap values axes appropriately.
def box_df_fail(request): return request.param @pytest.fixture( params=[ (pd.Index, False), (pd.Series, False), (pd.DataFrame, False), pytest.param((pd.DataFrame, True), marks=pytest.mark.xfail), (tm.to_array, False), ], ids=id_func, ) def box_transpose_fail(req...
def box_df_fail(request): return request.param @pytest.fixture(params=[pd.Index, pd.Series, pd.DataFrame, tm.to_array], ids=id_func) def box_with_array(request): """
class TestPeriodIndexArithmetic: rng -= pd.offsets.MonthEnd(5) tm.assert_index_equal(rng, expected) def test_pi_add_offset_n_gt1(self, box_transpose_fail): # GH#23215 # add offset to PeriodIndex with freq.n > 1 box, transpose = box_transpose_fail per = pd.Period("20...
class TestPeriodIndexArithmetic: rng -= pd.offsets.MonthEnd(5) tm.assert_index_equal(rng, expected) @pytest.mark.parametrize("transpose", [True, False]) def test_pi_add_offset_n_gt1(self, box_with_array, transpose): # GH#23215 # add offset to PeriodIndex with freq.n > 1 ...
class TestPeriodIndexArithmetic: with pytest.raises(IncompatibleFrequency, match=msg): rng -= other def test_parr_add_sub_td64_nat(self, box_transpose_fail): # GH#23320 special handling for timedelta64("NaT") box, transpose = box_transpose_fail pi = pd.period_range("199...
class TestPeriodIndexArithmetic: with pytest.raises(IncompatibleFrequency, match=msg): rng -= other @pytest.mark.parametrize("transpose", [True, False]) def test_parr_add_sub_td64_nat(self, box_with_array, transpose): # GH#23320 special handling for timedelta64("NaT") pi = p...
class TestPeriodIndexArithmetic: TimedeltaArray._from_sequence(["NaT"] * 9), ], ) def test_parr_add_sub_tdt64_nat_array(self, box_df_fail, other): # FIXME: DataFrame fails because when when operating column-wise # timedelta64 entries become NaT and are treated like datetimes...
class TestPeriodIndexArithmetic: TimedeltaArray._from_sequence(["NaT"] * 9), ], ) def test_parr_add_sub_tdt64_nat_array(self, box_with_array, other): pi = pd.period_range("1994-04-01", periods=9, freq="19D") expected = pd.PeriodIndex(["NaT"] * 9, freq="19D") obj = tm...
class BaseReshapingTests(BaseExtensionTests): # Check that we have a view, not a copy result[0] = result[1] assert data[0] == data[1]
class BaseReshapingTests(BaseExtensionTests): # Check that we have a view, not a copy result[0] = result[1] assert data[0] == data[1] def test_transpose(self, data): df = pd.DataFrame({"A": data[:4], "B": data[:4]}, index=["a", "b", "c", "d"]) result = df.T expected ...
class TestReshaping(BaseJSON, base.BaseReshapingTests): # this matches otherwise return super().test_unstack(data, index) class TestGetitem(BaseJSON, base.BaseGetitemTests): pass
class TestReshaping(BaseJSON, base.BaseReshapingTests): # this matches otherwise return super().test_unstack(data, index) @pytest.mark.xfail(reason="Inconsistent sizes.") def test_transpose(self, data): super().test_transpose(data) class TestGetitem(BaseJSON, base.BaseGetitemTests): ...
class TestReshaping(BaseNumPyTests, base.BaseReshapingTests): # Fails creating expected super().test_merge_on_extension_array_duplicates(data) class TestSetitem(BaseNumPyTests, base.BaseSetitemTests): @skip_nested
class TestReshaping(BaseNumPyTests, base.BaseReshapingTests): # Fails creating expected super().test_merge_on_extension_array_duplicates(data) @skip_nested def test_transpose(self, data): super().test_transpose(data) class TestSetitem(BaseNumPyTests, base.BaseSetitemTests): @skip_...
class Serializer(object): """ A swappable class for serialization. This handles most types of data as well as the following output formats:: * json * jsonp * xml * yaml * html * plist (see http://explorapp.com/biplist/) It was designed to ma...
class Serializer(object): """ A swappable class for serialization. This handles most types of data as well as the following output formats:: * json * jsonp * xml * yaml * html * plist (see http://explorapp.com/biplist/) It was designed to make changing ...
class Serializer(object): 'html': 'text/html', 'plist': 'application/x-plist', } def __init__(self, formats=None, content_types=None, datetime_formatting=None): self.supported_formats = [] self.datetime_formatting = getattr(settings, 'TASTYPIE_DATETIME_FORMATTING', 'iso-8601...
class Serializer(object): 'html': 'text/html', 'plist': 'application/x-plist', } def __init__(self, formats=None, content_types=None, datetime_formatting=None): self.supported_formats = [] self.datetime_formatting = getattr(settings, 'TASTYPIE_DATETIME_FORMATTING', 'iso-8601') ...
def get_mime_for_format(self, format): return self.content_types[format] except KeyError: return 'application/json' def format_datetime(self, data): """ A hook to control how datetimes are formatted. Can be overridden at the ``Serializer`` level ...
def get_mime_for_format(self, format): return self.content_types[format] except KeyError: return 'application/json' def format_datetime(self, data): """ A hook to control how datetimes are formatted. Can be overridden at the ``Serializer`` level (``datetime_...
def deserialize(self, content, format='application/json'): if hasattr(self, "from_%s" % short_format): desired_format = short_format break if desired_format is None: raise UnsupportedFormat("The format indicated '%s' had no available d...
def deserialize(self, content, format='application/json'): if hasattr(self, "from_%s" % short_format): desired_format = short_format break if desired_format is None: raise UnsupportedFormat("The format indicated '%s' had no available deseriali...
def to_simple(self, data, options): """ For a piece of data, attempts to recognize it and provide a simplified form of something complex. This brings complex Python data structures down to native types of the serialization format(s). """
def to_simple(self, data, options): """ For a piece of data, attempts to recognize it and provide a simplified form of something complex. This brings complex Python data structures down to native types of the serialization format(s). """
def from_etree(self, data): return False else: return None def to_json(self, data, options=None): """ Given some Python data, produces JSON output.
def from_etree(self, data): return False else: return None def to_json(self, data, options=None): """ Given some Python data, produces JSON output.
def to_xml(self, data, options=None): Given some Python data, produces XML output. """ options = options or {} if lxml is None: raise ImproperlyConfigured("Usage of the XML aspects requires lxml.") return tostring(self.to_etree(data, options), xml_de...
def to_xml(self, data, options=None): Given some Python data, produces XML output. """ options = options or {} if lxml is None: raise ImproperlyConfigured("Usage of the XML aspects requires lxml.") return tostring(self.to_etree(data, options), xml_declaration=True, ...
def get_type_string(data): Translates a Python data type into a string format. """ data_type = type(data) if data_type in (int, long): return 'integer' elif data_type == float:
def get_type_string(data): Translates a Python data type into a string format. """ data_type = type(data) if data_type in (int, long): return 'integer' elif data_type == float:
def setUp(self): def tearDown(self): # wait on the server thread to terminate self.evt.wait(4.0) # XXX this code does not work, and in fact stop_serving doesn't exist. if not self.evt.is_set(): self.evt.set() stop_serving() raise RuntimeError("tim...
def setUp(self): def tearDown(self): # wait on the server thread to terminate self.evt.wait() # disable traceback reporting xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = False
def test_unicode_host(self): server = xmlrpclib.ServerProxy("http://%s:%d/RPC2" % (ADDR, PORT)) self.assertEqual(server.add("a", "\xe9"), "a\xe9") class MultiPathServerTestCase(BaseServerTestCase): threadFunc = staticmethod(http_multi_server) request_count = 2
def test_unicode_host(self): server = xmlrpclib.ServerProxy("http://%s:%d/RPC2" % (ADDR, PORT)) self.assertEqual(server.add("a", "\xe9"), "a\xe9") def test_partial_post(self): # Check that a partial POST doesn't make the server loop: issue #14001. conn = http.client.HTTPConnection(A...
def do_POST(self): L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) L.append(self.rfile.read(chunk_size)) size_remaining -= len(L[-1]) data = b''.join(L)
def do_POST(self): L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) chunk = self.rfile.read(chunk_size) if not chunk: break L.append(chunk) size_remaining -= len(L[-1]...
def dump_to_file(*output: str) -> str: import tempfile with tempfile.NamedTemporaryFile( mode="w", prefix="blk_", suffix=".log", delete=False ) as f: for lines in output: f.write(lines)
def dump_to_file(*output: str) -> str: import tempfile with tempfile.NamedTemporaryFile( mode="w", prefix="blk_", suffix=".log", delete=False, encoding="utf8" ) as f: for lines in output: f.write(lines)
class BlackTestCase(unittest.TestCase): tmp_file = Path(black.dump_to_file(source)) try: self.assertTrue(ff(tmp_file, write_back=black.WriteBack.YES)) with open(tmp_file) as f: actual = f.read() finally: os.unlink(tmp_file)
class BlackTestCase(unittest.TestCase): tmp_file = Path(black.dump_to_file(source)) try: self.assertTrue(ff(tmp_file, write_back=black.WriteBack.YES)) with open(tmp_file, encoding="utf8") as f: actual = f.read() finally: os.unlink(tmp_file)
def _get_empty_dtype_and_na(join_units): dtype = upcast_classes["datetimetz"] return dtype[0], tslibs.NaT elif "datetime" in upcast_classes: return np.dtype("M8[ns]"), tslibs.iNaT elif "timedelta" in upcast_classes: return np.dtype("m8[ns]"), np.timedelta64("NaT", "ns") else:...
def _get_empty_dtype_and_na(join_units): dtype = upcast_classes["datetimetz"] return dtype[0], tslibs.NaT elif "datetime" in upcast_classes: return np.dtype("M8[ns]"), np.datetime64("NaT", "ns") elif "timedelta" in upcast_classes: return np.dtype("m8[ns]"), np.timedelta64("NaT", ...
def test_merge_multiindex_columns(): expected["id"] = "" tm.assert_frame_equal(result, expected)
def test_merge_multiindex_columns(): expected["id"] = "" tm.assert_frame_equal(result, expected) def test_merge_datetime_upcast_dtype(): # https://github.com/pandas-dev/pandas/issues/31208 df1 = pd.DataFrame({"x": ["a", "b", "c"], "y": ["1", "2", "4"]}) df2 = pd.DataFrame( {"y": ["1", "2"...
from django.db import models from django.http import Http404 from django.template.engine import Engine from django.urls import get_mod_func, get_resolver, get_urlconf from django.utils.decorators import method_decorator from django.utils.inspect import ( func_accepts_kwargs, func_accepts_var_args, get_func_full_arg...
from django.db import models from django.http import Http404 from django.template.engine import Engine from django.urls import get_mod_func, get_resolver, get_urlconf from django.utils._os import safe_join from django.utils.decorators import method_decorator from django.utils.inspect import ( func_accepts_kwargs, f...
class TemplateDetailView(BaseAdminDocsView): else: # This doesn't account for template loaders (#24128). for index, directory in enumerate(default_engine.dirs): template_file = Path(directory) / template if template_file.exists(): with ...
class TemplateDetailView(BaseAdminDocsView): else: # This doesn't account for template loaders (#24128). for index, directory in enumerate(default_engine.dirs): template_file = Path(safe_join(directory, template)) if template_file.exists(): ...
class AdminDocViewTests(TestDataMixin, AdminDocsTestCase): self.assertContains(response, 'View documentation') @override_settings(TEMPLATES=[{ 'NAME': 'ONE', 'BACKEND': 'django.template.backends.django.DjangoTemplates',
class AdminDocViewTests(TestDataMixin, AdminDocsTestCase): self.assertContains(response, 'View documentation') @unittest.skipUnless(utils.docutils_is_available, 'no docutils installed.') class AdminDocViewDefaultEngineOnly(TestDataMixin, AdminDocsTestCase): def setUp(self): self.client.force_logi...
def test_getproxies_environment_keep_no_proxies(self): self.env.set('NO_PROXY', 'localhost, anotherdomain.com, newdomain.com') self.assertTrue(urllib.request.proxy_bypass_environment('anotherdomain.com')) class urlopen_HttpTests(unittest.TestCase, FakeHTTPMixin): """Test urlopen() opening a fake ht...
def test_getproxies_environment_keep_no_proxies(self): self.env.set('NO_PROXY', 'localhost, anotherdomain.com, newdomain.com') self.assertTrue(urllib.request.proxy_bypass_environment('anotherdomain.com')) def test_proxy_cgi_ignore(self): try: self.env.set('HTTP_PROXY', 'http://s...
def getproxies_environment(): name = name.lower() if value and name[-6:] == '_proxy': proxies[name[:-6]] = value return proxies def proxy_bypass_environment(host):
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 cli...
"""rope, a python refactoring library""" INFO = __doc__ VERSION = '0.10.7' COPYRIGHT = """\ Copyright (C) 2015-2016 Nicholas Smith Copyright (C) 2014-2015 Matej Cepl Copyright (C) 2006-2012 Ali Gholami Rudi Copyright (C) 2009-2012 Anton Gritsay
"""rope, a python refactoring library""" INFO = __doc__ VERSION = '0.11.0' COPYRIGHT = """\ Copyright (C) 2015-2018 Nicholas Smith Copyright (C) 2014-2015 Matej Cepl Copyright (C) 2006-2012 Ali Gholami Rudi Copyright (C) 2009-2012 Anton Gritsay
def load_data(path='imdb.npz', path, origin=origin_folder + 'imdb.npz', file_hash='599dadb1135973df5b59232a0e9a887c') with np.load(path) as f: x_train, labels_train = f['x_train'], f['y_train'] x_test, labels_test = f['x_test'], f['y_test']
def load_data(path='imdb.npz', path, origin=origin_folder + 'imdb.npz', file_hash='599dadb1135973df5b59232a0e9a887c') with np.load(path, allow_pickle=True) as f: x_train, labels_train = f['x_train'], f['y_train'] x_test, labels_test = f['x_test'], f['y_test']
import pandas.core.algorithms as algos from pandas.core.arrays import ExtensionArray from pandas.core.base import IndexOpsMixin, PandasObject import pandas.core.common as com from pandas.core.indexers import maybe_convert_indices from pandas.core.indexes.frozen import FrozenList import pandas.core.missing as missing
import pandas.core.algorithms as algos from pandas.core.arrays import ExtensionArray from pandas.core.base import IndexOpsMixin, PandasObject import pandas.core.common as com from pandas.core.construction import extract_array from pandas.core.indexers import maybe_convert_indices from pandas.core.indexes.frozen import ...
class Index(IndexOpsMixin, PandasObject): # if we have something that is Index-like, then # use this, e.g. DatetimeIndex # Things like `Series._get_value` (via .at) pass the EA directly here. s = getattr(series, "_values", series) if isinstance(s, (ExtensionArray, Index)) and is_...
class Index(IndexOpsMixin, PandasObject): # if we have something that is Index-like, then # use this, e.g. DatetimeIndex # Things like `Series._get_value` (via .at) pass the EA directly here. s = extract_array(series, extract_numpy=True) if isinstance(s, ExtensionArray): ...
def test_groupby_agg_ea_method(monkeypatch): s = pd.Series(DecimalArray(data)) result = s.groupby(np.array([0, 0, 0, 1, 1])).agg(lambda x: x.values.my_sum()) tm.assert_series_equal(result, expected, check_names=False)
def test_groupby_agg_ea_method(monkeypatch): s = pd.Series(DecimalArray(data)) result = s.groupby(np.array([0, 0, 0, 1, 1])).agg(lambda x: x.values.my_sum()) tm.assert_series_equal(result, expected, check_names=False) def test_indexing_no_materialize(monkeypatch): # See https://github.com/pandas-dev/p...
class HttpRequest(object): def scheme(self): if settings.SECURE_PROXY_SSL_HEADER: try: header, value = settings.SECURE_PROXY_SSL_HEADER except ValueError: raise ImproperlyConfigured( 'The SECURE_PROXY_SSL_HEADER setting must be a tu...
class HttpRequest(object): def scheme(self): if settings.SECURE_PROXY_SSL_HEADER: try: header, secure_value = settings.SECURE_PROXY_SSL_HEADER except ValueError: raise ImproperlyConfigured( 'The SECURE_PROXY_SSL_HEADER setting must ...
class SecureProxySslHeaderTest(SimpleTestCase): req.META['HTTP_X_FORWARDED_PROTOCOL'] = 'https' self.assertIs(req.is_secure(), True) class IsOverriddenTest(SimpleTestCase): def test_configure(self):
class SecureProxySslHeaderTest(SimpleTestCase): req.META['HTTP_X_FORWARDED_PROTOCOL'] = 'https' self.assertIs(req.is_secure(), True) @override_settings(SECURE_PROXY_SSL_HEADER=('HTTP_X_FORWARDED_PROTOCOL', 'https')) def test_xheader_preferred_to_underlying_request(self): class ProxyRequ...
class MultiIndex(Index): if names is lib.no_default: names = [getattr(it, "name", None) for it in iterables] codes = cartesian_product(codes) return MultiIndex(levels, codes, sortorder=sortorder, names=names)
class MultiIndex(Index): if names is lib.no_default: names = [getattr(it, "name", None) for it in iterables] # codes are all ndarrays, so cartesian_product is lossless codes = cartesian_product(codes) return MultiIndex(levels, codes, sortorder=sortorder, names=names)
import numpy as np from pandas.core.dtypes.common import is_list_like import pandas.core.common as com def cartesian_product(X): """
import numpy as np from pandas.core.dtypes.common import is_list_like def cartesian_product(X): """
def cartesian_product(X): # if any factor is empty, the cartesian product is empty b = np.zeros_like(cumprodX) return [ np.tile( np.repeat(np.asarray(com.values_from_object(x)), b[i]), np.product(a[i]) ) for i, x in enumerate(X) ]
def cartesian_product(X): # if any factor is empty, the cartesian product is empty b = np.zeros_like(cumprodX) return [_tile_compat(np.repeat(x, b[i]), np.product(a[i])) for i, x in enumerate(X)] def _tile_compat(arr, num: int): """ Index compat for np.tile. Notes ----- Does ...
class TestPivotTable: tm.assert_frame_equal(result, expected) def test_pivot_integer_columns(self): # caused by upstream bug in unstack
class TestPivotTable: tm.assert_frame_equal(result, expected) def test_pivot_table_retains_tz(self): dti = date_range("2016-01-01", periods=3, tz="Europe/Amsterdam") df = DataFrame({"A": np.random.randn(3), "B": np.random.randn(3), "C": dti}) result = df.pivot_table(index=["B", "C"...
class TestCartesianProduct: tm.assert_index_equal(result1, expected1) tm.assert_index_equal(result2, expected2) def test_empty(self): # product of empty factors X = [[], [0, 1], []]
class TestCartesianProduct: tm.assert_index_equal(result1, expected1) tm.assert_index_equal(result2, expected2) def test_tzaware_retained(self): x = date_range("2000-01-01", periods=2, tz="US/Pacific") y = np.array([3, 4]) result1, result2 = cartesian_product([x, y]) ...
from lookatme.exceptions import IgnoredByContrib def render_code(token, body, stack, loop): lang = token["lang"] or "" if lang != "calendar":
from lookatme.exceptions import IgnoredByContrib def user_warnings(): """No warnings exist for this extension. Anything you want to warn the user about, such as security risks in processing untrusted markdown, should go here. """ return [] def render_code(token, body, stack, loop): lang = to...
is_flag=True, default=False, ) @click.option( "-e", "--exts",
is_flag=True, default=False, ) @click.option( "-s", "--safe", help="Do not load any new extensions specified in the source markdown. " "Extensions specified via env var or -e are still loaded", is_flag=True, default=False, ) @click.option( "--no-ext-warn", help="Load new ext...
nargs=-1, ) def main(debug, log_path, theme, code_style, dump_styles, input_files, live_reload, extensions, single_slide): """lookatme - An interactive, terminal-based markdown presentation tool. """ if debug: lookatme.config.LOG = lookatme.log.create_log(log_path)
nargs=-1, ) def main(debug, log_path, theme, code_style, dump_styles, input_files, live_reload, extensions, single_slide, safe, no_ext_warn, ignore_ext_failure): """lookatme - An interactive, terminal-based markdown presentation tool. See https://lookatme.readthedocs.io/en/v{{VERSION}...
def main(debug, log_path, theme, code_style, dump_styles, live_reload=live_reload, single_slide=single_slide, preload_extensions=preload_exts, ) if dump_styles:
def main(debug, log_path, theme, code_style, dump_styles, live_reload=live_reload, single_slide=single_slide, preload_extensions=preload_exts, safe=safe, no_ext_warn=no_ext_warn, ignore_ext_failure=ignore_ext_failure, ) if dump_styles:
import contextlib from lookatme.exceptions import IgnoredByContrib from . import terminal from . import file_loader CONTRIB_MODULES = [ terminal, file_loader, ] def load_contribs(contrib_names): """Load all contrib modules specified by ``contrib_names``. These should all be namespaced packages und...
import contextlib import lookatme.ascii_art from lookatme.exceptions import IgnoredByContrib import lookatme.prompt from . import terminal from . import file_loader CONTRIB_MODULES = [] def validate_extension_mod(ext_name, ext_mod): """Validate the extension, returns an array of warnings associated with the ...
from lookatme.exceptions import IgnoredByContrib class YamlRender: loads = lambda data: yaml.safe_load(data) dumps = lambda data: yaml.safe_dump(data)
from lookatme.exceptions import IgnoredByContrib def user_warnings(): """Provide warnings to the user that loading this extension may cause shell commands specified in the markdown to be run. """ return [ "Code-blocks with a language starting with 'file' may cause shell", " commands f...
import lookatme.config class YamlRender: loads = lambda data: yaml.safe_load(data) dumps = lambda data: yaml.safe_dump(data)
import lookatme.config def user_warnings(): """Provide warnings to the user that loading this extension may cause shell commands specified in the markdown to be run. """ return [ "Code-blocks with a language starting with 'terminal' will cause shell", " commands from the source markdo...
import lookatme.config import lookatme.contrib from lookatme.parser import Parser import lookatme.themes import lookatme.tui from lookatme.utils import dict_deep_update
import lookatme.config import lookatme.contrib from lookatme.parser import Parser import lookatme.prompt import lookatme.themes import lookatme.tui from lookatme.utils import dict_deep_update
class Presentation(object): """Defines a presentation """ def __init__(self, input_stream, theme, style_override=None, live_reload=False, single_slide=False, preload_extensions=None): """Creates a new Presentation :param stream input_stream: An input stream from which to re...
class Presentation(object): """Defines a presentation """ def __init__(self, input_stream, theme, style_override=None, live_reload=False, single_slide=False, preload_extensions=None, safe=False, no_ext_warn=False, ignore_ext_failure=False): """Creates a new Presenta...
def __init__(self, input_stream, theme, style_override=None, live_reload=False, self.live_reload = live_reload self.tui = None self.single_slide = single_slide self.theme_mod = __import__("lookatme.themes." + theme, fromlist=[theme])
def __init__(self, input_stream, theme, style_override=None, live_reload=False, self.live_reload = live_reload self.tui = None self.single_slide = single_slide self.safe = safe self.no_ext_warn = no_ext_warn self.ignore_ext_failure = ignore_ext_failure self.initia...
def __init__(self, input_stream, theme, style_override=None, live_reload=False, self.reload_thread.start() self.reload(data=input_stream.read()) def reload_watcher(self): """Watch for changes to the input filename, automatically reloading
def __init__(self, input_stream, theme, style_override=None, live_reload=False, self.reload_thread.start() self.reload(data=input_stream.read()) self.initial_load_complete = True def reload_watcher(self): """Watch for changes to the input filename, automatically reloading
def reload(self, data=None): parser = Parser(single_slide=self.single_slide) self.meta, self.slides = parser.parse(data) all_exts = set(self.preload_extensions) all_exts |= set(self.meta.get("extensions", [])) lookatme.contrib.load_contribs(all_exts) self.styles = looka...
def reload(self, data=None): parser = Parser(single_slide=self.single_slide) self.meta, self.slides = parser.parse(data) # only load extensions once! Live editing does not support # auto-extension reloading if not self.initial_load_complete: safe_exts = set(self.prel...
def reload(self, data=None): self.styles["style"] = self.style_override lookatme.config.STYLE = self.styles def run(self, start_slide=0): """Run the presentation!
def reload(self, data=None): self.styles["style"] = self.style_override lookatme.config.STYLE = self.styles self.initial_load_complete = True def warn_exts(self, exts): """Warn about source-provided extensions that are to-be-loaded """ if len(exts) == 0 or self....
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...
class Sanic: "Endpoint with name `{}` was not found".format(view_name) ) if view_name == "static" or view_name.endswith(".static"): filename = kwargs.pop("filename", None) # it's static folder
class Sanic: "Endpoint with name `{}` was not found".format(view_name) ) # If the route has host defined, split that off # TODO: Retain netloc and path separately in Route objects host = uri.find("/") if host > 0: host, uri = uri[:host], uri[host:...
class Sanic: netloc = kwargs.pop("_server", None) if netloc is None and external: netloc = self.config.get("SERVER_NAME", "") if external: if not scheme:
class Sanic: netloc = kwargs.pop("_server", None) if netloc is None and external: netloc = host or self.config.get("SERVER_NAME", "") if external: if not scheme:
def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='', # sign sign = '' if isinstance(number, Decimal): str_number = '{:f}'.format(number) else: str_number = str(number) if str_number[0] == '-':
def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='', # sign sign = '' if isinstance(number, Decimal): # Format values with more than 200 digits (an arbitrary cutoff) using # scientific notation to avoid high memory usage in {:f}'.format(). _, digits, exponen...
class TestNumberFormat(SimpleTestCase): ) self.assertEqual(nformat(Decimal('3.'), '.'), '3') self.assertEqual(nformat(Decimal('3.0'), '.'), '3.0') def test_decimal_subclass(self): class EuroDecimal(Decimal):
class TestNumberFormat(SimpleTestCase): ) self.assertEqual(nformat(Decimal('3.'), '.'), '3') self.assertEqual(nformat(Decimal('3.0'), '.'), '3.0') # Very large & small numbers. tests = [ ('9e9999', None, '9e+9999'), ('9e9999', 3, '9.000e+9999'), ...
def test_urlopener_retrieve_remote(self): filename, _ = urllib.request.URLopener().retrieve(url) self.assertEqual(os.path.splitext(filename)[1], ".txt") # Just commented them out. # Can't really tell why keep failing in windows and sparc.
def test_urlopener_retrieve_remote(self): filename, _ = urllib.request.URLopener().retrieve(url) self.assertEqual(os.path.splitext(filename)[1], ".txt") @support.ignore_warnings(category=DeprecationWarning) def test_local_file_open(self): # bpo-35907, CVE-2019-9948: urllib must reject l...
def open(self, fullurl, data=None): name = 'open_' + urltype self.type = urltype name = name.replace('-', '_') if not hasattr(self, name): if proxy: return self.open_unknown_proxy(proxy, fullurl, data) else:
def open(self, fullurl, data=None): name = 'open_' + urltype self.type = urltype name = name.replace('-', '_') if not hasattr(self, name) or name == 'open_local_file': if proxy: return self.open_unknown_proxy(proxy, fullurl, data) else:
def get_openapi_path( operation_parameters = get_openapi_operation_parameters(all_route_params) parameters.extend(operation_parameters) if parameters: operation["parameters"] = parameters if method in METHODS_WITH_BODY: request_body_oai = g...
def get_openapi_path( operation_parameters = get_openapi_operation_parameters(all_route_params) parameters.extend(operation_parameters) if parameters: operation["parameters"] = list( {param["name"]: param for param in parameters}.values() ...
def __xml_scan(node, env, path, arg): styledoc = libxml2.parseFile(xsl_file) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseFile(str(node)) result = style.applyStylesheet(doc, None) depfiles = []
def __xml_scan(node, env, path, arg): styledoc = libxml2.parseFile(xsl_file) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.readFile(str(node), None, libxml2.XML_PARSE_NOENT) result = style.applyStylesheet(doc, None) depfiles = []
def __xinclude_libxml2(target, source, env): Resolving XIncludes, using the libxml2 module. """ doc = libxml2.readFile(str(source[0]), None, libxml2.XML_PARSE_NOENT) doc.xincludeProcess() doc.saveFile(str(target[0])) doc.freeDoc()
def __xinclude_libxml2(target, source, env): Resolving XIncludes, using the libxml2 module. """ doc = libxml2.readFile(str(source[0]), None, libxml2.XML_PARSE_NOENT) doc.xincludeProcessFlags(libxml2.XML_PARSE_NOENT) doc.saveFile(str(target[0])) doc.freeDoc()
class TestUtil(unittest.TestCase): def test_urljoin(self): self.assertEqual(urljoin('http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt') self.assertEqual(urljoin('//foo.de/', '/a/b/c.txt'), '//foo.de/a/b/c.txt') self.assertEqual(urljoin('http://foo.de/', 'a/b/c.txt'), 'http://foo.de/...
class TestUtil(unittest.TestCase): def test_urljoin(self): self.assertEqual(urljoin('http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt') self.assertEqual(urljoin(b'http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt') self.assertEqual(urljoin('http://foo.de/', b'/a/b/c.txt'), 'h...