buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
class Categorical(ExtensionArray, PandasObject):
raise ValueError("fill value must be in categories")
values_codes = _get_codes_for_values(value, self.categories)
indexer = np.where(values_codes != -1)
codes[indexer] = values_codes[values_codes != -1]... | class Categorical(ExtensionArray, PandasObject):
raise ValueError("fill value must be in categories")
values_codes = _get_codes_for_values(value, self.categories)
indexer = np.where(codes == -1)
codes[indexer] = values_codes[indexer]
# If... |
class TestSeriesMissingData:
exp = Series(Categorical(expected_output, categories=["a", "b"]))
tm.assert_series_equal(s.fillna(fill_value), exp)
def test_fillna_categorical_raise(self):
data = ["a", np.nan, "b", np.nan, np.nan]
s = Series(Categorical(data, categories=["a", "b"])) | class TestSeriesMissingData:
exp = Series(Categorical(expected_output, categories=["a", "b"]))
tm.assert_series_equal(s.fillna(fill_value), exp)
@pytest.mark.parametrize(
"fill_value, expected_output",
[
(Series(["a", "b", "c", "d", "e"]), ["a", "b", "b", "d", "e"]),
... |
from PyQt5 import QtGui
from PyQt5 import QtWidgets
from electrum import util
if platform.system() == 'Windows': | from PyQt5 import QtGui
from PyQt5 import QtWidgets
from electrum import util
from electrum.i18n import _
if platform.system() == 'Windows': |
MONOSPACE_FONT = 'monospace'
class Console(QtWidgets.QPlainTextEdit):
def __init__(self, prompt='>> ', startup_message='', parent=None):
QtWidgets.QPlainTextEdit.__init__(self, parent) | MONOSPACE_FONT = 'monospace'
class OverlayLabel(QtWidgets.QLabel):
STYLESHEET = '''
QLabel, QLabel link {
color: rgb(0, 0, 0);
background-color: rgb(248, 240, 200);
border: 1px solid;
border-color: rgb(255, 114, 47);
padding: 2px;
}
'''
def __init__(self... |
def __init__(self, prompt='>> ', startup_message='', parent=None):
self.updateNamespace({'run':self.run_script})
self.set_json(False)
def set_json(self, b):
self.is_json = b
| def __init__(self, prompt='>> ', startup_message='', parent=None):
self.updateNamespace({'run':self.run_script})
self.set_json(False)
warning_text = "<h1>{}</h1><br>{}<br><br>{}".format(
_("Warning!"),
_("Do not paste code here that you don't understand. Executing the wr... |
import stat
from django.http import (
FileResponse, Http404, HttpResponse, HttpResponseNotModified,
HttpResponseRedirect,
)
from django.template import Context, Engine, TemplateDoesNotExist, loader
from django.utils.http import http_date, parse_http_date
from django.utils.six.moves.urllib.parse import unquote
... | import stat
from django.http import (
FileResponse, Http404, HttpResponse, HttpResponseNotModified,
)
from django.template import Context, Engine, TemplateDoesNotExist, loader
from django.utils._os import safe_join
from django.utils.http import http_date, parse_http_date
from django.utils.six.moves.urllib.parse im... |
def serve(request, path, document_root=None, show_indexes=False):
but if you'd like to override it, you can create a template called
``static/directory_index.html``.
"""
path = posixpath.normpath(unquote(path))
path = path.lstrip('/')
newpath = ''
for part in path.split('/'):
if not ... | def serve(request, path, document_root=None, show_indexes=False):
but if you'd like to override it, you can create a template called
``static/directory_index.html``.
"""
path = posixpath.normpath(unquote(path)).lstrip('/')
fullpath = safe_join(document_root, path)
if os.path.isdir(fullpath):
... |
def to_categorical(y, num_classes=None):
"""
y = np.array(y, dtype='int')
input_shape = y.shape
y = y.ravel()
if not num_classes:
num_classes = np.max(y) + 1 | def to_categorical(y, num_classes=None):
"""
y = np.array(y, dtype='int')
input_shape = y.shape
if input_shape and input_shape[-1] == 1:
input_shape = tuple(input_shape[:-1])
y = y.ravel()
if not num_classes:
num_classes = np.max(y) + 1 |
from keras.utils import to_categorical
def test_to_categorical():
num_classes = 5
shapes = [(3,), (4, 3), (5, 4, 3)]
labels = [np.random.randint(0, num_classes, shape) for shape in shapes]
one_hots = [to_categorical(label, num_classes) for label in labels]
for label, one_hot in zip(labels, one_hots... | from keras.utils import to_categorical
def test_to_categorical():
num_classes = 5
shapes = [(3,), (4, 3), (5, 4, 3), (3, 1), (3, 2, 1)]
expected_shapes = [(3, num_classes),
(4, 3, num_classes),
(5, 4, 3, num_classes),
(3, num_classes)]
... |
class BinGrouper(BaseGrouper):
ngroups,
)
@cache_readonly
def result_index(self):
if len(self.binlabels) != 0 and isna(self.binlabels[0]): | class BinGrouper(BaseGrouper):
ngroups,
)
@cache_readonly
def recons_codes(self):
# get unique result indices, and prepend 0 as groupby starts from the first
return [np.r_[0, np.flatnonzero(self.bins[1:] != self.bins[:-1]) + 1]]
@cache_readonly
def result_index(self... |
from itertools import product
import numpy as np
import pytest
from pandas import DataFrame, MultiIndex, Series, date_range
import pandas.util.testing as tm
| from itertools import product
import numpy as np
import pytest
from pandas import DataFrame, Grouper, MultiIndex, Series, date_range, to_datetime
import pandas.util.testing as tm
|
def test_series_groupby_value_counts(
# have to sort on index because of unstable sort on values
left, right = map(rebuild_index, (left, right)) # xref GH9212
tm.assert_series_equal(left.sort_index(), right.sort_index()) | def test_series_groupby_value_counts(
# have to sort on index because of unstable sort on values
left, right = map(rebuild_index, (left, right)) # xref GH9212
tm.assert_series_equal(left.sort_index(), right.sort_index())
def test_series_groupby_value_counts_with_grouper():
# GH28479
df = DataFram... |
def test_overrun(self):
except IOError as e:
self.assertEqual(str(e), "buffer overrun when reading image file")
class MockEncoder(object):
pass | def test_overrun(self):
except IOError as e:
self.assertEqual(str(e), "buffer overrun when reading image file")
with Image.open("Tests/images/fli_overrun2.bin") as im:
try:
im.seek(1)
self.assertFail()
except IOError as e:
... |
class HTTPBearer(HTTPBase):
else:
return None
if scheme.lower() != "bearer":
raise HTTPException(
status_code=HTTP_403_FORBIDDEN,
detail="Invalid authentication credentials",
)
return HTTPAuthorizationCredentials(scheme=... | class HTTPBearer(HTTPBase):
else:
return None
if scheme.lower() != "bearer":
if self.auto_error:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN,
detail="Invalid authentication credentials",
)
... |
def test_security_http_bearer_no_credentials():
def test_security_http_bearer_incorrect_scheme_credentials():
response = client.get("/users/me", headers={"Authorization": "Basic notreally"})
assert response.status_code == 403
assert response.json() == {"detail": "Invalid authentication credentials"} | def test_security_http_bearer_no_credentials():
def test_security_http_bearer_incorrect_scheme_credentials():
response = client.get("/users/me", headers={"Authorization": "Basic notreally"})
assert response.status_code == 200
assert response.json() == {"msg": "Create an account first"} |
def na_logical_op(x: np.ndarray, y, op):
assert not (is_bool_dtype(x.dtype) and is_bool_dtype(y.dtype))
x = ensure_object(x)
y = ensure_object(y)
result = libops.vec_binop(x, y, op)
else:
# let null fall thru
assert lib.is_scalar(y) | def na_logical_op(x: np.ndarray, y, op):
assert not (is_bool_dtype(x.dtype) and is_bool_dtype(y.dtype))
x = ensure_object(x)
y = ensure_object(y)
result = libops.vec_binop(x.ravel(), y.ravel(), op)
else:
# let null fall thru
assert lib.is_s... |
def na_logical_op(x: np.ndarray, y, op):
f"and scalar of type [{typ}]"
)
return result
def logical_op( | def na_logical_op(x: np.ndarray, y, op):
f"and scalar of type [{typ}]"
)
return result.reshape(x.shape)
def logical_op( |
def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]:
"""
srcbuf = io.BytesIO(src)
encoding, lines = tokenize.detect_encoding(srcbuf.readline)
newline = "\r\n" if b"\r\n" == lines[0][-2:] else "\n"
srcbuf.seek(0)
with io.TextIOWrapper(srcbuf, encoding) as tiow: | def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]:
"""
srcbuf = io.BytesIO(src)
encoding, lines = tokenize.detect_encoding(srcbuf.readline)
if not lines:
return "", encoding, "\n"
newline = "\r\n" if b"\r\n" == lines[0][-2:] else "\n"
srcbuf.seek(0)
with io.TextI... |
GRAMMARS = [
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) | GRAMMARS = [
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) |
class BlackTestCase(unittest.TestCase):
black.err(str(ve))
self.assertEqual(expected, actual)
@patch("black.dump_to_file", dump_to_stderr)
def test_self(self) -> None:
source, expected = read_data("test_black") | class BlackTestCase(unittest.TestCase):
black.err(str(ve))
self.assertEqual(expected, actual)
@patch("black.dump_to_file", dump_to_stderr)
def test_empty(self) -> None:
source = expected = ""
actual = fs(source)
self.assertFormatEqual(expected, actual)
bl... |
def request_httprepr(request):
parsed = urlparse_cached(request)
path = urlunparse(('', '', parsed.path or '/', parsed.params, parsed.query, ''))
s = to_bytes(request.method) + b" " + to_bytes(path) + b" HTTP/1.1\r\n"
s += b"Host: " + to_bytes(parsed.hostname) + b"\r\n"
if request.headers:
s... | def request_httprepr(request):
parsed = urlparse_cached(request)
path = urlunparse(('', '', parsed.path or '/', parsed.params, parsed.query, ''))
s = to_bytes(request.method) + b" " + to_bytes(path) + b" HTTP/1.1\r\n"
s += b"Host: " + to_bytes(parsed.hostname or b'') + b"\r\n"
if request.headers:
... |
class UtilsRequestTest(unittest.TestCase):
r1 = Request("http://www.example.com", method='POST', headers={"Content-type": b"text/html"}, body=b"Some body")
self.assertEqual(request_httprepr(r1), b'POST / HTTP/1.1\r\nHost: www.example.com\r\nContent-Type: text/html\r\n\r\nSome body')
if __name__ == "__m... | class UtilsRequestTest(unittest.TestCase):
r1 = Request("http://www.example.com", method='POST', headers={"Content-type": b"text/html"}, body=b"Some body")
self.assertEqual(request_httprepr(r1), b'POST / HTTP/1.1\r\nHost: www.example.com\r\nContent-Type: text/html\r\n\r\nSome body')
def test_reques... |
class AdminReadonlyField:
except (AttributeError, ValueError, ObjectDoesNotExist):
result_repr = self.empty_value_display
else:
if f is None:
if getattr(attr, 'boolean', False):
result_repr = _boolean_icon(value) | class AdminReadonlyField:
except (AttributeError, ValueError, ObjectDoesNotExist):
result_repr = self.empty_value_display
else:
if field in self.form.fields:
widget = self.form[field].field.widget
# This isn't elegant but suffices for contrib.auth'... |
UserModel = get_user_model()
class ReadOnlyPasswordHashWidget(forms.Widget):
template_name = 'auth/widgets/read_only_password_hash.html'
def get_context(self, name, value, attrs):
context = super().get_context(name, value, attrs) | UserModel = get_user_model()
class ReadOnlyPasswordHashWidget(forms.Widget):
template_name = 'auth/widgets/read_only_password_hash.html'
read_only = True
def get_context(self, name, value, attrs):
context = super().get_context(name, value, attrs) |
from django.contrib.auth import (
from django.contrib.auth.forms import (
AuthenticationForm, PasswordChangeForm, SetPasswordForm,
)
from django.contrib.auth.models import User
from django.contrib.auth.views import (
INTERNAL_RESET_SESSION_TOKEN, LoginView, logout_then_login,
redirect_to_login,
)
from djang... | from django.contrib.auth import (
from django.contrib.auth.forms import (
AuthenticationForm, PasswordChangeForm, SetPasswordForm,
)
from django.contrib.auth.models import Permission, User
from django.contrib.auth.views import (
INTERNAL_RESET_SESSION_TOKEN, LoginView, logout_then_login,
redirect_to_login,
... |
class LogoutTest(AuthViewsTestCase):
self.assertRedirects(response, '/logout/', fetch_redirect_response=False)
# Redirect in test_user_change_password will fail if session auth hash
# isn't updated after password change (#21649)
@override_settings(ROOT_URLCONF='auth_tests.urls_admin') | class LogoutTest(AuthViewsTestCase):
self.assertRedirects(response, '/logout/', fetch_redirect_response=False)
def get_perm(Model, perm):
ct = ContentType.objects.get_for_model(Model)
return Permission.objects.get(content_type=ct, codename=perm)
# Redirect in test_user_change_password will fail if s... |
class ChangelistTests(AuthViewsTestCase):
(_request, user), _kwargs = has_change_permission.call_args
self.assertEqual(user.pk, self.admin.pk)
@override_settings(
AUTH_USER_MODEL='auth_tests.UUIDUser', | class ChangelistTests(AuthViewsTestCase):
(_request, user), _kwargs = has_change_permission.call_args
self.assertEqual(user.pk, self.admin.pk)
def test_view_user_password_is_readonly(self):
u = User.objects.get(username='testclient')
u.is_superuser = False
u.save()
u... |
import os
import salt.payload
import salt.utils.files
import salt.utils.path
from salt.ext import six
log = logging.getLogger(__name__) | import os
import salt.payload
import salt.utils.files
import salt.utils.path
import salt.utils.verify
from salt.ext import six
log = logging.getLogger(__name__) |
def get_token(opts, tok):
:returns: Token data if successful. Empty dict if failed.
"""
t_path = os.path.join(opts["token_dir"], tok)
if not os.path.isfile(t_path):
return {}
serial = salt.payload.Serial(opts) | def get_token(opts, tok):
:returns: Token data if successful. Empty dict if failed.
"""
t_path = os.path.join(opts["token_dir"], tok)
if not salt.utils.verify.clean_path(opts["token_dir"], t_path):
return {}
if not os.path.isfile(t_path):
return {}
serial = salt.payload.Serial(op... |
from __future__ import absolute_import, print_function, unicode_literals
import errno
import logging
# Import python libs
import os
import re
import socket | from __future__ import absolute_import, print_function, unicode_literals
import errno
import logging
import os
import re
import socket |
import stat
import sys
import salt.defaults.exitcodes
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.user
from salt.exceptions import CommandExecutionError, SaltClientError, SaltSystemExit
# Import salt libs
from salt.log import is_console_configured
from salt.log.setup im... | import stat
import sys
import salt.defaults.exitcodes
import salt.ext.six
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.user
from salt.exceptions import CommandExecutionError, SaltClientError, SaltSystemExit
from salt.log import is_console_configured
from salt.log.setup im... |
def check_max_open_files(opts):
log.log(level=level, msg=msg)
def clean_path(root, path, subdir=False):
"""
Accepts the root the path needs to be under and verifies that the path is
under said root. Pass in subdir=True if the path can result in a
subdirectory of the root instead of having to resid... | def check_max_open_files(opts):
log.log(level=level, msg=msg)
def _realpath_darwin(path):
base = ""
for part in path.split(os.path.sep)[1:]:
if base != "":
if os.path.islink(os.path.sep.join([base, part])):
base = os.readlink(os.path.sep.join([base, part]))
... |
def update_config(file_name, yaml_contents):
__opts__["config_dir"], os.path.dirname(__opts__["default_include"])
)
try:
yaml_out = salt.utils.yaml.safe_dump(yaml_contents, default_flow_style=False)
if not os.path.exists(dir_path):
log.debug("Creating directory %s", dir_path... | def update_config(file_name, yaml_contents):
__opts__["config_dir"], os.path.dirname(__opts__["default_include"])
)
try:
yaml_out = salt.utils.yaml.safe_dump(yaml_contents, default_flow_style=False,)
if not os.path.exists(dir_path):
log.debug("Creating directory %s", dir_pat... |
def find(path, saltenv="base"):
return ret
for root in __opts__["file_roots"][saltenv]:
full = os.path.join(root, path)
if os.path.isfile(full):
# Add it to the dict
with salt.utils.files.fopen(full, "rb") as fp_: | def find(path, saltenv="base"):
return ret
for root in __opts__["file_roots"][saltenv]:
full = os.path.join(root, path)
if not salt.utils.verify.clean_path(root, full):
continue
if os.path.isfile(full):
# Add it to the dict
with salt.utils.files.fo... |
def write(data, path, saltenv="base", index=0):
return (
"The path passed in {0} is not relative to the environment " "{1}"
).format(path, saltenv)
dest = os.path.join(__opts__["file_roots"][saltenv][index], path)
dest_dir = os.path.dirname(dest)
if not os.path.isdir(dest_dir):
... | def write(data, path, saltenv="base", index=0):
return (
"The path passed in {0} is not relative to the environment " "{1}"
).format(path, saltenv)
root = __opts__["file_roots"][saltenv][index]
dest = os.path.join(root, path)
if not salt.utils.verify.clean_path(root, dest, subdir... |
class ClearFuncsPubTestCase(TestCase):
ret_evt = raw
break
assert not os.path.exists(self.tmpfile), "Evil file created" | class ClearFuncsPubTestCase(TestCase):
ret_evt = raw
break
assert not os.path.exists(self.tmpfile), "Evil file created"
class ClearFuncsConfigTest(TestCase):
def setUp(self):
master_opts = AdaptedConfigurationTestCaseMixin.get_config("master")
self.conf_dir ... |
class BadTestModuleNamesTestCase(TestCase):
"integration.logging.test_jid_logging",
"integration.logging.handlers.test_logstash_mod",
"integration.master.test_event_return",
"integration.minion.test_blackout",
"integration.minion.test_executor",
"i... | class BadTestModuleNamesTestCase(TestCase):
"integration.logging.test_jid_logging",
"integration.logging.handlers.test_logstash_mod",
"integration.master.test_event_return",
"integration.master.test_clear_funcs",
"integration.minion.test_blackout",
... |
class BadTestModuleNamesTestCase(TestCase):
"integration.reactor.test_reactor",
"integration.returners.test_noop_return",
"integration.runners.test_runner_returns",
"unit.utils.scheduler.test_error",
"unit.utils.scheduler.test_eval",
"unit.utils.sc... | class BadTestModuleNamesTestCase(TestCase):
"integration.reactor.test_reactor",
"integration.returners.test_noop_return",
"integration.runners.test_runner_returns",
"integration.scheduler.test_error",
"integration.scheduler.test_eval",
"integration... |
class BadTestModuleNamesTestCase(TestCase):
"integration.ssh.test_raw",
"integration.ssh.test_saltcheck",
"integration.ssh.test_state",
"integration.ssh.test_pre_flight",
"integration.states.test_compiler",
"integration.states.test_handle_error",
... | class BadTestModuleNamesTestCase(TestCase):
"integration.ssh.test_raw",
"integration.ssh.test_saltcheck",
"integration.ssh.test_state",
"integration.states.test_compiler",
"integration.states.test_handle_error",
"integration.states.test_handle_iord... |
Test the verification routines
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import getpass
import os
import shutil | Test the verification routines
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import ctypes
import getpass
import os
import shutil |
from salt.ext.six.moves import range # pylint: disable=import-error,redefined-b
from salt.utils.verify import (
check_max_open_files,
check_user,
log,
valid_id,
verify_env, | from salt.ext.six.moves import range # pylint: disable=import-error,redefined-b
from salt.utils.verify import (
check_max_open_files,
check_user,
clean_path,
log,
valid_id,
verify_env, |
from salt.utils.verify import (
from tests.support.helpers import TstSuiteLoggingHandler, requires_network
from tests.support.mock import MagicMock, patch
# Import Salt Testing libs
from tests.support.runtests import RUNTIME_VARS
from tests.support.unit import TestCase, skipIf | from salt.utils.verify import (
from tests.support.helpers import TstSuiteLoggingHandler, requires_network
from tests.support.mock import MagicMock, patch
# Import Salt Testing libs
# Import Salt Testing libs
from tests.support.runtests import RUNTIME_VARS
from tests.support.unit import TestCase, skipIf |
else:
import resource
class TestVerify(TestCase):
"""
Verify module tests | else:
import resource
# Import third party libs
if sys.platform.startswith("win"):
import win32file
else:
import resource
class TestVerify(TestCase):
"""
Verify module tests |
class TestVerifyLog(TestCase):
self.assertFalse(os.path.exists(path))
verify_log_files([path], getpass.getuser())
self.assertTrue(os.path.exists(path)) | class TestVerifyLog(TestCase):
self.assertFalse(os.path.exists(path))
verify_log_files([path], getpass.getuser())
self.assertTrue(os.path.exists(path))
class TestCleanPath(TestCase):
"""
salt.utils.clean_path works as expected
"""
def setUp(self):
self.tmpdir = tempfil... |
# Copyright (C) 1998-2005 by the Free Software Foundation, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License | # Copyright (C) 1998-2006 by the Free Software Foundation, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License |
def main():
# page don't work.
if true_filename.endswith('/index.html') and parts[-1] <> 'index.html':
action += SLASH
print Utils.maketext(
'private.html',
{'action' : action,
'realname': mlist.real_name,
'message' : message,
... | def main():
# page don't work.
if true_filename.endswith('/index.html') and parts[-1] <> 'index.html':
action += SLASH
# Escape web input parameter to avoid cross-site scripting.
print Utils.maketext(
'private.html',
{'action' : Utils.websafe(action),... |
import copy
import datetime
from functools import partial
import string
from typing import TYPE_CHECKING, Optional, Tuple, Union
import warnings
import numpy as np
from pandas._libs import Timedelta, hashtable as libhashtable, lib
import pandas._libs.join as libjoin
from pandas._typing import FrameOrSeries
from panda... | import copy
import datetime
from functools import partial
import string
from typing import TYPE_CHECKING, Optional, Tuple, Union, cast
import warnings
import numpy as np
from pandas._libs import Timedelta, hashtable as libhashtable, lib
import pandas._libs.join as libjoin
from pandas._typing import ArrayLike, FrameOr... |
from pandas.core.dtypes.common import (
is_array_like,
is_bool,
is_bool_dtype,
is_categorical_dtype,
is_datetime64tz_dtype,
is_dtype_equal, | from pandas.core.dtypes.common import (
is_array_like,
is_bool,
is_bool_dtype,
is_categorical,
is_categorical_dtype,
is_datetime64tz_dtype,
is_dtype_equal, |
def _get_join_indexers(
# get left & right join labels and num. of levels at each location
mapped = (
_factorize_keys(left_keys[n], right_keys[n], sort=sort)
for n in range(len(left_keys))
)
zipped = zip(*mapped) | def _get_join_indexers(
# get left & right join labels and num. of levels at each location
mapped = (
_factorize_keys(left_keys[n], right_keys[n], sort=sort, how=how)
for n in range(len(left_keys))
)
zipped = zip(*mapped) |
def _get_join_indexers(
# factorize keys to a dense i8 space
# `count` is the num. of unique keys
# set(lkey) | set(rkey) == range(count)
lkey, rkey, count = _factorize_keys(lkey, rkey, sort=sort)
# preserve left frame order if how == 'left' and sort == False
kwargs = copy.copy(kwargs)
if h... | def _get_join_indexers(
# factorize keys to a dense i8 space
# `count` is the num. of unique keys
# set(lkey) | set(rkey) == range(count)
lkey, rkey, count = _factorize_keys(lkey, rkey, sort=sort, how=how)
# preserve left frame order if how == 'left' and sort == False
kwargs = copy.copy(kwargs)... |
def _right_outer_join(x, y, max_groups):
return left_indexer, right_indexer
def _factorize_keys(lk, rk, sort=True):
# Some pre-processing for non-ndarray lk / rk
lk = extract_array(lk, extract_numpy=True)
rk = extract_array(rk, extract_numpy=True) | def _right_outer_join(x, y, max_groups):
return left_indexer, right_indexer
def _factorize_keys(
lk: ArrayLike, rk: ArrayLike, sort: bool = True, how: str = "inner"
) -> Tuple[np.array, np.array, int]:
"""
Encode left and right keys as enumerated types.
This is used to get the join indexers to be... |
def _factorize_keys(lk, rk, sort=True):
rk, _ = rk._values_for_factorize()
elif (
is_categorical_dtype(lk) and is_categorical_dtype(rk) and lk.is_dtype_equal(rk)
):
if lk.categories.equals(rk.categories):
# if we exactly match in categories, allow us to factorize on codes
... | def _factorize_keys(lk, rk, sort=True):
rk, _ = rk._values_for_factorize()
elif (
is_categorical_dtype(lk) and is_categorical_dtype(rk) and is_dtype_equal(lk, rk)
):
assert is_categorical(lk) and is_categorical(rk)
lk = cast(Categorical, lk)
rk = cast(Categorical, rk)
... |
def _factorize_keys(lk, rk, sort=True):
np.putmask(rlab, rmask, count)
count += 1
return llab, rlab, count
| def _factorize_keys(lk, rk, sort=True):
np.putmask(rlab, rmask, count)
count += 1
if how == "right":
return rlab, llab, count
return llab, rlab, count
|
class TestMerge:
# GH 24212
# pd.merge gets [0, 1, 2, -1, -1, -1] as left_indexer, ensure that
# -1 is interpreted as a missing value instead of the last element
df1 = pd.DataFrame({"a": [1, 2, 3], "key": [0, 2, 2]}, index=index)
df2 = pd.DataFrame({"b": [1, 2, 3, 4, 5]})
... | class TestMerge:
# GH 24212
# pd.merge gets [0, 1, 2, -1, -1, -1] as left_indexer, ensure that
# -1 is interpreted as a missing value instead of the last element
df1 = pd.DataFrame({"a": [0, 1, 2], "key": [0, 1, 2]}, index=index)
df2 = pd.DataFrame({"b": [0, 1, 2, 3, 4, 5]})
... |
class TestMerge:
result = left.merge(right, left_on="key", right_index=True, how="right")
tm.assert_frame_equal(result, expected)
def test_merge_take_missing_values_from_index_of_other_dtype(self):
# GH 24212
left = pd.DataFrame( | class TestMerge:
result = left.merge(right, left_on="key", right_index=True, how="right")
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("how", ["left", "right"])
def test_merge_preserves_row_order(self, how):
# GH 27453
left_df = pd.DataFrame({"animal": ["dog"... |
import re
from setuptools import setup, find_packages
# Requirements
REQUIREMENTS = ["marshmallow>=2.15.0"]
def find_version(fname): | import re
from setuptools import setup, find_packages
# Requirements
REQUIREMENTS = ["marshmallow>=2.15.2"]
def find_version(fname): |
def check_required_arguments(argument_spec, module_parameters):
missing.append(k)
if missing:
msg = "missing required arguments: %s" % ", ".join(missing)
raise TypeError(to_native(msg))
return missing | def check_required_arguments(argument_spec, module_parameters):
missing.append(k)
if missing:
msg = "missing required arguments: %s" % ", ".join(sorted(missing))
raise TypeError(to_native(msg))
return missing |
def test_check_mutually_exclusive_found(mutually_exclusive_terms):
'fox': 'red',
'socks': 'blue',
}
expected = "TypeError('parameters are mutually exclusive: string1|string2, box|fox|socks',)"
with pytest.raises(TypeError) as e:
check_mutually_exclusive(mutually_exclusive_terms, par... | def test_check_mutually_exclusive_found(mutually_exclusive_terms):
'fox': 'red',
'socks': 'blue',
}
expected = "parameters are mutually exclusive: string1|string2, box|fox|socks"
with pytest.raises(TypeError) as e:
check_mutually_exclusive(mutually_exclusive_terms, params)
asse... |
def test_check_mutually_exclusive_none():
def test_check_mutually_exclusive_no_params(mutually_exclusive_terms):
with pytest.raises(TypeError) as te:
check_mutually_exclusive(mutually_exclusive_terms, None)
assert "TypeError: 'NoneType' object is not iterable" in to_native(te.error) | def test_check_mutually_exclusive_none():
def test_check_mutually_exclusive_no_params(mutually_exclusive_terms):
with pytest.raises(TypeError) as te:
check_mutually_exclusive(mutually_exclusive_terms, None)
assert "'NoneType' object is not iterable" in to_native(te.value) |
class tqdm(object):
return self.total if self.iterable is None else \
(self.iterable.shape[0] if hasattr(self.iterable, "shape")
else len(self.iterable) if hasattr(self.iterable, "__len__")
else self.total)
def __enter__(self):
return self | class tqdm(object):
return self.total if self.iterable is None else \
(self.iterable.shape[0] if hasattr(self.iterable, "shape")
else len(self.iterable) if hasattr(self.iterable, "__len__")
else getattr(self, "total", None))
def __enter__(self):
return self |
from __future__ import division
from tqdm import tqdm
from tests_tqdm import with_setup, pretest, posttest, StringIO, closing
from tests_tqdm import DiscreteTimer, cpu_timify
from time import sleep
from threading import Event
from tqdm import TMonitor
class FakeSleep(object): | from __future__ import division
from tqdm import tqdm, TMonitor
from tests_tqdm import with_setup, pretest, posttest, SkipTest, \
StringIO, closing
from tests_tqdm import DiscreteTimer, cpu_timify
from time import sleep
from threading import Event
class FakeSleep(object): |
def make_create_fake_sleep_event(sleep):
return create_fake_sleep_event
@with_setup(pretest, posttest)
def test_monitor_thread():
"""Test dummy monitoring thread""" | def make_create_fake_sleep_event(sleep):
return create_fake_sleep_event
def incr(x):
return x + 1
@with_setup(pretest, posttest)
def test_monitor_thread():
"""Test dummy monitoring thread""" |
def test_monitoring_multi():
# Check that class var monitor is deleted if no instance left
tqdm.monitor_interval = 10
assert tqdm.monitor is None | def test_monitoring_multi():
# Check that class var monitor is deleted if no instance left
tqdm.monitor_interval = 10
assert tqdm.monitor is None
@with_setup(pretest, posttest)
def test_imap():
"""Test multiprocessing.Pool"""
try:
from multiprocessing import Pool
except ImportError:
... |
logger = logging.getLogger(__name__)
title_regex = re.compile(r"(?<=<title>).*(?=</title>)")
id_regex = re.compile(r"(?<=<id>)\d*(?=</id>)")
text_regex = re.compile(r"(?<=<text xml:space=\"preserve\">).*(?=</text)")
info_regex = re.compile(r"{[^{]*?}")
html_regex = re.compile(r"<!--[^-]*-->")
ref_regex = re.comp... | logger = logging.getLogger(__name__)
title_regex = re.compile(r"(?<=<title>).*(?=</title>)")
id_regex = re.compile(r"(?<=<id>)\d*(?=</id>)")
text_tag_regex = re.compile(r"(?<=<text).*?(?=>)")
text_regex = re.compile(r"(?<=<text>).*(?=</text)")
info_regex = re.compile(r"{[^{]*?}")
html_regex = re.compile(r"<!--[^-]*... |
def _process_wp_text(article_title, article_text, wp_to_id):
return None, None
# remove the text tags
text_search = text_regex.search(article_text)
if text_search is None:
return None, None
text = text_search.group(0) | def _process_wp_text(article_title, article_text, wp_to_id):
return None, None
# remove the text tags
text_search = text_tag_regex.sub("", article_text)
text_search = text_regex.search(text_search)
if text_search is None:
return None, None
text = text_search.group(0) |
from threading import local
from django.conf import settings
from django.core import signals
from django.core.cache.backends.base import (
BaseCache, CacheKeyWarning, InvalidCacheBackendError,
)
from django.utils.module_loading import import_string
__all__ = [
'cache', 'caches', 'DEFAULT_CACHE_ALIAS', 'Invalid... | from threading import local
from django.conf import settings
from django.core import signals
from django.core.cache.backends.base import (
BaseCache, CacheKeyWarning, InvalidCacheBackendError, InvalidCacheKey,
)
from django.utils.module_loading import import_string
__all__ = [
'cache', 'caches', 'DEFAULT_CACHE... |
class CacheKeyWarning(RuntimeWarning):
pass
# Stub class to ensure not passing in a `timeout` argument results in
# the default timeout
DEFAULT_TIMEOUT = object() | class CacheKeyWarning(RuntimeWarning):
pass
class InvalidCacheKey(ValueError):
pass
# Stub class to ensure not passing in a `timeout` argument results in
# the default timeout
DEFAULT_TIMEOUT = object() |
class BaseCache:
backend. This encourages (but does not force) writing backend-portable
cache code.
"""
if len(key) > MEMCACHE_MAX_KEY_LENGTH:
warnings.warn(
'Cache key will cause errors if used with memcached: %r '
'(longer than %s)' % (key, M... | class BaseCache:
backend. This encourages (but does not force) writing backend-portable
cache code.
"""
for warning in memcache_key_warnings(key):
warnings.warn(warning, CacheKeyWarning)
def incr_version(self, key, delta=1, version=None):
""" |
class BaseCache:
def close(self, **kwargs):
"""Close the cache connection"""
pass | class BaseCache:
def close(self, **kwargs):
"""Close the cache connection"""
pass
def memcache_key_warnings(key):
if len(key) > MEMCACHE_MAX_KEY_LENGTH:
yield (
'Cache key will cause errors if used with memcached: %r '
'(longer than %s)' % (key, MEMCACHE_MAX_KEY... |
import pickle
import re
import time
from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache
from django.utils.functional import cached_property
| import pickle
import re
import time
from django.core.cache.backends.base import (
DEFAULT_TIMEOUT, BaseCache, InvalidCacheKey, memcache_key_warnings,
)
from django.utils.functional import cached_property
|
class BaseMemcachedCache(BaseCache):
def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
key = self.make_key(key, version=version)
return self._cache.add(key, value, self.get_backend_timeout(timeout))
def get(self, key, default=None, version=None):
key = self.make_key(key... | class BaseMemcachedCache(BaseCache):
def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
key = self.make_key(key, version=version)
self.validate_key(key)
return self._cache.add(key, value, self.get_backend_timeout(timeout))
def get(self, key, default=None, version=None):
... |
class BaseMemcachedCache(BaseCache):
def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
key = self.make_key(key, version=version)
if not self._cache.set(key, value, self.get_backend_timeout(timeout)):
# make sure the key doesn't keep its old value in case of failure to se... | class BaseMemcachedCache(BaseCache):
def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
key = self.make_key(key, version=version)
self.validate_key(key)
if not self._cache.set(key, value, self.get_backend_timeout(timeout)):
# make sure the key doesn't keep its old... |
class BaseMemcachedCache(BaseCache):
def incr(self, key, delta=1, version=None):
key = self.make_key(key, version=version)
# memcached doesn't support a negative delta
if delta < 0:
return self._cache.decr(key, -delta) | class BaseMemcachedCache(BaseCache):
def incr(self, key, delta=1, version=None):
key = self.make_key(key, version=version)
self.validate_key(key)
# memcached doesn't support a negative delta
if delta < 0:
return self._cache.decr(key, -delta) |
class BaseMemcachedCache(BaseCache):
def decr(self, key, delta=1, version=None):
key = self.make_key(key, version=version)
# memcached doesn't support a negative delta
if delta < 0:
return self._cache.incr(key, -delta) | class BaseMemcachedCache(BaseCache):
def decr(self, key, delta=1, version=None):
key = self.make_key(key, version=version)
self.validate_key(key)
# memcached doesn't support a negative delta
if delta < 0:
return self._cache.incr(key, -delta) |
class BaseMemcachedCache(BaseCache):
original_keys = {}
for key, value in data.items():
safe_key = self.make_key(key, version=version)
safe_data[safe_key] = value
original_keys[safe_key] = key
failed_keys = self._cache.set_multi(safe_data, self.get_backend_tim... | class BaseMemcachedCache(BaseCache):
original_keys = {}
for key, value in data.items():
safe_key = self.make_key(key, version=version)
self.validate_key(safe_key)
safe_data[safe_key] = value
original_keys[safe_key] = key
failed_keys = self._cache.s... |
class BaseMemcachedCache(BaseCache):
def clear(self):
self._cache.flush_all()
class MemcachedCache(BaseMemcachedCache):
"An implementation of a cache binding using python-memcached" | class BaseMemcachedCache(BaseCache):
def clear(self):
self._cache.flush_all()
def validate_key(self, key):
for warning in memcache_key_warnings(key):
raise InvalidCacheKey(warning)
class MemcachedCache(BaseMemcachedCache):
"An implementation of a cache binding using python-mem... |
from unittest import mock
from django.conf import settings
from django.core import management, signals
from django.core.cache import (
DEFAULT_CACHE_ALIAS, CacheKeyWarning, cache, caches,
)
from django.core.cache.utils import make_template_fragment_key
from django.db import close_old_connections, connection, connec... | from unittest import mock
from django.conf import settings
from django.core import management, signals
from django.core.cache import (
DEFAULT_CACHE_ALIAS, CacheKeyWarning, InvalidCacheKey, cache, caches,
)
from django.core.cache.utils import make_template_fragment_key
from django.db import close_old_connections, c... |
class BaseCacheTests:
def _perform_invalid_key_test(self, key, expected_warning):
"""
All the builtin backends (except memcached, see below) should warn on
keys that would be refused by memcached. This encourages portable
caching code without making it too difficult to use productio... | class BaseCacheTests:
def _perform_invalid_key_test(self, key, expected_warning):
"""
All the builtin backends should warn (except memcached that should
error) on keys that would be refused by memcached. This encourages
portable caching code without making it too difficult to use pr... |
class BaseMemcachedTests(BaseCacheTests):
with self.settings(CACHES={'default': params}):
self.assertEqual(cache._servers, ['server1.tld', 'server2:11211'])
def test_invalid_key_characters(self):
"""
On memcached, we don't introduce a duplicate key validation
... | class BaseMemcachedTests(BaseCacheTests):
with self.settings(CACHES={'default': params}):
self.assertEqual(cache._servers, ['server1.tld', 'server2:11211'])
def _perform_invalid_key_test(self, key, expected_warning):
"""
Whilst other backends merely warn, memcach... |
class PyLibMCCacheTests(BaseMemcachedTests, TestCase):
# libmemcached manages its own connections.
should_disconnect_on_close = False
# By default, pylibmc/libmemcached don't verify keys client-side and so
# this test triggers a server-side bug that causes later tests to fail
# (#19914). The `verif... | class PyLibMCCacheTests(BaseMemcachedTests, TestCase):
# libmemcached manages its own connections.
should_disconnect_on_close = False
@override_settings(CACHES=caches_setting_for_tests(
base=PyLibMCCache_params,
exclude=memcached_excluded_caches, |
class Connection(object):
self.user = user
self.password = password
self.private_key_file = private_key_file
self.HASHED_KEY_MAGIC = "|1|"
def connect(self): | class Connection(object):
self.user = user
self.password = password
self.private_key_file = private_key_file
self.cp_dir = utils.prepare_writeable_dir('$HOME/.ansible/cp',mode=0700)
self.HASHED_KEY_MAGIC = "|1|"
def connect(self): |
class Connection(object):
else:
self.common_args += ["-o", "ControlMaster=auto",
"-o", "ControlPersist=60s",
"-o", "ControlPath=/tmp/ansible-ssh-%h-%p-%r"]
if not C.HOST_KEY_CHECKING:
self.common_args += ["-o", "S... | class Connection(object):
else:
self.common_args += ["-o", "ControlMaster=auto",
"-o", "ControlPersist=60s",
"-o", "ControlPath=%s/ansible-ssh-%%h-%%p-%%r" % self.cp_dir]
cp_in_use = False
cp_path_set = False
... |
def is_executable(path):
or stat.S_IXGRP & os.stat(path)[stat.ST_MODE]
or stat.S_IXOTH & os.stat(path)[stat.ST_MODE])
def prepare_writeable_dir(tree):
''' make sure a directory exists and is writeable '''
if tree != '/':
tree = os.path.realpath(os.path.expanduser(tree))
if ... | def is_executable(path):
or stat.S_IXGRP & os.stat(path)[stat.ST_MODE]
or stat.S_IXOTH & os.stat(path)[stat.ST_MODE])
def unfrackpath(path):
'''
returns a path that is free of symlinks, environment
variables, relative path traversals and symbols (~)
example:
'$HOME/../../va... |
class Series(base.IndexOpsMixin, generic.NDFrame):
"""
kwargs["inplace"] = validate_bool_kwarg(kwargs.get("inplace", False), "inplace")
non_mapping = is_scalar(index) or (
is_list_like(index) and not is_dict_like(index)
)
if non_mapping:
return self._set_... | class Series(base.IndexOpsMixin, generic.NDFrame):
"""
kwargs["inplace"] = validate_bool_kwarg(kwargs.get("inplace", False), "inplace")
if callable(index) or is_dict_like(index):
return super().rename(index=index, **kwargs)
else:
return self._set_name(index, inpl... |
class TestSeriesAlterAxes:
expected = Series([1, 2, 3], index=expected_index)
tm.assert_series_equal(result, expected)
def test_set_axis_inplace_axes(self, axis_series):
# GH14636
ser = Series(np.arange(4), index=[1, 3, 5, 7], dtype="int64") | class TestSeriesAlterAxes:
expected = Series([1, 2, 3], index=expected_index)
tm.assert_series_equal(result, expected)
def test_rename_with_custom_indexer(self):
# GH 27814
class MyIndexer:
pass
ix = MyIndexer()
s = Series([1, 2, 3]).rename(ix)
a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.